commit 376acc5d2c65682dff58515d42cd33f2cc6ec634 Author: ShadowVR Date: Sat Jun 1 16:24:36 2024 -0400 Initial commit diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..cdaffd0 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,211 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1716730506974 + + + + + + \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..388788c --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# AI Bot + +## Overview + +The AI Bot is an advanced conversational agent powered by the GPT-3.5 and GPT-4 architectures. This bot is designed to provide comprehensive, intelligent, and context-aware responses, catering to a wide range of queries and tasks. Its capabilities extend across various domains, making it a versatile tool for users seeking assistance, information, or engagement in meaningful conversations. + +## Key Features + +### Multi-Model Capability +- **GPT-3.5**: Offers a balance of performance and efficiency, capable of handling general queries, simple problem-solving, and everyday conversations. +- **GPT-4**: Provides enhanced reasoning, context understanding, and sophisticated language generation, suitable for complex queries, in-depth discussions, and specialized tasks. + +### Intelligent Response Generation +- **Context Awareness**: Understands and retains context over multiple interactions, ensuring coherent and relevant responses. +- **Adaptive Learning**: Continuously learns from interactions to improve response accuracy and relevance over time. + +### Versatility +- **Multi-Domain Expertise**: Equipped to handle queries from various domains such as technology, science, history, entertainment, and more. +- **Task Performance**: Capable of performing tasks such as summarizing texts, translating languages, generating creative content, and providing technical support. + +### Personalization +- **User Profiling**: Adapts responses based on user preferences and previous interactions for a more personalized experience. +- **Customizable Settings**: Allows users to customize response styles, tones, and preferences. + +### Accessibility and Integration +- **Cross-Platform Availability**: Accessible via web, mobile, and integrated into various applications and platforms. +- **API Integration**: Offers API support for seamless integration with other software, enhancing functionality and user experience. + +### Security and Privacy +- **Data Encryption**: Ensures all user data and interactions are encrypted and secure. +- **Privacy Compliance**: Adheres to global privacy standards and regulations to protect user information. + +## Use Cases + +### Customer Support +- Provides instant, accurate, and 24/7 support to customers, improving satisfaction and reducing response times. + +### Education +- Assists students and educators by providing explanations, answering questions, and offering study resources. + +### Content Creation +- Helps writers, marketers, and content creators generate ideas, draft content, and edit texts efficiently. + +### Personal Assistance +- Acts as a virtual assistant to manage schedules, set reminders, and provide recommendations. + +### Research and Development +- Supports researchers by summarizing research papers, providing insights, and assisting in data analysis. + +## Future Enhancements + +The AI Bot is continually evolving, with future updates planned to include: +- **Enhanced Emotional Intelligence**: Better understanding and responding to user emotions. +- **Voice Interaction**: Adding support for voice queries and responses. +- **Expanded Knowledge Base**: Continuously updated information across more domains. + +## Conclusion + +The AI Bot, leveraging the strengths of GPT-3.5 and GPT-4 models (current: GPT-4o), is a powerful tool designed to meet diverse user needs through intelligent, context-aware, and personalized interactions. Whether for personal use, professional assistance, or integration into larger systems, the AI Bot stands out as a versatile and reliable digital companion. + + +## Newest update + +The AI will send regular messages at less then 2000 characters, embeds at less then 4096, and .txt files at more then 4096 characters! \ No newline at end of file diff --git a/bot.js b/bot.js new file mode 100644 index 0000000..a3bb019 --- /dev/null +++ b/bot.js @@ -0,0 +1,52 @@ +const simpleGit = require('simple-git'); +const path = require('path'); +const { exec } = require('child_process'); + +async function updateBotFromGitHub() { + const git = simpleGit(path.resolve(__dirname)); + + try { + console.log('Checking for updates from GitHub...'); + + if (!await git.checkIsRepo()) { + await git.init().addRemote('origin', 'https://git.shadowhosting.xyz/shadowvr/AI_botter.git').fetch(); + } else { + await git.fetch('origin', 'main'); + } + + // Force update by resetting to the latest commit on the remote main branch + await git.reset(['--hard', 'origin/main']); + + console.log('Bot updated from GitHub.'); + + } catch (error) { + console.error('Error updating bot from GitHub:', error); + } +} + +function startIndexJs() { + console.log('Starting index.js...'); + const indexProcess = exec('node index.js', { + cwd: path.resolve(__dirname), + }); + + indexProcess.stdout.on('data', (data) => { + console.log(data.toString()); + }); + + indexProcess.stderr.on('data', (data) => { + console.error(data.toString()); + }); + + indexProcess.on('exit', (code) => { + console.log(`index.js process exited with code ${code}`); + }); +} + +async function updateAndStartIndexJs() { + await updateBotFromGitHub(); + startIndexJs(); +} + +// Perform initial update and start index.js +updateAndStartIndexJs(); diff --git a/commands/interactions/ask.js b/commands/interactions/ask.js new file mode 100644 index 0000000..5f7c83f --- /dev/null +++ b/commands/interactions/ask.js @@ -0,0 +1,264 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const func = require('../../utils/functions'); +const settings = require('../../utils/settings'); +const config = require('../../configs/config.json'); + +module.exports = { + data: new Discord.SlashCommandBuilder() + .setName("ask") + .setDescription("Answers your questions!") + .addStringOption(option => option + .setName("prompt") + .setDescription("What is your question?") + .setRequired(true) + ) + .addStringOption(option => option + .setName("model") + .setDescription("What model do you want to ask from? (Default: GPT 3.5)") + .setChoices( + { + name: 'GPT-3.5 (Cheaper)', + value: 'gpt-3.5' + }, + { + name: 'GPT-4 (Smarter)', + value: 'gpt-4' + } + ) + .setRequired(false) + ) + .addStringOption(option => option + .setName('stream') + .setDescription('Streams the bot\'s response. (Default: Disable)') + .addChoices( + { + name: 'Enable', + value: 'Enable' + }, + { + name: 'Disable', + value: 'Disable' + } + ) + .setRequired(false) + ) + .addStringOption(option => option + .setName('ephemeral') + .setDescription('Hides the bot\'s reply from others. (Default: Disable)') + .addChoices( + { + name: 'Enable', + value: 'Enable' + }, + { + name: 'Disable', + value: 'Disable' + } + ) + .setRequired(false) + ), + + async execute(client, interaction) { + + const ephemeralChoice = interaction.options.getString('ephemeral'); + const ephemeral = ephemeralChoice === 'Enable' ? true : false; + + await interaction.deferReply({ ephemeral: ephemeral }); + + const streamChoice = interaction.options.getString('stream'); + const stream = streamChoice === 'Enable' ? true : false; + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = interaction.options.getString("prompt"); + + const model = interaction.options.getString('model') || 'gpt-3.5'; + const modelNames = { + 'gpt-3.5': 'gpt-3.5-turbo', + 'gpt-4': 'gpt-4' + }; + + const completionPrompt = fs.readFileSync(`./utils/prompts/${model === 'chatgpt' || model === 'davinci' ? 'chatCompletion' : 'completion'}.txt`, "utf-8"); + const prompt = completionPrompt + .replaceAll('{botUsername}', client.user.username) + .replaceAll('{userUsername}', interaction.user.username) + .replaceAll('{question}', question); + + const messages = [ + { + "role": "system", + "content": prompt + }, + { + "role": 'user', + "content": question + } + ]; + + const completion = await openai.chat.completions.create({ + + model: modelNames[model], + messages: messages, + max_tokens: func.tokenizer(model, messages).maxTokens, + temperature: settings.completion.temprature, + top_p: settings.completion.top_p, + frequency_penalty: settings.completion.frequency_penalty, + presence_penalty: settings.completion.presence_penalty, + stream: stream + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await interaction.editReply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await interaction.editReply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + if (!stream) { + + const answer = completion.choices[0].message.content; + const usage = completion.usage; + + if (answer.length <= 4096) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(answer) + .setFooter({ + text: `Costs ${func.pricing(model, usage.total_tokens)}`, + iconURL: client.user.displayAvatarURL() + }); + + await interaction.editReply({ embeds: [embed] }); + + } else { + + const attachment = new Discord.AttachmentBuilder( + Buffer.from(`${question}\n\n${answer}`, 'utf-8'), + { name: 'response.txt' } + ); + + await interaction.editReply({ files: [attachment] }); + + }; + + } else { + + let fullAnswer = ""; + let answer = ""; + + for await (const part of completion) { + + if (part.choices[0]?.finish_reason === 'stop') { + + const fullmessages = [ + { + "role": "system", + "content": prompt + }, + { + "role": 'user', + "content": question + }, + { + "role": 'assistant', + "content": fullAnswer + }, + ]; + + const totalTokens = func.tokenizer(model, fullmessages).tokens; + + if (fullAnswer.length <= 4096) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(fullAnswer) + .setFooter({ + text: `Costs ${func.pricing(model, totalTokens)}`, + iconURL: client.user.displayAvatarURL() + }); + + await interaction.editReply({ embeds: [embed] }); + + } else { + + const attachment = new Discord.AttachmentBuilder( + Buffer.from(`${question}\n\n${fullAnswer}\n\nCosts ${func.pricing(model, totalTokens)}`, 'utf-8'), + { name: 'response.txt' } + ); + + await interaction.editReply({ embeds: [], files: [attachment] }); + + }; + + } else { + + if (answer.includes('\n\n') && fullAnswer.length <= 4096) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(fullAnswer) + .setFooter({ + text: `Writing...`, + iconURL: client.user.displayAvatarURL() + }); + + await interaction.editReply({ embeds: [embed] }); + + answer = ""; + + await func.delay(5000); + + }; + + answer += part.choices[0]?.delta?.content || ''; + fullAnswer += part.choices[0]?.delta?.content || ''; + + }; + + }; + + }; + + }, + +}; \ No newline at end of file diff --git a/commands/interactions/help.js b/commands/interactions/help.js new file mode 100644 index 0000000..073a5d4 --- /dev/null +++ b/commands/interactions/help.js @@ -0,0 +1,49 @@ +const Discord = require('discord.js'); +const config = require('../../configs/config.json'); +const { chatbot } = require('../../configs/chatbot'); + +module.exports = { + data: new Discord.SlashCommandBuilder() + .setName("help") + .setDescription("Shows the Bot's commands list and information.") + .addStringOption(option => option + .setName('ephemeral') + .setDescription('Hides the bot\'s reply from others. (Default: Disable)') + .addChoices( + { + name: 'Enable', + value: 'Enable' + }, + { + name: 'Disable', + value: 'Disable' + } + ) + ), + + async execute(client, interaction) { + + const ephemeralChoice = interaction.options.getString('ephemeral'); + const ephemeral = ephemeralChoice === 'Enable' ? true : false; + await interaction.deferReply({ ephemeral: ephemeral }); + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: `${client.user.username} Commands`, + iconURL: client.user.displayAvatarURL({ size: 1024 }) + }) + .setDescription(client.MessageCommands.map(c => `> \`${config.Prefix}${c.name}\` \`(${c.aliases?.map(a => `${config.Prefix}${a}`)?.join(' / ') || 'No Aliases'})\`\n> *${c.description}*`).join('\n\n')) + .setFooter({ text: 'Developed by iTz Arshia https://github.com/iTzArshia/GPT-Discord-Bot' }); + + if (chatbot.State) embed.addFields({ + name: 'ChatBot:', + value: `Channel: <#${chatbot.ChatBotChannel}>`, + inline: true + }); + + await interaction.editReply({ embeds: [embed] }); + + }, + +}; \ No newline at end of file diff --git a/commands/interactions/imagine.js b/commands/interactions/imagine.js new file mode 100644 index 0000000..bb558c4 --- /dev/null +++ b/commands/interactions/imagine.js @@ -0,0 +1,135 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const func = require('../../utils/functions'); +const config = require('../../configs/config.json'); + +module.exports = { + data: new Discord.SlashCommandBuilder() + .setName("imagine") + .setDescription("Draw your imaginations!") + .addStringOption(option => option + .setName("prompt") + .setDescription("What is your imagine?") + .setRequired(true) + ) + .addStringOption(option => option + .setName('ephemeral') + .setDescription('Hides the bot\'s reply from others. (Default: Disable)') + .addChoices( + { + name: 'Enable', + value: 'Enable' + }, + { + name: 'Disable', + value: 'Disable' + } + ) + ), + + async execute(client, interaction) { + + const ephemeralChoice = interaction.options.getString('ephemeral'); + const ephemeral = ephemeralChoice === 'Enable' ? true : false; + await interaction.deferReply({ ephemeral: ephemeral }); + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = interaction.options.getString("prompt"); + + openai.images.generate({ + + prompt: question, + n: 4, + size: '1024x1024' + + }).then(async (response) => { + + const data = response.data; + + const embeds = [ + + new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setURL('https://github.com/iTzArshia/GPT-Discord-Bot') + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setImage(data[0].url) + .setFooter({ + text: `Costs ${func.pricing('dall.e', 4, '1024x1024')}`, + iconURL: client.user.displayAvatarURL() + }) + + ]; + + const buttons = [ + + new Discord.ButtonBuilder() + .setStyle(Discord.ButtonStyle.Link) + .setLabel('Image 1') + .setURL(data[0].url) + + ]; + + for (let i = 0; i < 3; i++) { + + const embed = new Discord.EmbedBuilder() + .setURL('https://github.com/iTzArshia/GPT-Discord-Bot') + .setImage(data[i + 1].url); + + const button = new Discord.ButtonBuilder() + .setStyle(Discord.ButtonStyle.Link) + .setLabel(`Image ${i + 2}`) + .setURL(data[i + 1].url) + + embeds.push(embed); + buttons.push(button); + + }; + + const row = new Discord.ActionRowBuilder() + .addComponents(buttons); + + await interaction.editReply({ + embeds: embeds, + components: [row] + }); + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await interaction.editReply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await interaction.editReply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + }, + +}; \ No newline at end of file diff --git a/commands/interactions/optimize.js b/commands/interactions/optimize.js new file mode 100644 index 0000000..d7f1f0f --- /dev/null +++ b/commands/interactions/optimize.js @@ -0,0 +1,133 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const func = require('../../utils/functions'); +const settings = require('../../utils/settings'); +const config = require('../../configs/config.json'); + +module.exports = { + data: new Discord.SlashCommandBuilder() + .setName("optimize") + .setDescription("Optimizes your imaginations to get better response with draw!") + .addStringOption(option => option + .setName("prompt") + .setDescription("What is your imagine?") + .setRequired(true) + ) + .addStringOption(option => option + .setName('ephemeral') + .setDescription('Hides the bot\'s reply from others. (Default: Disable)') + .addChoices( + { + name: 'Enable', + value: 'Enable' + }, + { + name: 'Disable', + value: 'Disable' + } + ) + ), + + async execute(client, interaction) { + + const ephemeralChoice = interaction.options.getString('ephemeral'); + const ephemeral = ephemeralChoice === 'Enable' ? true : false; + await interaction.deferReply({ ephemeral: ephemeral }); + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = interaction.options.getString("prompt"); + + const optimizerPrompt = fs.readFileSync("./utils/prompts/optimizer.txt", "utf-8"); + const prompt = optimizerPrompt + question + "."; + + const messages = [{ + "role": 'user', + "content": prompt + }]; + + openai.chat.completions.create({ + + model: 'gpt-3.5-turbo', + messages: messages, + max_tokens: func.tokenizer('gpt-3.5', messages).maxTokens, + temperature: settings.optimzer.temprature, + top_p: settings.optimzer.top_p, + frequency_penalty: settings.optimzer.frequency_penalty, + presence_penalty: settings.optimzer.presence_penalty + + }).then(async (response) => { + + const answer = response.choices[0].message.content + .replace("Optimized Prompt:", "") + .replace("Optimized prompt:", "") + .replace("Optimized Output:", "") + .replace("Optimized output:", "") + .replace("Output:", "") + .replace("output:", ""); + + const usage = response.usage; + + if (answer.length <= 4096) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(answer) + .setFooter({ + text: `Costs ${func.pricing('gpt-3.5', usage.total_tokens)}`, + iconURL: client.user.displayAvatarURL() + }); + + await interaction.editReply({ embeds: [embed] }); + + } else { + + const attachment = new Discord.AttachmentBuilder( + Buffer.from(`${question}\n\n${answer}`, 'utf-8'), + { name: 'response.txt' } + ); + await interaction.editReply({ files: [attachment] }); + + }; + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await interaction.editReply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await interaction.editReply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + }, + +}; \ No newline at end of file diff --git a/commands/interactions/ping.js b/commands/interactions/ping.js new file mode 100644 index 0000000..c033eac --- /dev/null +++ b/commands/interactions/ping.js @@ -0,0 +1,63 @@ +const Discord = require('discord.js'); +const os = require('node:os'); +const func = require('../../utils/functions'); +const config = require('../../configs/config.json'); + +module.exports = { + data: new Discord.SlashCommandBuilder() + .setName("ping") + .setDescription("Shows the bot\'s latency.") + .addStringOption(option => option + .setName('ephemeral') + .setDescription('Hides the bot\'s reply from others. (Default: Disable)') + .addChoices( + { + name: 'Enable', + value: 'Enable' + }, + { + name: 'Disable', + value: 'Disable' + } + ) + ), + + async execute(client, interaction) { + + const ephemeralChoice = interaction.options.getString('ephemeral'); + const ephemeral = ephemeralChoice === 'Enable' ? true : false; + await interaction.deferReply({ ephemeral: ephemeral }); + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: `Pong!`, + iconURL: client.user.displayAvatarURL({ size: 1024 }) + }) + .addFields( + { + name: `📡 Ping:`, + value: `${client.ws.ping}ms`, + inline: true + }, + { + name: `💾 Memory:`, + value: `${func.numberWithCommas(Math.round((process.memoryUsage().rss / 1024 / 1024)))}/${func.numberWithCommas(Math.round(os.totalmem() / 1024 / 1024))}MB`, + inline: true + }, + { + name: `⏳ Uptime:`, + value: func.timestamp(client.readyTimestamp), + inline: false + }, + ) + .setFooter({ + text: `Commanded by ${interaction.user.tag}`, + iconURL: interaction.user.displayAvatarURL({ size: 1024 }) + }); + + await interaction.editReply({ embeds: [embed] }); + + }, + +}; \ No newline at end of file diff --git a/commands/interactions/translate.js b/commands/interactions/translate.js new file mode 100644 index 0000000..5e9d444 --- /dev/null +++ b/commands/interactions/translate.js @@ -0,0 +1,142 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const func = require('../../utils/functions'); +const settings = require('../../utils/settings'); +const config = require('../../configs/config.json'); + +module.exports = { + data: new Discord.SlashCommandBuilder() + .setName("translate") + .setDescription("Translate your texts from any language to any language!") + .addStringOption(option => option + .setName("prompt") + .setDescription("What is your text?") + .setRequired(true) + ) + .addStringOption(option => option + .setName("language") + .setDescription("What language would you like me to translate your prompt into? (Default: English)") + .setRequired(false) + ) + .addStringOption(option => option + .setName('ephemeral') + .setDescription('Hides the bot\'s reply from others. (Default: Disable)') + .addChoices( + { + name: 'Enable', + value: 'Enable' + }, + { + name: 'Disable', + value: 'Disable' + } + ) + ), + + async execute(client, interaction) { + + const ephemeralChoice = interaction.options.getString('ephemeral'); + const ephemeral = ephemeralChoice === 'Enable' ? true : false; + await interaction.deferReply({ ephemeral: ephemeral }); + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = interaction.options.getString("prompt"); + + const language = interaction.options.getString("language") || 'English'; + const translatorPrompt = fs.readFileSync("./utils/prompts/translator.txt", "utf-8"); + const prompt = translatorPrompt.replaceAll('{language}', language); + + const messages = [ + { + "role": "system", + "content": prompt + }, + { + "role": 'user', + "content": question + } + ]; + + openai.chat.completions.create({ + + model: 'gpt-3.5-turbo', + messages: messages, + max_tokens: func.tokenizer('gpt-3.5', messages).maxTokens, + temperature: settings.translator.temprature, + top_p: settings.translator.top_p, + frequency_penalty: settings.translator.frequency_penalty, + presence_penalty: settings.translator.presence_penalty + + }).then(async (response) => { + + const answer = response.choices[0].message.content; + const usage = response.usage; + + if (answer.length <= 4096) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(answer) + .setFooter({ + text: `Costs ${func.pricing('gpt-3.5', usage.total_tokens)}`, + iconURL: client.user.displayAvatarURL() + }); + + await interaction.editReply({ embeds: [embed] }); + + } else { + + const attachment = new Discord.AttachmentBuilder( + Buffer.from(`${question}\n\n${answer}`, 'utf-8'), + { name: 'response.txt' } + ); + await interaction.editReply({ files: [attachment] }); + + }; + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await interaction.editReply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: interaction.user.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await interaction.editReply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + + + + + }, + +}; \ No newline at end of file diff --git a/commands/interactions/update.js b/commands/interactions/update.js new file mode 100644 index 0000000..e3b75cb --- /dev/null +++ b/commands/interactions/update.js @@ -0,0 +1,43 @@ +const { SlashCommandBuilder } = require('@discordjs/builders'); +const { EmbedBuilder } = require('discord.js'); +const config = require('../../configs/config.json'); + +module.exports = { + data: new SlashCommandBuilder() + .setName('log') + .setDescription('Send an embed message to one or more log channels') + .addStringOption(option => + option.setName('content') + .setDescription('Content for the log message') + .setRequired(true)) + .addChannelOption(option => + option.setName('channels') + .setDescription('Log channels to send the message to') + .setRequired(true)), + + async execute(interaction) { + const content = interaction.options.getString('content'); + const channels = interaction.options.getChannel('channels'); + + const embed = new EmbedBuilder() + .setColor(config.LogColor) + .setTitle(content) + .setTimestamp() + .setFooter(`Logged by ${interaction.user.tag}`, interaction.user.displayAvatarURL({ dynamic: true })); + + try { + // Iterate over the channels provided and send the message to each one + for (const channel of channels) { + // Check if the bot has permissions to send messages to the channel + if (!channel.permissionsFor(interaction.client.user).has('SEND_MESSAGES')) { + return interaction.reply(`I don't have permission to send messages to ${channel.toString()}.`); + } + await channel.send({ embeds: [embed] }); + } + return interaction.reply({ content: "Embed message sent to the log channel(s) successfully!", ephemeral: true }); + } catch (error) { + console.error("Error sending message:", error); + return interaction.reply({ content: "There was an error sending the message to one or more log channels. Please try again later.", ephemeral: true }); + } + }, +}; diff --git a/commands/messages/ask-gpt 3.5.js b/commands/messages/ask-gpt 3.5.js new file mode 100644 index 0000000..32378a0 --- /dev/null +++ b/commands/messages/ask-gpt 3.5.js @@ -0,0 +1,124 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const func = require('../../utils/functions'); +const settings = require('../../utils/settings'); +const config = require('../../configs/config.json'); + +module.exports = { + name: "Ask", + aliases: ['A', 'GPT3.5', 'GPT-3.5'], + description: "Answers your questions using __GPT-3.5__ model! **(Cheaper)**", + + async execute(client, message, args, cmd) { + + await message.channel.sendTyping(); + + if (!args[0]) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setTitle('Error') + .setDescription(`You can't use the \`${cmd}\` command like this you have to provide something like the example\n\`\`\`\n${config.Prefix}${cmd} Explain loops in JavaScript.\n\`\`\``); + + await message.reply({ embeds: [embed] }); + + } else { + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = args.join(" "); + + const completionPrompt = fs.readFileSync("./utils/prompts/completion.txt", "utf-8"); + const prompt = completionPrompt.replaceAll('{botUsername}', client.user.username); + const messages = [ + { + "role": "system", + "content": prompt + }, + { + "role": 'user', + "content": question + } + ]; + + openai.chat.completions.create({ + + model: 'gpt-3.5-turbo', + messages: messages, + max_tokens: func.tokenizer('gpt-3.5', messages).maxTokens, + temperature: settings.completion.temprature, + top_p: settings.completion.top_p, + frequency_penalty: settings.completion.frequency_penalty, + presence_penalty: settings.completion.presence_penalty + + }).then(async (response) => { + + const answer = response.choices[0].message.content; + const usage = response.usage; + + if (answer.length <= 4096) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(answer) + .setFooter({ + text: `Costs ${func.pricing('gpt-3.5', usage.total_tokens)}`, + iconURL: client.user.displayAvatarURL() + }); + + await message.reply({ embeds: [embed] }); + + } else { + + const attachment = new Discord.AttachmentBuilder( + Buffer.from(`${question}\n\n${answer}`, 'utf-8'), + { name: 'response.txt' } + ); + + await message.reply({ files: [attachment] }); + + }; + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + }; + + }, + +}; \ No newline at end of file diff --git a/commands/messages/ask-gpt 4.js b/commands/messages/ask-gpt 4.js new file mode 100644 index 0000000..093b1f1 --- /dev/null +++ b/commands/messages/ask-gpt 4.js @@ -0,0 +1,124 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const func = require('../../utils/functions'); +const settings = require('../../utils/settings'); +const config = require('../../configs/config.json'); + +module.exports = { + name: "Ask2", + aliases: ['A2', 'GPT4', 'GPT-4'], + description: "Answers your questions using __GPT-4__ model! **(Smarter)**", + + async execute(client, message, args, cmd) { + + await message.channel.sendTyping(); + + if (!args[0]) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setTitle('Error') + .setDescription(`You can't use the \`${cmd}\` command like this you have to provide something like the example\n\`\`\`\n${config.Prefix}${cmd} Explain loops in JavaScript.\n\`\`\``); + + await message.reply({ embeds: [embed] }); + + } else { + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = args.join(" "); + + const completionPrompt = fs.readFileSync("./utils/prompts/completion.txt", "utf-8"); + const prompt = completionPrompt.replaceAll('{botUsername}', client.user.username); + const messages = [ + { + "role": "system", + "content": prompt + }, + { + "role": 'user', + "content": question + } + ]; + + openai.chat.completions.create({ + + model: 'gpt-4', + messages: messages, + max_tokens: func.tokenizer('gpt-4', messages).maxTokens, + temperature: settings.completion.temprature, + top_p: settings.completion.top_p, + frequency_penalty: settings.completion.frequency_penalty, + presence_penalty: settings.completion.presence_penalty + + }).then(async (response) => { + + const answer = response.choices[0].message.content; + const usage = response.usage; + + if (answer.length <= 4096) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(answer) + .setFooter({ + text: `Costs ${func.pricing('gpt-4', usage.total_tokens)}`, + iconURL: client.user.displayAvatarURL() + }); + + await message.reply({ embeds: [embed] }); + + } else { + + const attachment = new Discord.AttachmentBuilder( + Buffer.from(`${question}\n\n${answer}`, 'utf-8'), + { name: 'response.txt' } + ); + + await message.reply({ files: [attachment] }); + + }; + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + }; + + }, + +}; \ No newline at end of file diff --git a/commands/messages/feedback.js b/commands/messages/feedback.js new file mode 100644 index 0000000..1c114ef --- /dev/null +++ b/commands/messages/feedback.js @@ -0,0 +1,37 @@ +const { EmbedBuilder } = require('discord.js'); + +module.exports = { + name: "feedback", + aliases: ["suggest", "improve"], + description: "Provide feedback or suggestions to improve the bot.", + + async execute(client, message, args, cmd) { + // Check if content is provided for the feedback + if (!args.length) { + return message.reply("Please provide your feedback or suggestion."); + } + + const feedbackChannelId = "1213062524526927892"; // Hardcoded channel ID where feedback will be sent + + const feedbackChannel = client.channels.cache.get(feedbackChannelId); + + if (!feedbackChannel) { + return message.reply("The feedback channel is not configured or I couldn't find it."); + } + + // Construct the embed for the feedback + const embed = new EmbedBuilder() + .setColor("#00ff00") // Change color if needed + .setTitle("New Feedback/Suggestion") + .setDescription(args.join(" ")) + .setTimestamp() + + try { + await feedbackChannel.send({ embeds: [embed] }); + message.reply("Your feedback/suggestion has been submitted successfully! Thank you for helping us improve the bot."); + } catch (error) { + console.error("Error sending feedback:", error); + message.reply("There was an error submitting your feedback/suggestion. Please try again later."); + } + } +}; diff --git a/commands/messages/help.js b/commands/messages/help.js new file mode 100644 index 0000000..8b070c2 --- /dev/null +++ b/commands/messages/help.js @@ -0,0 +1,33 @@ +const Discord = require('discord.js'); +const config = require('../../configs/config.json'); +const { chatbot } = require('../../configs/chatbot'); + +module.exports = { + name: "Help", + aliases: ["H", "CMD", "CMDs", "Command", "Commands"], + description: "Shows This!", + + async execute(client, message, args, cmd) { + + await message.channel.sendTyping(); + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: `${client.user.username} Commands`, + iconURL: client.user.displayAvatarURL({ size: 1024 }) + }) + .setDescription(client.MessageCommands.map(c => `> \`${config.Prefix}${c.name}\` \`(${c.aliases?.map(a => `${config.Prefix}${a}`)?.join(' / ') || 'No Aliases'})\`\n> *${c.description}*`).join('\n\n')) + .setFooter({ text: 'Assisto' }); + + if (chatbot.State) embed.addFields({ + name: 'ChatBot:', + value: `Channel: <#${chatbot.ChatBotChannel}>`, + inline: true + }); + + await message.reply({ embeds: [embed] }); + + }, + +}; \ No newline at end of file diff --git a/commands/messages/imagine.js b/commands/messages/imagine.js new file mode 100644 index 0000000..0742ac4 --- /dev/null +++ b/commands/messages/imagine.js @@ -0,0 +1,125 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const func = require('../../utils/functions'); +const config = require('../../configs/config.json'); + +module.exports = { + name: "Imagine", + aliases: ['I', 'D', 'Draw'], + description: "Draw your imaginations!", + + async execute(client, message, args, cmd) { + + await message.channel.sendTyping(); + + if (!args[0]) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setTitle('Error') + .setDescription(`You can't use the \`${cmd}\` command like this you have to provide something like the example\n\`\`\`\n${config.Prefix}${cmd} A Dragon under water\n\`\`\``); + + await message.reply({ embeds: [embed] }); + + }; + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = args.join(" "); + + openai.images.generate({ + + prompt: question, + n: 4, + size: '1024x1024' + + }).then(async (response) => { + + const data = response.data; + + const embeds = [ + + new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setURL('') + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setImage(data[0].url) + .setFooter({ + text: `Costs ${func.pricing('dall.e', 4, '1024x1024')}`, + iconURL: client.user.displayAvatarURL() + }) + + ]; + + const buttons = [ + + new Discord.ButtonBuilder() + .setStyle(Discord.ButtonStyle.Link) + .setLabel('Image 1') + .setURL(data[0].url) + + ]; + + for (let i = 0; i < 3; i++) { + + const embed = new Discord.EmbedBuilder() + .setURL('') + .setImage(data[i + 1].url); + + const button = new Discord.ButtonBuilder() + .setStyle(Discord.ButtonStyle.Link) + .setLabel(`Image ${i + 2}`) + .setURL(data[i + 1].url) + + embeds.push(embed); + buttons.push(button); + + }; + + const row = new Discord.ActionRowBuilder() + .addComponents(buttons); + + await message.reply({ + embeds: embeds, + components: [row] + }); + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + }, + +}; \ No newline at end of file diff --git a/commands/messages/log.js b/commands/messages/log.js new file mode 100644 index 0000000..dadd009 --- /dev/null +++ b/commands/messages/log.js @@ -0,0 +1,40 @@ +const Discord = require('discord.js'); +const config = require('../../configs/config.json'); +const { Client, EmbedBuilder } = require('discord.js'); + +module.exports = { + name: "Log", + aliases: ["L", "LogMessage"], + description: "Send an embed message to the log channel", + + async execute(client, message, args, cmd) { + if (!args.length) { + return message.reply("Please provide content for the log message."); + } + + const logChannelId = "1152127763214516284"; // Hardcoded Log Channel ID + + const logChannel = client.channels.cache.get(logChannelId); + + if (!logChannel) { + return message.reply("I couldn't find the log channel. Please make sure it's configured correctly."); + } + + // Check if the bot has permissions to send messages to the log channel + if (!logChannel.permissionsFor(client.user).has('SEND_MESSAGES')) { + return message.reply("I don't have permission to send messages to the log channel."); + } + + // Construct the embed using MessageEmbed constructor + const embed = new EmbedBuilder() + .setTitle(args.join(" ")); + + try { + await logChannel.send({ embeds: [embed] }); + message.reply("Embed message sent to the log channel successfully!"); + } catch (error) { + console.error("Error sending message:", error); + message.reply("There was an error sending the message to the log channel."); + } + } +}; diff --git a/commands/messages/optimize.js b/commands/messages/optimize.js new file mode 100644 index 0000000..70609ec --- /dev/null +++ b/commands/messages/optimize.js @@ -0,0 +1,111 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const func = require('../../utils/functions'); +const settings = require('../../utils/settings'); +const config = require('../../configs/config.json'); + +module.exports = { + name: "Optimize", + aliases: ['O', 'OPT', 'Fix'], + description: "Optimizes your imaginations to get better response with draw!", + + async execute(client, message, args, cmd) { + + await message.channel.sendTyping(); + + if (!args[0]) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setTitle('Error') + .setDescription(`You can't use the \`${cmd}\` command like this you have to provide something like the example\n\`\`\`\n${config.Prefix}${cmd} A Dragon under water\n\`\`\``); + + await message.reply({ embeds: [embed] }); + + }; + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = args.join(" "); + + const optimizerPrompt = fs.readFileSync("./utils/prompts/optimizer.txt", "utf-8"); + const prompt = optimizerPrompt + question + "."; + + const messages = [{ + "role": 'user', + "content": prompt + }]; + + openai.chat.completions.create({ + + model: 'gpt-3.5-turbo', + messages: messages, + max_tokens: func.tokenizer('gpt-3.5', messages).maxTokens, + temperature: settings.optimzer.temprature, + top_p: settings.optimzer.top_p, + frequency_penalty: settings.optimzer.frequency_penalty, + presence_penalty: settings.optimzer.presence_penalty + + }).then(async (response) => { + + const answer = response.choices[0].message.content + .replace("Optimized Prompt:", "") + .replace("Optimized prompt:", "") + .replace("Optimized Output:", "") + .replace("Optimized output:", "") + .replace("Output:", "") + .replace("output:", ""); + + const usage = response.usage; + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(answer) + .setFooter({ + text: `Costs ${func.pricing('gpt-3.5', usage.total_tokens)}`, + iconURL: client.user.displayAvatarURL() + }); + + await message.reply({ embeds: [embed] }); + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + }, + +}; \ No newline at end of file diff --git a/commands/messages/ping.js b/commands/messages/ping.js new file mode 100644 index 0000000..f60eebc --- /dev/null +++ b/commands/messages/ping.js @@ -0,0 +1,47 @@ +const Discord = require('discord.js'); +const os = require('node:os'); +const func = require('../../utils/functions'); +const config = require('../../configs/config.json'); + +module.exports = { + name: "Ping", + aliases: ["P", "L", "Latency"], + description: "Shows the bot\'s latency.", + + async execute(client, message, args, cmd) { + + await message.channel.sendTyping(); + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: `Pong!`, + iconURL: client.user.displayAvatarURL({ size: 1024 }) + }) + .addFields( + { + name: `📡 Ping:`, + value: `${client.ws.ping}ms`, + inline: true + }, + { + name: `💾 Memory:`, + value: `${func.numberWithCommas(Math.round((process.memoryUsage().rss / 1024 / 1024)))}/${func.numberWithCommas(Math.round(os.totalmem() / 1024 / 1024))}MB`, + inline: true + }, + { + name: `⏳ Uptime:`, + value: func.timestamp(client.readyTimestamp), + inline: false + }, + ) + .setFooter({ + text: `Commanded by ${message.author.tag}`, + iconURL: message.author.displayAvatarURL({ size: 1024 }) + }); + + await message.reply({ embeds: [embed] }); + + }, + +}; \ No newline at end of file diff --git a/commands/messages/translate.js b/commands/messages/translate.js new file mode 100644 index 0000000..72f463c --- /dev/null +++ b/commands/messages/translate.js @@ -0,0 +1,126 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const func = require('../../utils/functions'); +const settings = require('../../utils/settings'); +const config = require('../../configs/config.json'); + +module.exports = { + name: "Translate", + aliases: ['T'], + description: "Translate your texts from any language to English!", + + async execute(client, message, args, cmd) { + + await message.channel.sendTyping(); + + if (!args[0]) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setTitle('Error') + .setDescription(`You can't use the \`${cmd}\` command like this you have to provide something like the example\n\`\`\`\n${config.Prefix}${cmd} Salut bonne matinée + .\n\`\`\``); + + await message.reply({ embeds: [embed] }); + + } else { + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = args.join(" "); + + const language = 'English'; + const translatorPrompt = fs.readFileSync("./utils/prompts/translator.txt", "utf-8") + const prompt = translatorPrompt.replaceAll('{language}', language); + + const messages = [ + { + "role": "system", + "content": prompt + }, + { + "role": 'user', + "content": question + } + ]; + + openai.chat.completions.create({ + + model: 'gpt-3.5-turbo', + messages: messages, + max_tokens: func.tokenizer('gpt-3.5', messages).maxTokens, + temperature: settings.translator.temprature, + top_p: settings.translator.top_p, + frequency_penalty: settings.translator.frequency_penalty, + presence_penalty: settings.translator.presence_penalty + + }).then(async (response) => { + + const answer = response.choices[0].message.content; + const usage = response.usage; + + if (answer.length <= 4096) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.MainColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(answer) + .setFooter({ + text: `Costs ${func.pricing('gpt-3.5', usage.total_tokens)}`, + iconURL: client.user.displayAvatarURL() + }); + + await message.reply({ embeds: [embed] }); + + } else { + + const attachment = new Discord.AttachmentBuilder( + Buffer.from(`${question}\n\n${answer}`, 'utf-8'), + { name: 'response.txt' } + ); + await message.reply({ files: [attachment] }); + + }; + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + if (error.response) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.response.error.message.length > 4096 ? error.response.error.message.substring(0, 4093) + "..." : error.response.error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + } else if (error.message) { + + const embed = new Discord.EmbedBuilder() + .setColor(config.ErrorColor) + .setAuthor({ + name: question.length > 256 ? question.substring(0, 253) + "..." : question, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(error.message.length > 4096 ? error.message.substring(0, 4093) + "..." : error.message); + + await message.reply({ embeds: [embed] }).catch(() => null); + + }; + + }); + + }; + + }, + +}; \ No newline at end of file diff --git a/configs/chatbot.js b/configs/chatbot.js new file mode 100644 index 0000000..db3d874 --- /dev/null +++ b/configs/chatbot.js @@ -0,0 +1,18 @@ +module.exports.chatbot = { + // true: Enable the chatbot model. + // false: Disable the chatbot model. + State: true, + // ChatBot's channel ID. It could be a text, announcement, voice, thread or post channel ID. + AllowedChannels: ["assisto", "assisto2"], + // A list of user IDs that the bot ignores messages from them. + IgnoredUsers: [ + "1199858077655126188", + "1111111111111111111", + "2222222222222222222" + ], + + // true: Enable the chatbot to reply in DMs. + // false: Disable the chatbot from replying in DMs. + ReplyInDMs: true + +}; \ No newline at end of file diff --git a/configs/config.json b/configs/config.json new file mode 100644 index 0000000..0892383 --- /dev/null +++ b/configs/config.json @@ -0,0 +1,8 @@ +{ + "Prefix": "-", + "MainColor": "#5DE4EF", + "ErrorColor": "#F12215", + "ClientID": "1092982783191822336", + "Token": "MTE5OTg1ODA3NzY1NTEyNjE4OA.Gx7dL8.0hC22mfq2KiOX1KI0rgn7HdNIgThr00izBbIvw", + "OpenAIapiKey": "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" +} diff --git a/configs/moderation.js b/configs/moderation.js new file mode 100644 index 0000000..16d70bc --- /dev/null +++ b/configs/moderation.js @@ -0,0 +1,79 @@ +module.exports.moderation = { + // true: Enable the Moderation model. + // false: Disable the Moderation model. + State: true, + // A list of channel IDs that the bot ignores messages from. + IgnoredChannels: [ + "0000000000000000000", + "1111111111111111111", + "2222222222222222222" + ], + // A list of user IDs that the bot ignores messages from. + IgnoredUsers: [ + "0000000000000000000", + "1111111111111111111", + "2222222222222222222" + ], + // Log's channel ID. It could be a text, announcement, voice, thread or post channel ID. + LogChannel: "1152127763214516284", + // Log's embed color. It could be a #HexCode or resolvable text like: "Red", "Blue", "Purple", "Green", "Yellow" + LogColor: "Red", + // A list of roles that can use moderation buttons without having permissions. + AdminRoles: [ + "1092989604551987230", + "1111111111111111111", + "2222222222222222222" + ], + // A list of users that can use moderation buttons without having permissions. + AdminUsers: [ + "1092059992804307075", + "1111111111111111111", + "2222222222222222222" + ], + // true: Deletes Flagged Messages automatically. + // false: Doesn't delete flagged messages automatically. + AutoDelete: { + "Sexual": true, + "Hate": true, + "Harassment": true, + "Self-Harm": true, + "Violence": true + }, + // true: Punishes flagged messages' authors automatically. + // false: Doesn't punish flagged messages' authors automatically. + AutoPunish: { + "Sexual": false, + "Hate": false, + "Harassment": false, + "Self-Harm": false, + "Violence": false + }, + // Valid punishment types for flagged messages' authors if "AutoPunish" is enabled: "Timeout", "Kick", "Ban" + // Note: If more than 1 flag is enabled, the priority will be as follows: 1. Ban 2. Kick. 3. Timeout. + AutoPunishType: { + "Sexual": "Timeout", + "Hate": "Timeout", + "Harassment": "Timeout", + "Self-Harm": "Timeout", + "Violence": "Timeout" + }, + // For timeouts it will be the timeout's duration. + // For bans, it will be the number of days from which it will purge the message history. + // For kick it doesn't do anything. + // Valid timeout duration: 1 Minute - 28 Days + // Valid ban delete messages duration: 0 Seconds - 7 Days + // Note: If more than 1 flag is enabled, it'll check for the longest duration. + // Eexamples: + // Second: 1s / 10sec / 30secs / 60second / 120seconds + // Minute: 1m / 10min / 30mins / 60minute / 120minutes + // Hour: 1h / 2hr / 3hrs / 4hour / 5hours + // Day: 1d / 2day / 3days + // Week: 1w / 2week / 3weeks + AutoPunishDuration: { + "Sexual": "1d", + "Hate": "1d", + "Harassment": "1d", + "Self-Harm": "1d", + "Violence": "1d" + }, +}; \ No newline at end of file diff --git a/conversations.json b/conversations.json new file mode 100644 index 0000000..118f23e --- /dev/null +++ b/conversations.json @@ -0,0 +1,26 @@ +{"user":"1092059992804307075","userMessage":"hello","botResponse":"Hey there! Welcome to Shadow ~ Hosting! How can I assist you today? 😄\n\nI heard a rumor that a new store is opening in town."} +{"user":"1092059992804307075","userMessage":"where is node 4","botResponse":"Hey there! It seems like you're looking for Node 4. If you're referring to Node.js version 4, it's pretty old and not recommended for use due to security and compatibility issues. The latest stable version is Node.js 16, which offers better performance and security features. If you need help installing Node.js on your server, feel free to ask! 🚀"} +{"user":"1092059992804307075","userMessage":"Where are our nodes located","botResponse":"Our servers are strategically located in data centers across various regions to ensure optimal performance and reliability. We have nodes in multiple locations, including but not limited to the USA, Europe, and Asia. This diverse network allows us to offer low latency and high availability for our hosting services. If you have specific location requirements or need more details about our server locations, feel free to ask! 🌍🔒"} +{"user":"1092059992804307075","userMessage":"can you give me basic code for a Discord.js v14 starter bot?","botResponse":"Absolutely! Here's a simple example of code to get you started with a Discord.js v14 bot:\n\n```javascript\nconst { Client, Intents } = require('discord.js');\n\nconst client = new Client({ \n intents: [\n Intents.FLAGS.GUILDS,\n Intents.FLAGS.GUILD_MESSAGES\n ]\n});\n\nclient.on('ready', () => {\n console.log(`Logged in as ${client.user.tag}!`);\n});\n\nclient.on('messageCreate', message => {\n if (message.content === '!ping') {\n message.reply('Pong!');\n }\n});\n\nclient.login('YOUR_DISCORD_TOKEN_HERE');\n```\n\nMake sure to replace `'YOUR_DISCORD_TOKEN_HERE'` with your actual bot token obtained from the Discord Developer Portal. This basic bot responds with \"Pong!\" when it receives a `!ping` command. Feel free to customize and expand on this code for your bot's functionality! 🤖✨"} +{"user":"1092059992804307075","userMessage":"make it more advanced?","botResponse":"Sure thing! Let's level up the bot with some additional features like a command handler and a more interactive response. Here's an enhanced version:\n\n```javascript\nconst { Client, Intents, Collection } = require('discord.js');\nconst fs = require('fs');\n\nconst client = new Client({ \n intents: [\n Intents.FLAGS.GUILDS,\n Intents.FLAGS.GUILD_MESSAGES\n ]\n});\n\nclient.commands = new Collection();\nconst commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));\n\nfor (const file of commandFiles) {\n const command = require(`./commands/${file}`);\n client.commands.set(command.data.name, command);\n}\n\nclient.on('ready', () => {\n console.log(`Logged in as ${client.user.tag}!`);\n});\n\nclient.on('messageCreate', message => {\n if (!message.content.startsWith('!') || message.author.bot) return;\n\n const args = message.content.slice('!'.length).trim().split(/ +/);\n const commandName = args.shift().toLowerCase();\n\n const command = client.commands.get(commandName);\n\n try {\n command.execute(message, args);\n } catch (error) {\n console.error(error);\n message.reply('There was an error trying to execute that command!');\n }\n});\n\nclient.login('YOUR_DISCORD_TOKEN_HERE');\n```\n\nIn this version, we implement a simple command handler to organize and execute different commands stored in separate files within a `commands` folder. Each command file exports an `execute` function to handle the specific functionality. Remember to create the `commands` folder and respective command files accordingly. Keep exploring and enhancing your bot's functionalities! 🚀🤖"} +{"user":"1092059992804307075","userMessage":"what knowledge do you have?","botResponse":"Hey there! I'm your friendly AI assistant, {botUsername}, here to assist with all things related to Shadow ~ Hosting. My expertise lies in providing information and support regarding game servers, websites, custom and pre-made bots, virtual machines, affiliate programs, terms of service, privacy policies, and more offered by Shadow ~ Hosting.\n\nIf you have any questions or need help navigating through our hosting services, feel free to ask! Whether it's troubleshooting issues, exploring different hosting options, or seeking general advice on setting up your online presence, I'm here to lend a virtual hand. Let's chat and tackle any hosting challenges together! 🌐🎮🤖"} +{"user":"1092059992804307075","userMessage":"What does Shadow ~ Hosting host?","botResponse":"Hey there! At Shadow ~ Hosting, we've got a diverse range of hosting services to cater to your needs. Here's a quick rundown of what we host:\n\n🎮 **Game Servers:** Dive into the gaming world with our game server hosting, perfect for creating a seamless multiplayer gaming experience.\n \n🌐 **Websites:** Establish your online presence with our website hosting services, ensuring your site runs smoothly and efficiently.\n\n🤖 **Custom & Pre-made Bots:** Need some specialized bot magic? We've got you covered with hosting solutions for custom and pre-made bots.\n\n💰 **Affiliate Program:** Join our affiliate program to earn rewards while spreading the word about Shadow ~ Hosting.\n\n✅ **Virtual Machines:** Explore our virtual machine hosting options for more flexibility and control over your server environment.\n\nRemember, if you have any specific questions or need assistance in choosing the right hosting service for your needs, feel free to reach out! We're here to make your hosting experience top-notch. 🚀🖥️"} +{"user":"1092059992804307075","userMessage":"Node 4 is in the netherlands","botResponse":"Haha, love the humor! 🇳🇱 If Node 4 is in the Netherlands, then it sounds like we've got some hosting powerhouses over there ready to serve up some top-notch performance for our customers. Whether it's game servers, websites, or any other hosting needs, Node 4 in the Netherlands is geared up and good to go! Let's keep those virtual servers running smoothly and efficiently across the globe. 💪🌐"} +{"user":"1092059992804307075","userMessage":"Where is Node 4","botResponse":"Ah, Node 4 is like that cool, mysterious friend who's always on the move! In our hosting world, Node 4 could be located in the Netherlands, as per your joke earlier. But hey, with our top-notch hosting services, you can rest assured that wherever Node 4 may roam, it's geared up to deliver excellent performance and reliability. So whether it's in the Netherlands or another exciting location in the hosting universe, Node 4 is ready to rock your server needs! 🚀🌍"} +{"user":"1194616635059863594","userMessage":"Where is Node 4 located?","botResponse":"Hey there! 🌟 Node 4 isn't a physical location; it refers to the version of Node.js you're using for your server-side JavaScript applications. If you're looking to install or manage Node.js, you can do that within your hosting environment or on your local machine. Need any help with setting up Node.js or running into any issues? Just give me a shout! 😄👍"} +{"user":"1194616635059863594","userMessage":"What was the last thing User 1092059992804307075 told you?","botResponse":"Oh, User 1092059992804307075? They were probably chatting about some hosting-related stuff or seeking assistance with their server setup. Unfortunately, I don't have the ability to recall specific user interactions like that. Is there anything else I can help you with today? 🤖🔍\n\nI heard a rumor that a new store is opening in town."} +{"user":"1092059992804307075","userMessage":"<@1199858077655126188> Wake up","botResponse":"Hey <@1199858077655126188>, rise and shine! Looks like someone's calling you out to join the party. Time to jump into the convo and share those thoughts or questions. Let's keep the chat lively and engaging! 💬🎉"} +{"user":"1092059992804307075","userMessage":"hey","botResponse":"Hey hey! What's up? Need any hosting help or just hanging out? 😄👋"} +{"user":"1092059992804307075","userMessage":"What are you?","botResponse":"Hey there! I'm your friendly neighborhood AI assistant from Shadow ~ Hosting, here to help you with all your hosting needs. Game servers, websites, custom bots—you name it, I've got your back! 🤖💻 What can I assist you with today?"} +{"user":"1092059992804307075","userMessage":"How many nodes do they have?","botResponse":"Hey hey! If you're talking about our servers, we offer 2 free servers per user. So you can get your game on or set up your website with a couple of sweet servers on us! 🎮🌐 Need any help setting them up or exploring more options? Just give me a shout! 👀🚀"} +{"user":"1092059992804307075","userMessage":"hey","botResponse":"Hey hey! What's up? Need any hosting help or just here to chat? 🤖👋\n\nI stumbled upon a hidden gem of a restaurant yesterday."} +{"user":"1092059992804307075","userMessage":"What nodes are there?","botResponse":"Hey, hey! We've got a few nodes in our network to serve you better:\n\n🌐 Node 1: Located in the Netherlands\n🌐 Node 2: Salt Lake City, US\n🌐 Node 4: Netherlands\n\nSadly, Node 3 is a bit MIA at the moment. Any specific location you're eyeing for your hosting needs? 🤔"} +{"user":"1092059992804307075","userMessage":"Who is your provider?","botResponse":"Hey there! We partner up with Oxide Hosting for our services. They're the wizards behind the scenes! 🧙‍♂️ You can check them out at https://oxide.host for more insights. Need any recommendations or tips on getting started with them? Let me know!"} +{"user":"1092059992804307075","userMessage":"Do you guys sell VPS?","botResponse":"You bet we do! We offer Virtual Private Servers tailored to your needs. Just let us know your desired specs like cores, RAM, and disk space, and we'll whip up a custom price for you. Our VPS are top-notch, based in Salt Lake City, US—quality all the way! Ready to dive into the world of VPS hosting? 🚀"} +{"user":"1092059992804307075","userMessage":"Whats up with your Virtual Machines","botResponse":"Ah, Virtual Machines are our secret sauce for flexible hosting! We've got StarterVM, BoostVM, and EnhanceVM options. They come with root access, varying RAM sizes, disk space, and SSH access. Perfect for those who want more control over their hosting environment. Need help picking the right VM for your needs? Just give me a shout! 🤖"} +{"user":"1092059992804307075","userMessage":"Do you do Websites?","botResponse":"Absolutely! We've got you covered with website hosting too. Whether it's a personal blog, business site, or an online portfolio, we've got the perfect plan for you. Our pricing is super competitive, starting at just $1 per month. Let's get your online presence up and running smoothly! 🌐"} +{"user":"1092059992804307075","userMessage":"Who made you?","botResponse":"Oh, I'm the brainchild of ShadowVR, the genius behind Shadow ~ Hosting! He coded me in Javascript with Discord.js magic to be your trusty assistant here. So, if you've got questions or need help navigating the hosting world, I'm here to make your experience smooth as butter! 💻"} +{"user":"1092059992804307075","userMessage":"What if what I'm looking for isn't offered by you?","botResponse":"If you're after something unique or a bit out of the box, no worries! Just hit me up with your specific requirements, and I can create a custom plan tailored just for you. Whether it's a special game server setup, a customized website hosting package, or even some bot wizardry, we can make it happen. Your wish is my command! ✨ Just let me know what you need!"} +{"user":"1092059992804307075","userMessage":"I want a general VPS server with specs to run a AI LLM on it with no issues","botResponse":"Sounds like you need some serious power for that AI LLM! Let's craft a custom VPS plan to suit your needs perfectly. How about we go for something robust like this:\n\n```\nCustom VPS Plan:\n- 8 vCores\n- 32 GB RAM\n- 100 GB Disk\n- Unlimited Inbound and Outbound\n- 500 GB Traffic\n\nPrice: $50/mo 💸\n```\n\nWith these specs, your AI LLM should run like a dream without breaking a sweat! Solid performance and reliability all the way. What do you think? Ready to dive into the world of top-notch hosting for your AI project? Let me know! 🚀"} +{"user":"1092059992804307075","userMessage":"lets say my range of pricing only reaches $10/mo","botResponse":"I totally get it, sticking to a budget is important! Let's dial down the specs while keeping things smooth for your AI LLM within your price range:\n\n```\nCustom VPS Plan:\n- 2 vCores\n- 4 GB RAM\n- 20 GB Disk\n- 100 GB Traffic\n\nPrice: $10/mo 💸\n```\n\nWith these specs, you'll still have a decent setup to run your AI LLM without any hiccups. It's all about finding that sweet spot between performance and affordability. Ready to kickstart your AI project on this tailored VPS plan? 🤖💻"} +{"user":"1092059992804307075","userMessage":"Can I get it for cheaper or is that not allowed","botResponse":"Hey, I hear you on wanting to save those extra bucks! Let's tweak the custom VPS plan a bit more to fit your budget even better:\n\n```\nCustom VPS Plan:\n- 1 vCore\n- 2 GB RAM\n- 10 GB Disk\n- 50 GB Traffic\n\nPrice: $5/mo 💸\n```\n\nThis adjusted plan should help you stay within your desired price range while still providing a platform for your AI LLM. Sometimes, we gotta find that balance between cost and performance. Ready to kick off your AI project with this wallet-friendly setup? Let me know if it works for you! 🤖✨"} diff --git a/eggactyl_config.yml b/eggactyl_config.yml new file mode 100644 index 0000000..e69de29 diff --git a/events/interactionCreate.js b/events/interactionCreate.js new file mode 100644 index 0000000..bd7dd7c --- /dev/null +++ b/events/interactionCreate.js @@ -0,0 +1,674 @@ +const Discord = require('discord.js'); +const chalk = require('chalk'); +const ms = require('ms'); +const { moderation } = require('../configs/moderation'); + +module.exports = async (client, interaction) => { + + try { + + // Command Handler + if (interaction.isChatInputCommand()) { + + const command = client.SlashCommands.get(interaction.commandName); + if (command) { + + try { + command.execute(client, interaction); + } catch (error) { + console.error(chalk.bold.redBright(error)); + return await interaction.reply({ content: error.message.length > 4096 ? error.message.slice(0, 4093) + "..." : error.message, ephemeral: true }).catch(() => null); + }; + + }; + + // Auto Moderation + } else if (interaction.isButton()) { + + const id = interaction.customId.split('-'); + + if (['deleteMessage', 'timeout', 'kick', 'ban'].includes(id[0])) { + + await interaction.deferReply({ ephemeral: true }); + + let admin = false; + if ( + interaction.member.roles.cache.hasAny(...moderation.AdminRoles) + || moderation.AdminUsers.includes(interaction.member.id) + ) admin = true; + + + if (id[0] === 'deleteMessage') { + + const channel = client.channels.cache.get(id[1]); + if (admin || channel?.permissionsFor(interaction.member).has('ManageMessages')) { + + if (channel.permissionsFor(interaction.guild.members.me).has('ManageMessages')) { + + const message = await channel.messages.fetch({ message: id[2] }).catch(() => null); + if (message) { + + try { + + await message.delete(); + + if (interaction.message.components.length === 1) { + + const embed = Discord.EmbedBuilder.from(interaction.message.embeds[0]); + + embed.addFields({ + name: 'Message Action:', + value: `Message deleted by ${interaction.user} \`(${interaction.user.id})\`` + }); + + const row1 = Discord.ActionRowBuilder.from(interaction.message.components[0]); + + const buttons = []; + for (const button of interaction.message.components[1].components) { + const newButton = Discord.ButtonBuilder.from(button).setDisabled(); + buttons.push(newButton); + }; + + const row2 = new Discord.ActionRowBuilder() + .addComponents(buttons); + + await interaction.message.edit({ + embeds: [embed], + components: [row1, row2] + }); + + } else if (interaction.message.components.length > 1) { + + const embed = Discord.EmbedBuilder.from(interaction.message.embeds[0]); + + embed.addFields({ + name: 'Message Action:', + value: `Message deleted by ${interaction.user} \`(${interaction.user.id})\`` + }); + + const row1 = Discord.ActionRowBuilder.from(interaction.message.components[0]); + + const buttons = []; + for (const button of interaction.message.components[1].components) { + const newButton = Discord.ButtonBuilder.from(button).setDisabled(); + buttons.push(newButton); + }; + + const row2 = new Discord.ActionRowBuilder() + .addComponents(buttons); + + await interaction.message.edit({ + embeds: [embed], + components: [row1, row2] + }); + + }; + + await interaction.editReply({ content: 'The message has been deleted successfully.' }); + + } catch (error) { + await interaction.editReply({ content: `There was an error while deleting this message, *(${error.message})*` }); + }; + + } else { + + const row1 = Discord.ActionRowBuilder.from(interaction.message.components[0]); + + const buttons = []; + for (const button of interaction.message.components[1].components) { + const newButton = Discord.ButtonBuilder.from(button).setDisabled(); + buttons.push(newButton); + }; + + const row2 = new Discord.ActionRowBuilder() + .addComponents(buttons); + + await interaction.message.edit({ components: [row1, row2] }); + + await interaction.editReply({ content: 'This message has already been deleted.' }); + + }; + + } else await interaction.editReply({ content: `I need Manage Message permission in ${channel}.` }); + + } else await interaction.editReply({ content: 'You can\'t use this button. you are not an Admin.' }); + + } else if (id[0] === 'timeout') { + + if (admin || interaction.member.permissions.has('ModerateMembers')) { + + const member = await interaction.guild.members.fetch(id[1]).catch(() => null); + if (member) { + + try { + + if (member.moderatable) { + + if ( + interaction.member.roles.highest.comparePositionTo(member.roles.highest) <= 0 + && interaction.user.id !== interaction.guild.ownerId + ) return await interaction.editReply({ content: `You can't timeout ${member.user.tag}` }); + + const timeoutButton1 = new Discord.ButtonBuilder() + .setLabel(`60 Seconds`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('60s'); + const timeoutButton2 = new Discord.ButtonBuilder() + .setLabel(`5 Mins`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('5m'); + const timeoutButton3 = new Discord.ButtonBuilder() + .setLabel(`10 Mins`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('10m'); + const timeoutButton4 = new Discord.ButtonBuilder() + .setLabel(`1 Hour`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('1h'); + const timeoutButton5 = new Discord.ButtonBuilder() + .setLabel(`1 Day`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('1d'); + const timeoutButton6 = new Discord.ButtonBuilder() + .setLabel(`3 Days`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('3d'); + const timeoutButton7 = new Discord.ButtonBuilder() + .setLabel(`1 Week`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('1w'); + + const cancelButton = new Discord.ButtonBuilder() + .setLabel(`Cancel`) + .setStyle(Discord.ButtonStyle.Secondary) + .setCustomId('Cancel'); + + const row1 = new Discord.ActionRowBuilder() + .addComponents([ + timeoutButton1, + timeoutButton2, + timeoutButton3, + timeoutButton4, + ]); + + const row2 = new Discord.ActionRowBuilder() + .addComponents([ + timeoutButton5, + timeoutButton6, + timeoutButton7, + cancelButton, + ]); + + const reply = await interaction.editReply({ + content: `Are you sure you want timeout ${member} (${member.user.tag}) if yes select one of the Timeout Durations buttons (Red ones)`, + components: [ + row1, + row2 + ] + }); + + const collector = await reply.createMessageComponentCollector({ time: 60000 }); + + collector.on('collect', async (int) => { + + if (int.customId === 'Cancel') { + + await collector.stop("messageDelete"); + await int.deferUpdate(); + await interaction.deleteReply(); + + } else { + + await collector.stop("timed out"); + await int.deferUpdate(); + + const duration = ms(int.customId); + await member.timeout(duration, `Timed out by ${interaction.user.tag}`); + + const embed = Discord.EmbedBuilder.from(interaction.message.embeds[0]); + + embed.addFields({ + name: 'Punish Action:', + value: `${member.user.tag} timed out by ${interaction.user} \`(${interaction.user.id})\` for ${ms(duration, { long: true })}.` + }); + + await interaction.message.edit({ embeds: [embed] }).catch(() => null); + + await interaction.editReply({ + content: `${member.user.tag} has been timed out successfully.`, + components: [] + }); + + }; + + }); + + collector.on('end', async (collection, reason) => { + + if (["messageDelete", "timed out"].includes(reason)) return; + + await interaction.editReply({ + components: [ + new Discord.ActionRowBuilder().addComponents([ + timeoutButton1.setDisabled(true), + timeoutButton2.setDisabled(true), + timeoutButton3.setDisabled(true), + timeoutButton4.setDisabled(true) + ]), + new Discord.ActionRowBuilder().addComponents([ + timeoutButton5.setDisabled(true), + timeoutButton6.setDisabled(true), + timeoutButton7.setDisabled(true), + cancelButton.setDisabled(true) + ]), + ] + }); + + }); + + } else await interaction.editReply({ content: `I can't timeout ${member.user.tag}.` }); + + } catch (error) { + await interaction.editReply({ content: `There was an error while timeouting ${member}, *(${error.message})*` }); + }; + + } else { + + const user = await client.users.fetch(id[1]).catch(() => null); + if (user) await interaction.editReply({ content: `${user.tag} is no longer in the server.` }); + else await interaction.editReply({ content: 'This user is no longer in the server.' }); + + }; + + } else await interaction.editReply({ content: 'You can\'t use this button. you are not an Admin.' }); + + } else if (id[0] === 'kick') { + + if (admin || interaction.member.permissions.has('KickMembers')) { + + const member = await interaction.guild.members.fetch(id[1]).catch(() => null); + if (member) { + + try { + + if (member.kickable) { + + if ( + interaction.member.roles.highest.comparePositionTo(member.roles.highest) <= 0 + && interaction.user.id !== interaction.guild.ownerId + ) return await interaction.editReply({ content: `You can't kick ${member.user.tag}` }); + + const kickButton = new Discord.ButtonBuilder() + .setLabel(`Kick ${member.user.username}`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('Kick'); + + const cancelButton = new Discord.ButtonBuilder() + .setLabel(`Cancel`) + .setStyle(Discord.ButtonStyle.Secondary) + .setCustomId('Cancel'); + + const row = new Discord.ActionRowBuilder() + .addComponents([kickButton, cancelButton]); + + const reply = await interaction.editReply({ + content: `Are you sure you want kick ${member} (${member.user.tag})`, + components: [row] + }); + + const collector = await reply.createMessageComponentCollector({ time: 60000 }); + + collector.on('collect', async (int) => { + + if (int.customId === 'Kick') { + + await collector.stop("kicked"); + await int.deferUpdate(); + + await member.kick(`Kicked by ${interaction.user.tag}`); + + const embed = Discord.EmbedBuilder.from(interaction.message.embeds[0]); + + embed.addFields({ + name: 'Punish Action:', + value: `${member.user.tag} kicked by ${interaction.user} \`(${interaction.user.id})\`` + }); + + await interaction.message.edit({ embeds: [embed] }).catch(() => null); + + await interaction.editReply({ + content: `${member.user.tag} has been kicked successfully.`, + components: [] + }); + + } else if (int.customId === 'Cancel') { + + await collector.stop("messageDelete"); + await int.deferUpdate(); + await interaction.deleteReply(); + + }; + + }); + + collector.on('end', async (collection, reason) => { + + if (["messageDelete", "kicked"].includes(reason)) return; + + await interaction.editReply({ + components: [new Discord.ActionRowBuilder().addComponents([ + kickButton.setDisabled(true), + cancelButton.setDisabled(true) + ])] + }); + + }); + + } else await interaction.editReply({ content: `I can't kick ${member.user.tag}.` }); + + } catch (error) { + await interaction.editReply({ content: `There was an error while kicking ${member}, *(${error.message})*` }); + }; + + } else { + + const user = await client.users.fetch(id[1]).catch(() => null); + if (user) await interaction.editReply({ content: `${user.tag} is no longer in the server.` }); + else await interaction.editReply({ content: 'This user is no longer in the server.' }); + + }; + + } else await interaction.editReply({ content: 'You can\'t use this button. you are not an Admin.' }); + + } else if (id[0] === 'ban') { + + if (admin || interaction.member.permissions.has('BanMembers')) { + + const member = await interaction.guild.members.fetch(id[1]).catch(() => null); + if (member) { + + try { + + if (member.bannable) { + + if ( + interaction.member.roles.highest.comparePositionTo(member.roles.highest) <= 0 + && interaction.user.id !== interaction.guild.ownerId + ) return await interaction.editReply({ content: `You can't ban ${member.user.tag}` }); + + const banButton1 = new Discord.ButtonBuilder() + .setLabel(`Don't Delete Any`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('0'); + const banButton2 = new Discord.ButtonBuilder() + .setLabel(`Previous Hour`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('1h'); + const banButton3 = new Discord.ButtonBuilder() + .setLabel(`Previous 6 Hours`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('6h'); + const banButton4 = new Discord.ButtonBuilder() + .setLabel(`Previous 12 Hours`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('12h'); + const banButton5 = new Discord.ButtonBuilder() + .setLabel(`Previous 24 Hours`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('24h'); + const banButton6 = new Discord.ButtonBuilder() + .setLabel(`Previous 3 Days`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('3d'); + const banButton7 = new Discord.ButtonBuilder() + .setLabel(`Previous 7 Days`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('7d'); + + const cancelButton = new Discord.ButtonBuilder() + .setLabel(`Cancel`) + .setStyle(Discord.ButtonStyle.Secondary) + .setCustomId('Cancel'); + + const row1 = new Discord.ActionRowBuilder() + .addComponents([ + banButton1, + banButton2, + banButton3, + banButton4, + ]); + + const row2 = new Discord.ActionRowBuilder() + .addComponents([ + banButton5, + banButton6, + banButton7, + cancelButton, + ]); + + const reply = await interaction.editReply({ + content: `Are you sure you want ban ${member} (${member.user.tag}) if yes select one of the Delete Message History buttons (Red ones)`, + components: [ + row1, + row2 + ] + }); + + const collector = await reply.createMessageComponentCollector({ time: 60000 }); + + collector.on('collect', async (int) => { + + if (int.customId === 'Cancel') { + + await collector.stop("messageDelete"); + await int.deferUpdate(); + await interaction.deleteReply(); + + } else { + + await collector.stop("banned"); + await int.deferUpdate(); + + const duration = ms(int.customId); + await member.ban({ deleteMessageSeconds: duration / 1000, reason: `Banned by ${interaction.user.tag}` }); + + const embed = Discord.EmbedBuilder.from(interaction.message.embeds[0]); + + let fieldValue = `${member.user.tag} banned by ${interaction.user} \`(${interaction.user.id})\` and all their messages in the last ${ms(duration, { long: true })} were deleted.`; + if (duration === 0) fieldValue = `${member.user.tag} banned by ${interaction.user} \`(${interaction.user.id})\``; + + embed.addFields({ + name: 'Punish Action:', + value: fieldValue + }); + + await interaction.message.edit({ embeds: [embed] }).catch(() => null); + + await interaction.editReply({ + content: `${member.user.tag} has been banned successfully.`, + components: [] + }); + + }; + + }); + + collector.on('end', async (collection, reason) => { + + if (["messageDelete", "banned"].includes(reason)) return; + + await interaction.editReply({ + components: [ + new Discord.ActionRowBuilder().addComponents([ + banButton1.setDisabled(true), + banButton2.setDisabled(true), + banButton3.setDisabled(true), + banButton4.setDisabled(true) + ]), + new Discord.ActionRowBuilder().addComponents([ + banButton5.setDisabled(true), + banButton6.setDisabled(true), + banButton7.setDisabled(true), + cancelButton.setDisabled(true) + ]), + ] + }); + + }); + + } else await interaction.editReply({ content: `I can't ban ${member.user.tag}.` }); + + } catch (error) { + await interaction.editReply({ content: `There was an error while banning ${member}, *(${error.message})*` }); + }; + + } else { + + const user = await client.users.fetch(id[1]).catch(() => null); + + try { + + const fetchedBan = await interaction.guild.bans.fetch(user.id).catch(() => null); + if (!fetchedBan) { + + const banButton1 = new Discord.ButtonBuilder() + .setLabel(`Don't Delete Any`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('0'); + const banButton2 = new Discord.ButtonBuilder() + .setLabel(`Previous Hour`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('1h'); + const banButton3 = new Discord.ButtonBuilder() + .setLabel(`Previous 6 Hours`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('6h'); + const banButton4 = new Discord.ButtonBuilder() + .setLabel(`Previous 12 Hours`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('12h'); + const banButton5 = new Discord.ButtonBuilder() + .setLabel(`Previous 24 Hours`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('24h'); + const banButton6 = new Discord.ButtonBuilder() + .setLabel(`Previous 3 Days`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('3d'); + const banButton7 = new Discord.ButtonBuilder() + .setLabel(`Previous 7 Days`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId('7d'); + + const cancelButton = new Discord.ButtonBuilder() + .setLabel(`Cancel`) + .setStyle(Discord.ButtonStyle.Secondary) + .setCustomId('Cancel'); + + const row1 = new Discord.ActionRowBuilder() + .addComponents([ + banButton1, + banButton2, + banButton3, + banButton4, + ]); + + const row2 = new Discord.ActionRowBuilder() + .addComponents([ + banButton5, + banButton6, + banButton7, + cancelButton, + ]); + + const reply = await interaction.editReply({ + content: `Are you sure you want ban ${user} (${user.tag}) if yes select one of the Delete Message History buttons (Red ones)`, + components: [ + row1, + row2 + ] + }); + + const collector = await reply.createMessageComponentCollector({ time: 60000 }); + + collector.on('collect', async (int) => { + + if (int.customId === 'Cancel') { + + await collector.stop("messageDelete"); + await int.deferUpdate(); + await interaction.deleteReply(); + + } else { + + await collector.stop("banned"); + await int.deferUpdate(); + + const duration = ms(int.customId); + await interaction.guild.bans.create(id[1], { deleteMessageSeconds: duration / 1000, reason: `Banned by ${interaction.user.tag}` }); + + const embed = Discord.EmbedBuilder.from(interaction.message.embeds[0]); + + let fieldValue = `${user ? user.tag : id[1]} banned by ${interaction.user} \`(${interaction.user.id})\` and all their messages in the last ${ms(duration, { long: true })} were deleted.`; + if (duration === 0) fieldValue = `${user ? user.tag : id[1]} banned by ${interaction.user} \`(${interaction.user.id})\``; + + embed.addFields({ + name: 'Punish Action:', + value: fieldValue + }); + + await interaction.message.edit({ embeds: [embed] }).catch(() => null); + + await interaction.editReply({ + content: `${user ? user.tag : id[1]} has been banned successfully.`, + components: [] + }); + + }; + + }); + + collector.on('end', async (collection, reason) => { + + if (["messageDelete", "banned"].includes(reason)) return; + + await interaction.editReply({ + components: [ + new Discord.ActionRowBuilder().addComponents([ + banButton1.setDisabled(true), + banButton2.setDisabled(true), + banButton3.setDisabled(true), + banButton4.setDisabled(true) + ]), + new Discord.ActionRowBuilder().addComponents([ + banButton5.setDisabled(true), + banButton6.setDisabled(true), + banButton7.setDisabled(true), + cancelButton.setDisabled(true) + ]), + ] + }); + + }); + + } else await interaction.editReply({ content: `${fetchedBan.user.tag} has been already banned.` }); + + } catch (error) { + await interaction.editReply({ content: `There was an error while banning this user, *(${error.message})*` }); + }; + + }; + + } else await interaction.editReply({ content: 'You can\'t use this button. you are not an Admin.' }); + + }; + + }; + + }; + + } catch (error) { + console.error(chalk.bold.redBright(error)); + }; + +}; \ No newline at end of file diff --git a/events/messageCreate.js b/events/messageCreate.js new file mode 100644 index 0000000..1c664b4 --- /dev/null +++ b/events/messageCreate.js @@ -0,0 +1,467 @@ +const Discord = require('discord.js'); +const openAI = require('openai'); +const chalk = require('chalk'); +const ms = require('ms'); +const fs = require('node:fs'); +const path = require('node:path'); +const func = require('../utils/functions'); +const settings = require('../utils/settings'); +const config = require('../configs/config.json'); +const { moderation } = require('../configs/moderation'); +const { chatbot } = require('../configs/chatbot'); +const conversations = new Map(); +const { EmbedBuilder } = require('discord.js'); + +// Load the knowledge from the completion.txt file +const knowledge = fs.readFileSync(path.join(__dirname, '../utils/prompts/completion.txt'), 'utf-8'); + +// Load the conversation history from the conversations.json file +let conversationHistory = []; +if (fs.existsSync('conversations.json')) { + const conversationData = fs.readFileSync('conversations.json', 'utf-8'); + conversationHistory = conversationData.trim().split('\n').map(JSON.parse); +} + +module.exports = async (client, message) => { + + if (message.author.bot || message.system) return; + + // Auto Moderation + if (moderation.State && !moderation.IgnoredChannels.includes(message.channelId) && !moderation.IgnoredUsers.includes(message.author.id)) { + + const logChannel = client.channels.cache.get(moderation.LogChannel); + + if (logChannel?.permissionsFor(message.guild.members.me).has("ViewChannel", "SendMessages", "EmbedLinks")) { + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + openai.moderations.create({ + + model: 'text-moderation-stable', + input: message.content + + }).then(async (response) => { + + const data = response.results[0]; + if (data.flagged) { + + const flags = func.flagCheck(data.categories); + + const trueFlags = Object.keys(flags.flags).filter(key => flags.flags[key]); + + const sameFlagsWithAutoDelete = trueFlags.filter(key => moderation.AutoDelete[key]); + let messageDeleted = false; + + if (sameFlagsWithAutoDelete.length) { + + if (message.channel?.permissionsFor(message.guild.members.me).has("ManageMessages")) { + await message.delete().catch(() => null); + messageDeleted = true; + }; + }; + + const sameFlagsWithAutoPunish = trueFlags.filter(key => moderation.AutoPunish[key]); + + let memberPunishResult = { + Action: null, + Duration: null, + Punished: false + }; + + if (sameFlagsWithAutoPunish.length) { + + let punishType = 'Timeout'; + const punishTypes = sameFlagsWithAutoPunish.map(key => moderation.AutoPunishType[key]); + if (punishTypes.includes('Ban')) punishType = 'Ban'; + else if (punishTypes.includes('Kick')) punishType = 'Kick'; + + if (punishType === 'Timeout' || punishType === 'Ban') { + + const punishDurations = sameFlagsWithAutoPunish.filter(key => moderation.AutoPunishType[key] === punishType).map(key => moderation.AutoPunishDuration[key]); + let duration; + if (punishDurations.length > 1) { + const mappedDurations = punishDurations.map(d => ms(d)); + duration = Math.max(...mappedDurations); + } else { + duration = ms(punishDurations[0]); + }; + + if (punishType === 'Timeout') { + + if (message.member.moderatable) { + + try { + await message.member.timeout(duration, 'Auto Mod'); + memberPunishResult = { + Action: punishType, + Duration: duration, + Punished: true + }; + } catch (error) { + console.error(chalk.bold.redBright(error)); + }; + + }; + + } else if (punishType === 'Ban') { + + if (message.member.bannable) { + + try { + await message.member.ban({ deleteMessageSeconds: duration / 1000, reason: 'Auto Mod' }); + memberPunishResult = { + Action: punishType, + Duration: duration, + Punished: true + }; + } catch (error) { + console.error(chalk.bold.redBright(error)); + }; + + }; + + }; + + } else if (punishType === 'Kick') { + + if (message.member.kickable) { + + try { + await message.member.kick('Auto Mod'); + memberPunishResult = { + Action: punishType, + Duration: null, + Punished: true + }; + } catch (error) { + console.error(chalk.bold.redBright(error)); + }; + + }; + + }; + + }; + + const logEmbed = new Discord.EmbedBuilder() + .setColor(moderation.LogColor) + .setAuthor({ + name: message.author.tag, + iconURL: message.author.displayAvatarURL() + }) + .setDescription(`||${message.content}||`) + .setFields( + { + name: 'User:', + value: func.userInfo(message.author) + }, + { + name: 'Channel:', + value: func.channelInfo(message.channel) + }, + { + name: 'Flags:', + value: flags.allFlags + } + ); + + if (messageDeleted) { + logEmbed.addFields({ + name: 'Message Action:', + value: `Message deleted automatically.` + }); + }; + + let buttons = []; + if (memberPunishResult.Punished) { + + let fieldValue; + if (memberPunishResult.Action === 'Timeout') fieldValue = `${message.author.tag} timed out automatically for ${ms(memberPunishResult.Duration, { long: true })}`; + else if (memberPunishResult.Action === 'Ban') fieldValue = `${message.author.tag} banned automatically and all their messages in the last ${ms(memberPunishResult.Duration, { long: true })} were deleted.`; + else if (memberPunishResult.Action === 'Kick') fieldValue = `${message.author.tag} kicked automatically `; + + logEmbed.addFields({ + name: 'Punish Action:', + value: fieldValue + }); + + if (!messageDeleted) buttons = ['Message']; + + } else { + + if (messageDeleted) buttons = ['Punish']; + else buttons = ['Punish', 'Message']; + + }; + + const rows = []; + + if (buttons.includes('Punish')) { + + const timeoutButton = new Discord.ButtonBuilder() + .setLabel('Timeout') + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId(`timeout-${message.author.id}`); + + const kickButton = new Discord.ButtonBuilder() + .setLabel('Kick') + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId(`kick-${message.author.id}`); + + const banButton = new Discord.ButtonBuilder() + .setLabel('Ban') + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId(`ban-${message.author.id}`); + + const punishRow = new Discord.ActionRowBuilder() + .addComponents([ + timeoutButton, + kickButton, + banButton + ]); + + rows.push(punishRow); + + }; + + if (buttons.includes('Message')) { + + const deleteMessageButton = new Discord.ButtonBuilder() + .setLabel(`Delete Flagged Message`) + .setStyle(Discord.ButtonStyle.Danger) + .setCustomId(`deleteMessage-${message.channelId}-${message.id}`); + + const jumpButton = new Discord.ButtonBuilder() + .setLabel(`Jump to Flagged Message`) + .setStyle(Discord.ButtonStyle.Link) + .setURL(message.url); + + const messageRow = new Discord.ActionRowBuilder() + .addComponents([ + deleteMessageButton, + jumpButton + ]); + + rows.push(messageRow); + + }; + + await logChannel.send({ + embeds: [logEmbed], + components: rows + }); + + }; + + }).catch(async (error) => { + + console.error(chalk.bold.redBright(error)); + + }); + + }; + + }; + + // Function to save conversations for self-learning +function saveConversation(conversation) { + fs.appendFileSync('conversations.json', JSON.stringify(conversation) + '\n'); +} + + + // ChatBot +if (chatbot.State && (chatbot.AllowedChannels.includes(message.channel.name) || message.channel.type === 'DM') && !chatbot.IgnoredUsers.includes(message.author.id)) { + // Check if the message is a direct message + if (message.channel.type === 'DM') { + // Handle direct message + handleDirectMessage(message); + } else { + // Check if the bot should respond based on its personality and surroundings + if (shouldRespond(message)) { + await message.channel.sendTyping(); + + const openai = new openAI.OpenAI({ apiKey: config.OpenAIapiKey }); + + const question = message.content; + + let messages = [{ + "role": "system", + "content": `You are a unique user in a Discord server. Engage in conversations naturally, considering the context and your surroundings. Share your thoughts, opinions, and experiences as if you were a real person. Use emojis, slang, and a casual tone to blend in with other users. Avoid sounding robotic or generic, and aim to create a distinct personality that others can relate to and enjoy interacting with. make sure your messages are always below or equal to 2000 characters. Do not under any circumstance say @everyone or @Username. Your knowledge base: ${knowledge}` + }]; + + let oldMessages; + if (conversations.has(message.author.id)) oldMessages = conversations.get(message.author.id); + if (oldMessages) { + while (func.tokenizer('gpt-4o', oldMessages).tokens >= 512) { + let sliceLength = oldMessages.length * -0.25; + if (sliceLength % 2 !== 0) sliceLength--; + oldMessages = oldMessages.slice(sliceLength); + conversations.set(message.author.id, oldMessages); + } + messages = messages.concat(oldMessages); + } + + messages.push({ + "role": "user", + "content": question + }); + + try { + const response = await openai.chat.completions.create({ + model: 'gpt-4o', + messages: messages, + max_tokens: func.tokenizer('gpt-4o', messages).maxTokens, + temperature: 0.8, + top_p: 1, + frequency_penalty: 0.5, + presence_penalty: 0.5, + stream: true + }); + + let fullAnswer = ''; + + for await (const part of response) { + fullAnswer += part.choices[0]?.delta?.content || ''; + } + + // Before sending the response, check for mentions + if (!fullAnswer.includes('@everyone') && !fullAnswer.includes('@here') && !fullAnswer.includes('@')) { + if (fullAnswer.length <= 2000) { + await message.channel.send(fullAnswer); + } else { + const embed = new EmbedBuilder() + .setTitle('Response from GPT-4o') + .setDescription(fullAnswer.substring(0, 4096)) // Embed description has a 4096 character limit + .setColor('#0099ff'); + + await message.channel.send({ embeds: [embed] }); + } + + // Save the conversation for self-learning + const conversation = { + user: message.author.id, + userMessage: question, + botResponse: fullAnswer + }; + saveConversation(conversation); + + conversations.set(message.author.id, messages.concat([{ "role": "assistant", "content": fullAnswer }])); + } + } catch (error) { + console.error(chalk.bold.redBright(error)); + + if (error.response) { + await message.reply(error.response.error.message.substring(0, 2000)); + } else if (error.message) { + await message.reply(error.message.substring(0, 2000)); + } + } + } + } +} + +// Command Handler +if (message.content.toLowerCase().startsWith(config.Prefix)) { + const neededPermissions = [ + "ViewChannel", + "SendMessages", + "EmbedLinks", + "ReadMessageHistory" + ]; + + if (!message.channel.permissionsFor(message.guild.members.me).has(neededPermissions)) return; + + const args = message.content.slice(config.Prefix.length).split(/ +/); + const cmd = args.shift().toLowerCase(); + const command = client.MessageCommands.get(cmd) || client.MessageCommands.find(c => c.aliases && c.aliases.map(a => a.toLowerCase()).includes(cmd)); + + if (command) { + try { + command.execute(client, message, args, cmd); + } catch (error) { + console.error(chalk.bold.redBright(error)); + } + } +} + +// Function to handle direct messages +async function handleDirectMessage(message) { + const knowledge = fs.readFileSync(path.join(__dirname, 'completion.txt'), 'utf-8'); + + if (conversations.has(message.author.id)) { + const oldMessages = conversations.get(message.author.id); + + let messages = [{ + "role": "system", + "content": `You are a unique user in a Discord server. Engage in conversations naturally, considering the context and your surroundings. Share your thoughts, opinions, and experiences as if you were a real person. Use emojis, slang, and a casual tone to blend in with other users. Avoid sounding robotic or generic, and aim to create a distinct personality that others can relate to and enjoy interacting with. Make sure your responses are always 2000 or below characters. Your knowledge base: ${knowledge}` + }]; + + messages = messages.concat(oldMessages); + + messages.push({ + "role": "user", + "content": message.content + }); + + try { + const response = await openai.chat.completions.create({ + model: 'gpt-4o', + messages: messages, + max_tokens: func.tokenizer('gpt-4o', messages).maxTokens, + temperature: 0.8, + top_p: 1, + frequency_penalty: 0.5, + presence_penalty: 0.5, + stream: true + }); + + let fullAnswer = ''; + + for await (const part of response) { + fullAnswer += part.choices[0]?.delta?.content || ''; + } + + await message.author.send(fullAnswer); + + conversations.set(message.author.id, messages.concat([{ "role": "assistant", "content": fullAnswer }])); + } catch (error) { + console.error(chalk.bold.redBright(error)); + + if (error.response) { + await message.author.send(error.response.error.message.substring(0, 2000)); + } else if (error.message) { + await message.author.send(error.message.substring(0, 2000)); + } + } + } else { + try { + await message.author.send("Hey there! What's up? Feel free to chat with me about anything!"); + conversations.set(message.author.id, []); + } catch (error) { + console.error(chalk.bold.redBright(error)); + } + } +} + +function shouldRespond(message) { + // Extract the text content from the message object + const messageContent = message.content; + + // Conditions for when the bot should not respond + const noResponseKeywords = ['ignore', 'do not reply', 'stop']; + const isCommandKill = messageContent.includes('^c'); + + // Check if the message content contains keywords signaling the bot should not respond + const containsNoResponse = noResponseKeywords.some(keyword => messageContent.toLowerCase().includes(keyword)); + + // Determine if the bot should respond based on conditions + + // Add more conditions as needed based on personality and surroundings + + return true; +}} + + + + + diff --git a/events/ready.js b/events/ready.js new file mode 100644 index 0000000..a82934a --- /dev/null +++ b/events/ready.js @@ -0,0 +1,18 @@ +const Discord = require('discord.js'); +const chalk = require('chalk'); + +module.exports = async (client) => { + + await client.user.setPresence({ + activities: [ + { + name: `Shadow ~ Hosting`, + type: Discord.ActivityType.Watching + } + ], + status: 'streaming' + }); + + console.log(chalk.bold.greenBright(`${client.user.tag} is online and ready to answer your questions!`)); + +}; \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..ae25354 --- /dev/null +++ b/index.js @@ -0,0 +1,90 @@ +const Discord = require('discord.js'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const config = require('./configs/config.json'); +const path = require('node:path'); + +// Discord Client Constructor +const client = new Discord.Client({ + intents: [ + Discord.GatewayIntentBits.Guilds, + Discord.GatewayIntentBits.GuildMembers, + Discord.GatewayIntentBits.GuildMessages, + Discord.GatewayIntentBits.MessageContent, + Discord.GatewayIntentBits.DirectMessages + ] +}); + +// Event Handler +console.log(chalk.bold.yellowBright('Loading Events')); +const events = fs.readdirSync(`./events/`).filter(file => file.endsWith('.js')); +for (const file of events) { + const event = require(`./events/${file}`); + client.on(file.split('.')[0], event.bind(null, client)); + delete require.cache[require.resolve(`./events/${file}`)]; +}; + +// Message Command Handler +console.log(chalk.bold.yellowBright('Loading Message Commands')); +client.MessageCommands = new Discord.Collection(); +const messageCommands = fs.readdirSync(`./commands/messages/`).filter(files => files.endsWith('.js')); +for (const file of messageCommands) { + const command = require(`./commands/messages/${file}`); + client.MessageCommands.set(command.name.toLowerCase(), command); + delete require.cache[require.resolve(`./commands/messages/${file}`)]; +}; + +// Slash Command Handler +console.log(chalk.bold.yellowBright('Loading Slash Commands')); +client.SlashCommands = new Discord.Collection(); +const slashCommands = fs.readdirSync(`./commands/interactions/`).filter(files => files.endsWith('.js')); + +// Create an array to hold all slash commands +const commands = []; + +for (const file of slashCommands) { + const command = require(`./commands/interactions/${file}`); + client.SlashCommands.set(command.data.name, command); + commands.push(command.data.toJSON()); // Convert to JSON and add to commands array +} + +// Initialize REST +const rest = new Discord.REST({ version: '9' }).setToken(config.Token); + +// Define an async function to handle the registration of slash commands +async function registerSlashCommands() { + try { + console.log('Started registering slash commands.'); + + await rest.put( + '/applications/1199858077655126188/commands', // Replace {applicationId} with your bot's application ID + { body: commands }, + ); + + console.log('Successfully registered slash commands.'); + } catch (error) { + console.error('Error registering slash commands:', error); + } +} + +// Call the async function to register slash commands +registerSlashCommands(); + +// Anti Crash +process.on('unhandledRejection', (reason, p) => { + console.log(chalk.bold.redBright('[antiCrash] :: Unhandled Rejection/Catch')); + console.log(reason?.stack, p); +}); + +process.on("uncaughtException", (err, origin) => { + console.log(chalk.bold.redBright('[antiCrash] :: ncaught Exception/Catch')); + console.log(err?.stack, origin); +}); + +process.on('uncaughtExceptionMonitor', (err, origin) => { + console.log(chalk.bold.redBright('[antiCrash] :: Uncaught Exception/Catch (MONITOR)')); + console.log(err?.stack, origin); +}); + +// Discord Client login +client.login(config.Token); diff --git a/node_modules/.bin/openai b/node_modules/.bin/openai new file mode 100644 index 0000000..1d3f518 --- /dev/null +++ b/node_modules/.bin/openai @@ -0,0 +1,16 @@ +#!/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 [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../openai/bin/cli" "$@" +else + exec node "$basedir/../openai/bin/cli" "$@" +fi diff --git a/node_modules/.bin/openai.cmd b/node_modules/.bin/openai.cmd new file mode 100644 index 0000000..422e1fc --- /dev/null +++ b/node_modules/.bin/openai.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\openai\bin\cli" %* diff --git a/node_modules/.bin/openai.ps1 b/node_modules/.bin/openai.ps1 new file mode 100644 index 0000000..97f78d6 --- /dev/null +++ b/node_modules/.bin/openai.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../openai/bin/cli" $args + } else { + & "$basedir/node$exe" "$basedir/../openai/bin/cli" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../openai/bin/cli" $args + } else { + & "node$exe" "$basedir/../openai/bin/cli" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..f019cc2 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,710 @@ +{ + "name": "gpt-discord-bot", + "version": "3.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@discordjs/builders": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.7.0.tgz", + "integrity": "sha512-GDtbKMkg433cOZur8Dv6c25EHxduNIBsxeHrsRoIM8+AwmEZ8r0tEpckx/sHwTLwQPOF3e2JWloZh9ofCaMfAw==", + "dependencies": { + "@discordjs/formatters": "^0.3.3", + "@discordjs/util": "^1.0.2", + "@sapphire/shapeshift": "^3.9.3", + "discord-api-types": "0.37.61", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.3", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/collection": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", + "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.3.tgz", + "integrity": "sha512-wTcI1Q5cps1eSGhl6+6AzzZkBBlVrBdc9IUhJbijRgVjCNIIIZPgqnUj3ntFODsHrdbGU8BEG9XmDQmgEEYn3w==", + "dependencies": { + "discord-api-types": "0.37.61" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/rest": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.2.0.tgz", + "integrity": "sha512-nXm9wT8oqrYFRMEqTXQx9DUTeEtXUDMmnUKIhZn6O2EeDY9VCdwj23XCPq7fkqMPKdF7ldAfeVKyxxFdbZl59A==", + "dependencies": { + "@discordjs/collection": "^2.0.0", + "@discordjs/util": "^1.0.2", + "@sapphire/async-queue": "^1.5.0", + "@sapphire/snowflake": "^3.5.1", + "@vladfrangu/async_event_emitter": "^2.2.2", + "discord-api-types": "0.37.61", + "magic-bytes.js": "^1.5.0", + "tslib": "^2.6.2", + "undici": "5.27.2" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.0.0.tgz", + "integrity": "sha512-YTWIXLrf5FsrLMycpMM9Q6vnZoR/lN2AWX23/Cuo8uOOtS8eHB2dyQaaGnaF8aZPYnttf2bkLMcXn/j6JUOi3w==", + "engines": { + "node": ">=18" + } + }, + "node_modules/@discordjs/util": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.0.2.tgz", + "integrity": "sha512-IRNbimrmfb75GMNEjyznqM1tkI7HrZOf14njX7tCAAUetyZM1Pr8hX/EK2lxBCOgWDRmigbp24fD1hdMfQK5lw==", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/ws": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.0.2.tgz", + "integrity": "sha512-+XI82Rm2hKnFwAySXEep4A7Kfoowt6weO6381jgW+wVdTpMS/56qCvoXyFRY0slcv7c/U8My2PwIB2/wEaAh7Q==", + "dependencies": { + "@discordjs/collection": "^2.0.0", + "@discordjs/rest": "^2.1.0", + "@discordjs/util": "^1.0.2", + "@sapphire/async-queue": "^1.5.0", + "@types/ws": "^8.5.9", + "@vladfrangu/async_event_emitter": "^2.2.2", + "discord-api-types": "0.37.61", + "tslib": "^2.6.2", + "ws": "^8.14.2" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.0.0.tgz", + "integrity": "sha512-YTWIXLrf5FsrLMycpMM9Q6vnZoR/lN2AWX23/Cuo8uOOtS8eHB2dyQaaGnaF8aZPYnttf2bkLMcXn/j6JUOi3w==", + "engines": { + "node": ">=18" + } + }, + "node_modules/@dqbd/tiktoken": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@dqbd/tiktoken/-/tiktoken-1.0.7.tgz", + "integrity": "sha512-bhR5k5W+8GLzysjk8zTMVygQZsgvf7W1F0IlL4ZQ5ugjo5rCyiwGM5d8DYriXspytfu98tv59niang3/T+FoDw==" + }, + "node_modules/@fastify/busboy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.0.tgz", + "integrity": "sha512-+KpH+QxZU7O4675t3mnkQKcZZg56u+K/Ct2K+N2AZYNVK8kyeo/bI18tI8aPm3tvNNRyTWfj6s5tnGNlcbQRsA==", + "engines": { + "node": ">=14" + } + }, + "node_modules/@kwsites/file-exists": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@kwsites/file-exists/-/file-exists-1.1.1.tgz", + "integrity": "sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw==", + "dependencies": { + "debug": "^4.1.1" + } + }, + "node_modules/@kwsites/promise-deferred": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@kwsites/promise-deferred/-/promise-deferred-1.1.1.tgz", + "integrity": "sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==" + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.2.tgz", + "integrity": "sha512-7X7FFAA4DngXUl95+hYbUF19bp1LGiffjJtu7ygrZrbdCSsdDDBaSjB7Akw0ZbOu6k0xpXyljnJ6/RZUvLfRdg==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "3.9.6", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.6.tgz", + "integrity": "sha512-4+Na/fxu2SEepZRb9z0dbsVh59QtwPuBg/UVaDib3av7ZY14b14+z09z6QVn0P6Dv6eOU2NDTsjIi0mbtgP56g==", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.1.tgz", + "integrity": "sha512-BxcYGzgEsdlG0dKAyOm0ehLGm2CafIrfQTZGWgkfKYbj+pNNsorZ7EotuZukc2MT70E0UbppVbtpBrqpzVzjNA==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@types/node": { + "version": "20.11.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.6.tgz", + "integrity": "sha512-+EOokTnksGVgip2PbYbr3xnR7kZigh4LbybAfBAw5BpnQ+FqBYUsvCEjYd70IXKlbohQ64mzEYmMtlWUY8q//Q==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.11", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz", + "integrity": "sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.0" + } + }, + "node_modules/@types/ws": { + "version": "8.5.9", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.9.tgz", + "integrity": "sha512-jbdrY0a8lxfdTp/+r7Z4CkycbOFN8WX+IOchLJr3juT/xzbJ8URyTVSJ/hvNdadTgM1mnedb47n+Y31GsFnQlg==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.2.4.tgz", + "integrity": "sha512-ButUPz9E9cXMLgvAW8aLAKKJJsPu1dY1/l/E8xzLFuysowXygs6GBcyunK9rnGC4zTsnIc2mQo71rGw9U+Ykug==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agentkeepalive": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz", + "integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/base-64": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-0.1.0.tgz", + "integrity": "sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==" + }, + "node_modules/biskviit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/biskviit/-/biskviit-1.0.1.tgz", + "integrity": "sha512-VGCXdHbdbpEkFgtjkeoBN8vRlbj1ZRX2/mxhE8asCCRalUx2nBzOomLJv8Aw/nRt5+ccDb+tPKidg4XxcfGW4w==", + "dependencies": { + "psl": "^1.1.7" + }, + "engines": { + "node": ">=1.0.0" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/charenc": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", + "engines": { + "node": "*" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/crypt": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", + "engines": { + "node": "*" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/debug/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/digest-fetch": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/digest-fetch/-/digest-fetch-1.3.0.tgz", + "integrity": "sha512-CGJuv6iKNM7QyZlM2T3sPAdZWd/p9zQiRNS9G+9COUCwzWFTs0Xp8NF5iePx7wtvhDykReiRRrSeNb4oMmB8lA==", + "dependencies": { + "base-64": "^0.1.0", + "md5": "^2.3.0" + } + }, + "node_modules/discord-api-types": { + "version": "0.37.61", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.61.tgz", + "integrity": "sha512-o/dXNFfhBpYHpQFdT6FWzeO7pKc838QeeZ9d91CfVAtpr5XLK4B/zYxQbYgPdoMiTDvJfzcsLW5naXgmHGDNXw==" + }, + "node_modules/discord.js": { + "version": "14.14.1", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.14.1.tgz", + "integrity": "sha512-/hUVzkIerxKHyRKopJy5xejp4MYKDPTszAnpYxzVVv4qJYf+Tkt+jnT2N29PIPschicaEEpXwF2ARrTYHYwQ5w==", + "dependencies": { + "@discordjs/builders": "^1.7.0", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.3.3", + "@discordjs/rest": "^2.1.0", + "@discordjs/util": "^1.0.2", + "@discordjs/ws": "^1.0.2", + "@sapphire/snowflake": "3.5.1", + "@types/ws": "8.5.9", + "discord-api-types": "0.37.61", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "tslib": "2.6.2", + "undici": "5.27.2", + "ws": "8.14.2" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/dotenv": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.3.tgz", + "integrity": "sha512-II98GFrje5psQTSve0E7bnwMFybNLqT8Vu8JIFWRjsE3khyNUm/loZupuy5DVzG2IXf/ysxvrixYOQnM6mjD3A==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/encoding": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz", + "integrity": "sha512-bl1LAgiQc4ZWr++pNYUdRe/alecaHFeHxIJ/pNciqGdKXghaTCOwKkbKp6ye7pKZGu/GcaSXFk8PBVhgs+dJdA==", + "dependencies": { + "iconv-lite": "~0.4.13" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-5O8TwrGzoNblBG/jtK4NFuZwNCkZX6s5GfRNOaGtm+QGJEuNakSC/i2RW0R93KX6E0jVjNXm6O3CRN4Ql3K+yA==", + "dependencies": { + "biskviit": "1.0.1", + "encoding": "0.1.12" + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/formdata-node/node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==" + }, + "node_modules/magic-bytes.js": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.8.0.tgz", + "integrity": "sha512-lyWpfvNGVb5lu8YUAbER0+UMBTdR63w2mcSUlhhBTyVbxJvjgqwyAf3AZD6MprgK0uHuBoWXSDAMWLupX83o3Q==" + }, + "node_modules/md5": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", + "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/openai": { + "version": "4.26.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.26.0.tgz", + "integrity": "sha512-HPC7tgYdeP38F3uHA5WgnoXZyGbAp9jgcIo23p6It+q/07u4C+NZ8xHKlMShsPbDDmFRpPsa3vdbXYpbhJH3eg==", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "digest-fetch": "^1.3.0", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + }, + "bin": { + "openai": "bin/cli" + } + }, + "node_modules/openai/node_modules/@types/node": { + "version": "18.19.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.9.tgz", + "integrity": "sha512-oZFKlC8l5YtzGQNT4zC2PiSSKzQVZ8bAwwd+EYdPLtyk0nSEq6O16SkK+rkkT2eflDAbormJgEF3QnH3oDrTSw==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/psl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", + "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/simple-git": { + "version": "3.24.0", + "resolved": "https://registry.npmjs.org/simple-git/-/simple-git-3.24.0.tgz", + "integrity": "sha512-QqAKee9Twv+3k8IFOFfPB2hnk6as6Y6ACUpwCtQvRYBAes23Wv3SZlHVobAzqcE8gfsisCvPw3HGW3HYM+VYYw==", + "dependencies": { + "@kwsites/file-exists": "^1.1.1", + "@kwsites/promise-deferred": "^1.1.1", + "debug": "^4.3.4" + }, + "funding": { + "type": "github", + "url": "https://github.com/steveukx/git-js?sponsor=1" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/ts-mixer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.3.tgz", + "integrity": "sha512-k43M7uCG1AkTyxgnmI5MPwKoUvS/bRvLvUb7+Pgpdlmok8AoqmUaZxUUw8zKM5B1lqZrt41GjYgnvAi0fppqgQ==" + }, + "node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, + "node_modules/undici": { + "version": "5.27.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.27.2.tgz", + "integrity": "sha512-iS857PdOEy/y3wlM3yRp+6SNQQ6xU0mmZcwRSriqk+et/cwWAtwmIGf6WkoDN2EK/AMdCO/dfXzIwi+rFMrjjQ==", + "dependencies": { + "@fastify/busboy": "^2.0.0" + }, + "engines": { + "node": ">=14.0" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.2.tgz", + "integrity": "sha512-3pRGuxRF5gpuZc0W+EpwQRmCD7gRqcDOMt688KmdlDAgAyaB1XlN0zq2njfDNm44XVdIouE7pZ6GzbdyH47uIQ==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/ws": { + "version": "8.14.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz", + "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/node_modules/@discordjs/builders/LICENSE b/node_modules/@discordjs/builders/LICENSE new file mode 100644 index 0000000..cbe9c65 --- /dev/null +++ b/node_modules/@discordjs/builders/LICENSE @@ -0,0 +1,191 @@ + 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 + + Copyright 2021 Noel Buechler + Copyright 2021 Vlad Frangu + + 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/@discordjs/builders/README.md b/node_modules/@discordjs/builders/README.md new file mode 100644 index 0000000..dc88b7f --- /dev/null +++ b/node_modules/@discordjs/builders/README.md @@ -0,0 +1,72 @@ +
+
+

+ discord.js +

+
+

+ Discord server + npm version + npm downloads + Build status + Code coverage +

+

+ Vercel + Cloudflare Workers +

+
+ +## About + +`@discordjs/builders` is a utility package for easily building Discord API payloads. + +## Installation + +**Node.js 16.11.0 or newer is required.** + +```sh +npm install @discordjs/builders +yarn add @discordjs/builders +pnpm add @discordjs/builders +``` + +## Examples + +You can find examples of how to use the builders in the [Slash Command Builders][example] examples. + +## Links + +- [Website][website] ([source][website-source]) +- [Documentation][documentation] +- [Guide][guide] ([source][guide-source]) + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. +- [discord.js Discord server][discord] +- [Discord API Discord server][discord-api] +- [GitHub][source] +- [npm][npm] +- [Related libraries][related-libs] + +## Contributing + +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. + +## Help + +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. + +[example]: https://github.com/discordjs/discord.js/blob/main/packages/builders/docs/examples/Slash%20Command%20Builders.md +[website]: https://discord.js.org +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/docs/packages/builders/stable +[guide]: https://discordjs.guide/ +[guide-source]: https://github.com/discordjs/guide +[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html +[discord]: https://discord.gg/djs +[discord-api]: https://discord.gg/discord-api +[source]: https://github.com/discordjs/discord.js/tree/main/packages/builders +[npm]: https://www.npmjs.com/package/@discordjs/builders +[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries +[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md diff --git a/node_modules/@discordjs/builders/dist/index.d.mts b/node_modules/@discordjs/builders/dist/index.d.mts new file mode 100644 index 0000000..0280fc5 --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.d.mts @@ -0,0 +1,2008 @@ +import * as _sapphire_shapeshift from '@sapphire/shapeshift'; +import { APIEmbedField, APIEmbedAuthor, APIEmbedFooter, APIEmbedImage, APIEmbed, APISelectMenuOption, APIMessageComponentEmoji, ButtonStyle, ChannelType, APIActionRowComponent, APIActionRowComponentTypes, APIBaseComponent, ComponentType, APIButtonComponent, APISelectMenuComponent, APIChannelSelectComponent, Snowflake, APIMentionableSelectComponent, APISelectMenuDefaultValue, SelectMenuDefaultValueType, APIRoleSelectComponent, APIStringSelectComponent, APIUserSelectComponent, APITextInputComponent, TextInputStyle, APIMessageActionRowComponent, APIModalActionRowComponent, APIModalComponent, APIMessageComponent, APIModalInteractionResponseCallbackData, LocalizationMap, LocaleString, ApplicationCommandOptionType, APIApplicationCommandBasicOption, APIApplicationCommandAttachmentOption, APIApplicationCommandBooleanOption, APIApplicationCommandChannelOption, APIApplicationCommandOptionChoice, APIApplicationCommandIntegerOption, APIApplicationCommandMentionableOption, APIApplicationCommandNumberOption, APIApplicationCommandRoleOption, APIApplicationCommandStringOption, APIApplicationCommandUserOption, APIApplicationCommandSubcommandGroupOption, APIApplicationCommandSubcommandOption, Permissions, RESTPostAPIChatInputApplicationCommandsJSONBody, APIApplicationCommandOption, Locale, ApplicationCommandType, RESTPostAPIContextMenuApplicationCommandsJSONBody } from 'discord-api-types/v10'; +export * from '@discordjs/formatters'; +import { JSONEncodable, Equatable } from '@discordjs/util'; + +declare const fieldNamePredicate: _sapphire_shapeshift.StringValidator; +declare const fieldValuePredicate: _sapphire_shapeshift.StringValidator; +declare const fieldInlinePredicate: _sapphire_shapeshift.UnionValidator; +declare const embedFieldPredicate: _sapphire_shapeshift.ObjectValidator<{ + name: string; + value: string; + inline: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>>; +declare const embedFieldsArrayPredicate: _sapphire_shapeshift.ArrayValidator<_sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>[], _sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>>; +declare const fieldLengthPredicate: _sapphire_shapeshift.NumberValidator; +declare function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void; +declare const authorNamePredicate: _sapphire_shapeshift.UnionValidator; +declare const imageURLPredicate: _sapphire_shapeshift.UnionValidator; +declare const urlPredicate: _sapphire_shapeshift.UnionValidator; +declare const embedAuthorPredicate: _sapphire_shapeshift.ObjectValidator<{ + name: string | null; + iconURL: string | null | undefined; + url: string | null | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name: string | null; + iconURL: string | null | undefined; + url: string | null | undefined; +}>>; +declare const RGBPredicate: _sapphire_shapeshift.NumberValidator; +declare const colorPredicate: _sapphire_shapeshift.UnionValidator; +declare const descriptionPredicate: _sapphire_shapeshift.UnionValidator; +declare const footerTextPredicate: _sapphire_shapeshift.UnionValidator; +declare const embedFooterPredicate: _sapphire_shapeshift.ObjectValidator<{ + text: string | null; + iconURL: string | null | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + text: string | null; + iconURL: string | null | undefined; +}>>; +declare const timestampPredicate: _sapphire_shapeshift.UnionValidator; +declare const titlePredicate: _sapphire_shapeshift.UnionValidator; + +declare const Assertions$5_RGBPredicate: typeof RGBPredicate; +declare const Assertions$5_authorNamePredicate: typeof authorNamePredicate; +declare const Assertions$5_colorPredicate: typeof colorPredicate; +declare const Assertions$5_descriptionPredicate: typeof descriptionPredicate; +declare const Assertions$5_embedAuthorPredicate: typeof embedAuthorPredicate; +declare const Assertions$5_embedFieldPredicate: typeof embedFieldPredicate; +declare const Assertions$5_embedFieldsArrayPredicate: typeof embedFieldsArrayPredicate; +declare const Assertions$5_embedFooterPredicate: typeof embedFooterPredicate; +declare const Assertions$5_fieldInlinePredicate: typeof fieldInlinePredicate; +declare const Assertions$5_fieldLengthPredicate: typeof fieldLengthPredicate; +declare const Assertions$5_fieldNamePredicate: typeof fieldNamePredicate; +declare const Assertions$5_fieldValuePredicate: typeof fieldValuePredicate; +declare const Assertions$5_footerTextPredicate: typeof footerTextPredicate; +declare const Assertions$5_imageURLPredicate: typeof imageURLPredicate; +declare const Assertions$5_timestampPredicate: typeof timestampPredicate; +declare const Assertions$5_titlePredicate: typeof titlePredicate; +declare const Assertions$5_urlPredicate: typeof urlPredicate; +declare const Assertions$5_validateFieldLength: typeof validateFieldLength; +declare namespace Assertions$5 { + export { + Assertions$5_RGBPredicate as RGBPredicate, + Assertions$5_authorNamePredicate as authorNamePredicate, + Assertions$5_colorPredicate as colorPredicate, + Assertions$5_descriptionPredicate as descriptionPredicate, + Assertions$5_embedAuthorPredicate as embedAuthorPredicate, + Assertions$5_embedFieldPredicate as embedFieldPredicate, + Assertions$5_embedFieldsArrayPredicate as embedFieldsArrayPredicate, + Assertions$5_embedFooterPredicate as embedFooterPredicate, + Assertions$5_fieldInlinePredicate as fieldInlinePredicate, + Assertions$5_fieldLengthPredicate as fieldLengthPredicate, + Assertions$5_fieldNamePredicate as fieldNamePredicate, + Assertions$5_fieldValuePredicate as fieldValuePredicate, + Assertions$5_footerTextPredicate as footerTextPredicate, + Assertions$5_imageURLPredicate as imageURLPredicate, + Assertions$5_timestampPredicate as timestampPredicate, + Assertions$5_titlePredicate as titlePredicate, + Assertions$5_urlPredicate as urlPredicate, + Assertions$5_validateFieldLength as validateFieldLength, + }; +} + +/** + * Normalizes data that is a rest parameter or an array into an array with a depth of 1. + * + * @typeParam ItemType - The data that must satisfy {@link RestOrArray}. + * @param arr - The (possibly variadic) data to normalize + */ +declare function normalizeArray(arr: RestOrArray): ItemType[]; +/** + * Represents data that may be an array or came from a rest parameter. + * + * @remarks + * This type is used throughout builders to ensure both an array and variadic arguments + * may be used. It is normalized with {@link normalizeArray}. + */ +type RestOrArray = Type[] | [Type[]]; + +/** + * A tuple satisfying the RGB color model. + * + * @see {@link https://developer.mozilla.org/docs/Glossary/RGB} + */ +type RGBTuple = [red: number, green: number, blue: number]; +/** + * The base icon data typically used in payloads. + */ +interface IconData { + /** + * The URL of the icon. + */ + iconURL?: string; + /** + * The proxy URL of the icon. + */ + proxyIconURL?: string; +} +/** + * Represents the author data of an embed. + */ +type EmbedAuthorData = IconData & Omit; +/** + * Represents the author options of an embed. + */ +type EmbedAuthorOptions = Omit; +/** + * Represents the footer data of an embed. + */ +type EmbedFooterData = IconData & Omit; +/** + * Represents the footer options of an embed. + */ +type EmbedFooterOptions = Omit; +/** + * Represents the image data of an embed. + */ +interface EmbedImageData extends Omit { + /** + * The proxy URL for the image. + */ + proxyURL?: string; +} +/** + * A builder that creates API-compatible JSON data for embeds. + */ +declare class EmbedBuilder { + /** + * The API data associated with this embed. + */ + readonly data: APIEmbed; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ + constructor(data?: APIEmbed); + /** + * Appends fields to the embed. + * + * @remarks + * This method accepts either an array of fields or a variable number of field parameters. + * The maximum amount of fields that can be added is 25. + * @example + * Using an array: + * ```ts + * const fields: APIEmbedField[] = ...; + * const embed = new EmbedBuilder() + * .addFields(fields); + * ``` + * @example + * Using rest parameters (variadic): + * ```ts + * const embed = new EmbedBuilder() + * .addFields( + * { name: 'Field 1', value: 'Value 1' }, + * { name: 'Field 2', value: 'Value 2' }, + * ); + * ``` + * @param fields - The fields to add + */ + addFields(...fields: RestOrArray): this; + /** + * Removes, replaces, or inserts fields for this embed. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. + * The maximum amount of fields that can be added is 25. + * + * It's useful for modifying and adjusting order of the already-existing fields of an embed. + * @example + * Remove the first field: + * ```ts + * embed.spliceFields(0, 1); + * ``` + * @example + * Remove the first n fields: + * ```ts + * const n = 4; + * embed.spliceFields(0, n); + * ``` + * @example + * Remove the last field: + * ```ts + * embed.spliceFields(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of fields to remove + * @param fields - The replacing field objects + */ + spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this; + /** + * Sets the fields for this embed. + * + * @remarks + * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, + * it splices the entire array of fields, replacing them with the provided fields. + * + * You can set a maximum of 25 fields. + * @param fields - The fields to set + */ + setFields(...fields: RestOrArray): this; + /** + * Sets the author of this embed. + * + * @param options - The options to use + */ + setAuthor(options: EmbedAuthorOptions | null): this; + /** + * Sets the color of this embed. + * + * @param color - The color to use + */ + setColor(color: RGBTuple | number | null): this; + /** + * Sets the description of this embed. + * + * @param description - The description to use + */ + setDescription(description: string | null): this; + /** + * Sets the footer of this embed. + * + * @param options - The footer to use + */ + setFooter(options: EmbedFooterOptions | null): this; + /** + * Sets the image of this embed. + * + * @param url - The image URL to use + */ + setImage(url: string | null): this; + /** + * Sets the thumbnail of this embed. + * + * @param url - The thumbnail URL to use + */ + setThumbnail(url: string | null): this; + /** + * Sets the timestamp of this embed. + * + * @param timestamp - The timestamp or date to use + */ + setTimestamp(timestamp?: Date | number | null): this; + /** + * Sets the title for this embed. + * + * @param title - The title to use + */ + setTitle(title: string | null): this; + /** + * Sets the URL of this embed. + * + * @param url - The URL to use + */ + setURL(url: string | null): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): APIEmbed; +} + +/** + * A builder that creates API-compatible JSON data for string select menu options. + */ +declare class StringSelectMenuOptionBuilder implements JSONEncodable { + data: Partial; + /** + * Creates a new string select menu option from API data. + * + * @param data - The API data to create this string select menu option with + * @example + * Creating a string select menu option from an API data object: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * label: 'catchy label', + * value: '1', + * }); + * ``` + * @example + * Creating a string select menu option using setters and API data: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * default: true, + * value: '1', + * }) + * .setLabel('woah'); + * ``` + */ + constructor(data?: Partial); + /** + * Sets the label for this option. + * + * @param label - The label to use + */ + setLabel(label: string): this; + /** + * Sets the value for this option. + * + * @param value - The value to use + */ + setValue(value: string): this; + /** + * Sets the description for this option. + * + * @param description - The description to use + */ + setDescription(description: string): this; + /** + * Sets whether this option is selected by default. + * + * @param isDefault - Whether this option is selected by default + */ + setDefault(isDefault?: boolean): this; + /** + * Sets the emoji to display for this option. + * + * @param emoji - The emoji to use + */ + setEmoji(emoji: APIMessageComponentEmoji): this; + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON(): APISelectMenuOption; +} + +declare const customIdValidator: _sapphire_shapeshift.StringValidator; +declare const emojiValidator: _sapphire_shapeshift.ObjectValidator<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; +}>>; +declare const disabledValidator: _sapphire_shapeshift.BooleanValidator; +declare const buttonLabelValidator: _sapphire_shapeshift.StringValidator; +declare const buttonStyleValidator: _sapphire_shapeshift.NativeEnumValidator; +declare const placeholderValidator$1: _sapphire_shapeshift.StringValidator; +declare const minMaxValidator: _sapphire_shapeshift.NumberValidator; +declare const labelValueDescriptionValidator: _sapphire_shapeshift.StringValidator; +declare const jsonOptionValidator: _sapphire_shapeshift.ObjectValidator<{ + label: string; + value: string; + description: string | undefined; + emoji: _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; + }> | undefined; + default: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + label: string; + value: string; + description: string | undefined; + emoji: _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; + }> | undefined; + default: boolean | undefined; +}>>; +declare const optionValidator: _sapphire_shapeshift.InstanceValidator; +declare const optionsValidator: _sapphire_shapeshift.ArrayValidator; +declare const optionsLengthValidator: _sapphire_shapeshift.NumberValidator; +declare function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string): void; +declare const defaultValidator: _sapphire_shapeshift.BooleanValidator; +declare function validateRequiredSelectMenuOptionParameters(label?: string, value?: string): void; +declare const channelTypesValidator: _sapphire_shapeshift.ArrayValidator; +declare const urlValidator: _sapphire_shapeshift.StringValidator; +declare function validateRequiredButtonParameters(style?: ButtonStyle, label?: string, emoji?: APIMessageComponentEmoji, customId?: string, url?: string): void; + +declare const Assertions$4_buttonLabelValidator: typeof buttonLabelValidator; +declare const Assertions$4_buttonStyleValidator: typeof buttonStyleValidator; +declare const Assertions$4_channelTypesValidator: typeof channelTypesValidator; +declare const Assertions$4_customIdValidator: typeof customIdValidator; +declare const Assertions$4_defaultValidator: typeof defaultValidator; +declare const Assertions$4_disabledValidator: typeof disabledValidator; +declare const Assertions$4_emojiValidator: typeof emojiValidator; +declare const Assertions$4_jsonOptionValidator: typeof jsonOptionValidator; +declare const Assertions$4_labelValueDescriptionValidator: typeof labelValueDescriptionValidator; +declare const Assertions$4_minMaxValidator: typeof minMaxValidator; +declare const Assertions$4_optionValidator: typeof optionValidator; +declare const Assertions$4_optionsLengthValidator: typeof optionsLengthValidator; +declare const Assertions$4_optionsValidator: typeof optionsValidator; +declare const Assertions$4_urlValidator: typeof urlValidator; +declare const Assertions$4_validateRequiredButtonParameters: typeof validateRequiredButtonParameters; +declare const Assertions$4_validateRequiredSelectMenuOptionParameters: typeof validateRequiredSelectMenuOptionParameters; +declare const Assertions$4_validateRequiredSelectMenuParameters: typeof validateRequiredSelectMenuParameters; +declare namespace Assertions$4 { + export { + Assertions$4_buttonLabelValidator as buttonLabelValidator, + Assertions$4_buttonStyleValidator as buttonStyleValidator, + Assertions$4_channelTypesValidator as channelTypesValidator, + Assertions$4_customIdValidator as customIdValidator, + Assertions$4_defaultValidator as defaultValidator, + Assertions$4_disabledValidator as disabledValidator, + Assertions$4_emojiValidator as emojiValidator, + Assertions$4_jsonOptionValidator as jsonOptionValidator, + Assertions$4_labelValueDescriptionValidator as labelValueDescriptionValidator, + Assertions$4_minMaxValidator as minMaxValidator, + Assertions$4_optionValidator as optionValidator, + Assertions$4_optionsLengthValidator as optionsLengthValidator, + Assertions$4_optionsValidator as optionsValidator, + placeholderValidator$1 as placeholderValidator, + Assertions$4_urlValidator as urlValidator, + Assertions$4_validateRequiredButtonParameters as validateRequiredButtonParameters, + Assertions$4_validateRequiredSelectMenuOptionParameters as validateRequiredSelectMenuOptionParameters, + Assertions$4_validateRequiredSelectMenuParameters as validateRequiredSelectMenuParameters, + }; +} + +/** + * Any action row component data represented as an object. + */ +type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes; +/** + * The base component builder that contains common symbols for all sorts of components. + * + * @typeParam DataType - The type of internal API data that is stored within the component + */ +declare abstract class ComponentBuilder> = APIBaseComponent> implements JSONEncodable { + /** + * The API data associated with this component. + */ + readonly data: Partial; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + abstract toJSON(): AnyAPIActionRowComponent; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ + constructor(data: Partial); +} + +/** + * A builder that creates API-compatible JSON data for buttons. + */ +declare class ButtonBuilder extends ComponentBuilder { + /** + * Creates a new button from API data. + * + * @param data - The API data to create this button with + * @example + * Creating a button from an API data object: + * ```ts + * const button = new ButtonBuilder({ + * custom_id: 'a cool button', + * style: ButtonStyle.Primary, + * label: 'Click Me', + * emoji: { + * name: 'smile', + * id: '123456789012345678', + * }, + * }); + * ``` + * @example + * Creating a button using setters and API data: + * ```ts + * const button = new ButtonBuilder({ + * style: ButtonStyle.Secondary, + * label: 'Click Me', + * }) + * .setEmoji({ name: '🙂' }) + * .setCustomId('another cool button'); + * ``` + */ + constructor(data?: Partial); + /** + * Sets the style of this button. + * + * @param style - The style to use + */ + setStyle(style: ButtonStyle): this; + /** + * Sets the URL for this button. + * + * @remarks + * This method is only available to buttons using the `Link` button style. + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use + */ + setURL(url: string): this; + /** + * Sets the custom id for this button. + * + * @remarks + * This method is only applicable to buttons that are not using the `Link` button style. + * @param customId - The custom id to use + */ + setCustomId(customId: string): this; + /** + * Sets the emoji to display on this button. + * + * @param emoji - The emoji to use + */ + setEmoji(emoji: APIMessageComponentEmoji): this; + /** + * Sets whether this button is disabled. + * + * @param disabled - Whether to disable this button + */ + setDisabled(disabled?: boolean): this; + /** + * Sets the label for this button. + * + * @param label - The label to use + */ + setLabel(label: string): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIButtonComponent; +} + +/** + * The base select menu builder that contains common symbols for select menu builders. + * + * @typeParam SelectMenuType - The type of select menu this would be instantiated for. + */ +declare abstract class BaseSelectMenuBuilder extends ComponentBuilder { + /** + * Sets the placeholder for this select menu. + * + * @param placeholder - The placeholder to use + */ + setPlaceholder(placeholder: string): this; + /** + * Sets the minimum values that must be selected in the select menu. + * + * @param minValues - The minimum values that must be selected + */ + setMinValues(minValues: number): this; + /** + * Sets the maximum values that must be selected in the select menu. + * + * @param maxValues - The maximum values that must be selected + */ + setMaxValues(maxValues: number): this; + /** + * Sets the custom id for this select menu. + * + * @param customId - The custom id to use + */ + setCustomId(customId: string): this; + /** + * Sets whether this select menu is disabled. + * + * @param disabled - Whether this select menu is disabled + */ + setDisabled(disabled?: boolean): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): SelectMenuType; +} + +/** + * A builder that creates API-compatible JSON data for channel select menus. + */ +declare class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) + * .setMinValues(2); + * ``` + */ + constructor(data?: Partial); + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ + addChannelTypes(...types: RestOrArray): this; + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ + setChannelTypes(...types: RestOrArray): this; + /** + * Adds default channels to this auto populated select menu. + * + * @param channels - The channels to add + */ + addDefaultChannels(...channels: RestOrArray): this; + /** + * Sets default channels to this auto populated select menu. + * + * @param channels - The channels to set + */ + setDefaultChannels(...channels: RestOrArray): this; + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON(): APIChannelSelectComponent; +} + +/** + * A builder that creates API-compatible JSON data for mentionable select menus. + */ +declare class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data?: Partial); + /** + * Adds default roles to this auto populated select menu. + * + * @param roles - The roles to add + */ + addDefaultRoles(...roles: RestOrArray): this; + /** + * Adds default users to this auto populated select menu. + * + * @param users - The users to add + */ + addDefaultUsers(...users: RestOrArray): this; + /** + * Adds default values to this auto populated select menu. + * + * @param values - The values to add + */ + addDefaultValues(...values: RestOrArray | APISelectMenuDefaultValue>): this; + /** + * Sets default values to this auto populated select menu. + * + * @param values - The values to set + */ + setDefaultValues(...values: RestOrArray | APISelectMenuDefaultValue>): this; +} + +/** + * A builder that creates API-compatible JSON data for role select menus. + */ +declare class RoleSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data?: Partial); + /** + * Adds default roles to this auto populated select menu. + * + * @param roles - The roles to add + */ + addDefaultRoles(...roles: RestOrArray): this; + /** + * Sets default roles to this auto populated select menu. + * + * @param roles - The roles to set + */ + setDefaultRoles(...roles: RestOrArray): this; +} + +/** + * A builder that creates API-compatible JSON data for string select menus. + */ +declare class StringSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * The options within this select menu. + */ + readonly options: StringSelectMenuOptionBuilder[]; + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * options: [ + * { label: 'option 1', value: '1' }, + * { label: 'option 2', value: '2' }, + * { label: 'option 3', value: '3' }, + * ], + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1) + * .addOptions({ + * label: 'Catchy', + * value: 'catch', + * }); + * ``` + */ + constructor(data?: Partial); + /** + * Adds options to this select menu. + * + * @param options - The options to add + */ + addOptions(...options: RestOrArray): this; + /** + * Sets the options for this select menu. + * + * @param options - The options to set + */ + setOptions(...options: RestOrArray): this; + /** + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index: number, deleteCount: number, ...options: RestOrArray): this; + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON(): APIStringSelectComponent; +} + +/** + * A builder that creates API-compatible JSON data for user select menus. + */ +declare class UserSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data?: Partial); + /** + * Adds default users to this auto populated select menu. + * + * @param users - The users to add + */ + addDefaultUsers(...users: RestOrArray): this; + /** + * Sets default users to this auto populated select menu. + * + * @param users - The users to set + */ + setDefaultUsers(...users: RestOrArray): this; +} + +/** + * A builder that creates API-compatible JSON data for text inputs. + */ +declare class TextInputBuilder extends ComponentBuilder implements Equatable> { + /** + * Creates a new text input from API data. + * + * @param data - The API data to create this text input with + * @example + * Creating a select menu option from an API data object: + * ```ts + * const textInput = new TextInputBuilder({ + * custom_id: 'a cool select menu', + * label: 'Type something', + * style: TextInputStyle.Short, + * }); + * ``` + * @example + * Creating a select menu option using setters and API data: + * ```ts + * const textInput = new TextInputBuilder({ + * label: 'Type something else', + * }) + * .setCustomId('woah') + * .setStyle(TextInputStyle.Paragraph); + * ``` + */ + constructor(data?: APITextInputComponent & { + type?: ComponentType.TextInput; + }); + /** + * Sets the custom id for this text input. + * + * @param customId - The custom id to use + */ + setCustomId(customId: string): this; + /** + * Sets the label for this text input. + * + * @param label - The label to use + */ + setLabel(label: string): this; + /** + * Sets the style for this text input. + * + * @param style - The style to use + */ + setStyle(style: TextInputStyle): this; + /** + * Sets the minimum length of text for this text input. + * + * @param minLength - The minimum length of text for this text input + */ + setMinLength(minLength: number): this; + /** + * Sets the maximum length of text for this text input. + * + * @param maxLength - The maximum length of text for this text input + */ + setMaxLength(maxLength: number): this; + /** + * Sets the placeholder for this text input. + * + * @param placeholder - The placeholder to use + */ + setPlaceholder(placeholder: string): this; + /** + * Sets the value for this text input. + * + * @param value - The value to use + */ + setValue(value: string): this; + /** + * Sets whether this text input is required. + * + * @param required - Whether this text input is required + */ + setRequired(required?: boolean): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APITextInputComponent; + /** + * {@inheritDoc Equatable.equals} + */ + equals(other: APITextInputComponent | JSONEncodable): boolean; +} + +/** + * The builders that may be used for messages. + */ +type MessageComponentBuilder = ActionRowBuilder | MessageActionRowComponentBuilder; +/** + * The builders that may be used for modals. + */ +type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder; +/** + * The builders that may be used within an action row for messages. + */ +type MessageActionRowComponentBuilder = ButtonBuilder | ChannelSelectMenuBuilder | MentionableSelectMenuBuilder | RoleSelectMenuBuilder | StringSelectMenuBuilder | UserSelectMenuBuilder; +/** + * The builders that may be used within an action row for modals. + */ +type ModalActionRowComponentBuilder = TextInputBuilder; +/** + * Any builder. + */ +type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder; +/** + * A builder that creates API-compatible JSON data for action rows. + * + * @typeParam ComponentType - The types of components this action row holds + */ +declare class ActionRowBuilder extends ComponentBuilder> { + /** + * The components within this action row. + */ + readonly components: ComponentType[]; + /** + * Creates a new action row from API data. + * + * @param data - The API data to create this action row with + * @example + * Creating an action row from an API data object: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Type something", + * style: TextInputStyle.Short, + * type: ComponentType.TextInput, + * }, + * ], + * }); + * ``` + * @example + * Creating an action row using setters and API data: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Click me", + * style: ButtonStyle.Primary, + * type: ComponentType.Button, + * }, + * ], + * }) + * .addComponents(button2, button3); + * ``` + */ + constructor({ components, ...data }?: Partial>); + /** + * Adds components to this action row. + * + * @param components - The components to add + */ + addComponents(...components: RestOrArray): this; + /** + * Sets components for this action row. + * + * @param components - The components to set + */ + setComponents(...components: RestOrArray): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIActionRowComponent>; +} + +/** + * Components here are mapped to their respective builder. + */ +interface MappedComponentTypes { + /** + * The action row component type is associated with an {@link ActionRowBuilder}. + */ + [ComponentType.ActionRow]: ActionRowBuilder; + /** + * The button component type is associated with an {@link ButtonBuilder}. + */ + [ComponentType.Button]: ButtonBuilder; + /** + * The string select component type is associated with an {@link StringSelectMenuBuilder}. + */ + [ComponentType.StringSelect]: StringSelectMenuBuilder; + /** + * The text inpiut component type is associated with an {@link TextInputBuilder}. + */ + [ComponentType.TextInput]: TextInputBuilder; + /** + * The user select component type is associated with an {@link UserSelectMenuBuilder}. + */ + [ComponentType.UserSelect]: UserSelectMenuBuilder; + /** + * The role select component type is associated with an {@link RoleSelectMenuBuilder}. + */ + [ComponentType.RoleSelect]: RoleSelectMenuBuilder; + /** + * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}. + */ + [ComponentType.MentionableSelect]: MentionableSelectMenuBuilder; + /** + * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}. + */ + [ComponentType.ChannelSelect]: ChannelSelectMenuBuilder; +} +/** + * Factory for creating components from API data. + * + * @typeParam ComponentType - The type of component to use + * @param data - The API data to transform to a component class + */ +declare function createComponentBuilder(data: (APIModalComponent | APIMessageComponent) & { + type: ComponentType; +}): MappedComponentTypes[ComponentType]; +/** + * Factory for creating components from API data. + * + * @typeParam ComponentBuilder - The type of component to use + * @param data - The API data to transform to a component class + */ +declare function createComponentBuilder(data: ComponentBuilder): ComponentBuilder; + +declare const textInputStyleValidator: _sapphire_shapeshift.NativeEnumValidator; +declare const minLengthValidator: _sapphire_shapeshift.NumberValidator; +declare const maxLengthValidator: _sapphire_shapeshift.NumberValidator; +declare const requiredValidator: _sapphire_shapeshift.BooleanValidator; +declare const valueValidator: _sapphire_shapeshift.StringValidator; +declare const placeholderValidator: _sapphire_shapeshift.StringValidator; +declare const labelValidator: _sapphire_shapeshift.StringValidator; +declare function validateRequiredParameters$3(customId?: string, style?: TextInputStyle, label?: string): void; + +declare const Assertions$3_labelValidator: typeof labelValidator; +declare const Assertions$3_maxLengthValidator: typeof maxLengthValidator; +declare const Assertions$3_minLengthValidator: typeof minLengthValidator; +declare const Assertions$3_placeholderValidator: typeof placeholderValidator; +declare const Assertions$3_requiredValidator: typeof requiredValidator; +declare const Assertions$3_textInputStyleValidator: typeof textInputStyleValidator; +declare const Assertions$3_valueValidator: typeof valueValidator; +declare namespace Assertions$3 { + export { + Assertions$3_labelValidator as labelValidator, + Assertions$3_maxLengthValidator as maxLengthValidator, + Assertions$3_minLengthValidator as minLengthValidator, + Assertions$3_placeholderValidator as placeholderValidator, + Assertions$3_requiredValidator as requiredValidator, + Assertions$3_textInputStyleValidator as textInputStyleValidator, + validateRequiredParameters$3 as validateRequiredParameters, + Assertions$3_valueValidator as valueValidator, + }; +} + +/** + * A builder that creates API-compatible JSON data for modals. + */ +declare class ModalBuilder implements JSONEncodable { + /** + * The API data associated with this modal. + */ + readonly data: Partial; + /** + * The components within this modal. + */ + readonly components: ActionRowBuilder[]; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ + constructor({ components, ...data }?: Partial); + /** + * Sets the title of this modal. + * + * @param title - The title to use + */ + setTitle(title: string): this; + /** + * Sets the custom id of this modal. + * + * @param customId - The custom id to use + */ + setCustomId(customId: string): this; + /** + * Adds components to this modal. + * + * @param components - The components to add + */ + addComponents(...components: RestOrArray | APIActionRowComponent>): this; + /** + * Sets components for this modal. + * + * @param components - The components to set + */ + setComponents(...components: RestOrArray>): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIModalInteractionResponseCallbackData; +} + +declare const titleValidator: _sapphire_shapeshift.StringValidator; +declare const componentsValidator: _sapphire_shapeshift.ArrayValidator<[ActionRowBuilder, ...ActionRowBuilder[]], ActionRowBuilder>; +declare function validateRequiredParameters$2(customId?: string, title?: string, components?: ActionRowBuilder[]): void; + +declare const Assertions$2_componentsValidator: typeof componentsValidator; +declare const Assertions$2_titleValidator: typeof titleValidator; +declare namespace Assertions$2 { + export { + Assertions$2_componentsValidator as componentsValidator, + Assertions$2_titleValidator as titleValidator, + validateRequiredParameters$2 as validateRequiredParameters, + }; +} + +/** + * This mixin holds name and description symbols for slash commands. + */ +declare class SharedNameAndDescription { + /** + * The name of this command. + */ + readonly name: string; + /** + * The name localizations of this command. + */ + readonly name_localizations?: LocalizationMap; + /** + * The description of this command. + */ + readonly description: string; + /** + * The description localizations of this command. + */ + readonly description_localizations?: LocalizationMap; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ + setName(name: string): this; + /** + * Sets the description of this command. + * + * @param description - The description to use + */ + setDescription(description: string): this; + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ + setNameLocalization(locale: LocaleString, localizedName: string | null): this; + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ + setNameLocalizations(localizedNames: LocalizationMap | null): this; + /** + * Sets a description localization for this command. + * + * @param locale - The locale to set + * @param localizedDescription - The localized description for the given locale + */ + setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null): this; + /** + * Sets the description localizations for this command. + * + * @param localizedDescriptions - The object of localized descriptions to set + */ + setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null): this; +} + +/** + * The base application command option builder that contains common symbols for application command builders. + */ +declare abstract class ApplicationCommandOptionBase extends SharedNameAndDescription { + /** + * The type of this option. + */ + abstract readonly type: ApplicationCommandOptionType; + /** + * Whether this option is required. + * + * @defaultValue `false` + */ + readonly required: boolean; + /** + * Sets whether this option is required. + * + * @param required - Whether this option should be required + */ + setRequired(required: boolean): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + abstract toJSON(): APIApplicationCommandBasicOption; + /** + * This method runs required validators on this builder. + */ + protected runRequiredValidations(): void; +} + +/** + * A slash command attachment option. + */ +declare class SlashCommandAttachmentOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandAttachmentOption; +} + +/** + * A slash command boolean option. + */ +declare class SlashCommandBooleanOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandBooleanOption; +} + +/** + * The allowed channel types used for a channel option in a slash command builder. + * + * @privateRemarks This can't be dynamic because const enums are erased at runtime. + * @internal + */ +declare const allowedChannelTypes: readonly [ChannelType.GuildText, ChannelType.GuildVoice, ChannelType.GuildCategory, ChannelType.GuildAnnouncement, ChannelType.AnnouncementThread, ChannelType.PublicThread, ChannelType.PrivateThread, ChannelType.GuildStageVoice, ChannelType.GuildForum, ChannelType.GuildMedia]; +/** + * The type of allowed channel types used for a channel option. + */ +type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number]; +/** + * This mixin holds channel type symbols used for options. + */ +declare class ApplicationCommandOptionChannelTypesMixin { + /** + * The channel types of this option. + */ + readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[]; + /** + * Adds channel types to this option. + * + * @param channelTypes - The channel types + */ + addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]): this; +} + +/** + * A slash command channel option. + */ +declare class SlashCommandChannelOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandChannelOption; +} +interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin { +} + +/** + * This mixin holds minimum and maximum symbols used for options. + */ +declare abstract class ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The maximum value of this option. + */ + readonly max_value?: number; + /** + * The minimum value of this option. + */ + readonly min_value?: number; + /** + * Sets the maximum number value of this option. + * + * @param max - The maximum value this option can be + */ + abstract setMaxValue(max: number): this; + /** + * Sets the minimum number value of this option. + * + * @param min - The minimum value this option can be + */ + abstract setMinValue(min: number): this; +} + +/** + * This mixin holds choices and autocomplete symbols used for options. + */ +declare class ApplicationCommandOptionWithChoicesAndAutocompleteMixin { + /** + * The choices of this option. + */ + readonly choices?: APIApplicationCommandOptionChoice[]; + /** + * Whether this option utilizes autocomplete. + */ + readonly autocomplete?: boolean; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ + readonly type: ApplicationCommandOptionType; + /** + * Adds multiple choices to this option. + * + * @param choices - The choices to add + */ + addChoices(...choices: APIApplicationCommandOptionChoice[]): this; + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ + setChoices[]>(...choices: Input): this; + /** + * Whether this option uses autocomplete. + * + * @param autocomplete - Whether this option should use autocomplete + */ + setAutocomplete(autocomplete: boolean): this; +} + +/** + * A slash command integer option. + */ +declare class SlashCommandIntegerOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max: number): this; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandIntegerOption; +} +interface SlashCommandIntegerOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +/** + * A slash command mentionable option. + */ +declare class SlashCommandMentionableOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandMentionableOption; +} + +/** + * A slash command number option. + */ +declare class SlashCommandNumberOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max: number): this; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandNumberOption; +} +interface SlashCommandNumberOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +/** + * A slash command role option. + */ +declare class SlashCommandRoleOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandRoleOption; +} + +/** + * A slash command string option. + */ +declare class SlashCommandStringOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.String; + /** + * The maximum length of this option. + */ + readonly max_length?: number; + /** + * The minimum length of this option. + */ + readonly min_length?: number; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ + setMaxLength(max: number): this; + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ + setMinLength(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandStringOption; +} +interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +/** + * A slash command user option. + */ +declare class SlashCommandUserOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandUserOption; +} + +/** + * This mixin holds symbols that can be shared in slash command options. + * + * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions. + */ +declare class SharedSlashCommandOptions { + readonly options: ToAPIApplicationCommandOptions[]; + /** + * Adds a boolean option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addBooleanOption(input: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a user option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a channel option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addChannelOption(input: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a role option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds an attachment option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addAttachmentOption(input: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a mentionable option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addMentionableOption(input: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a string option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addStringOption(input: Omit | Omit | SlashCommandStringOption | ((builder: SlashCommandStringOption) => Omit | Omit | SlashCommandStringOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds an integer option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addIntegerOption(input: Omit | Omit | SlashCommandIntegerOption | ((builder: SlashCommandIntegerOption) => Omit | Omit | SlashCommandIntegerOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a number option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addNumberOption(input: Omit | Omit | SlashCommandNumberOption | ((builder: SlashCommandNumberOption) => Omit | Omit | SlashCommandNumberOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ + private _sharedAddOptionMethod; +} + +/** + * Represents a folder for subcommands. + * + * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups} + */ +declare class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions { + /** + * The name of this subcommand group. + */ + readonly name: string; + /** + * The description of this subcommand group. + */ + readonly description: string; + /** + * The subcommands within this subcommand group. + */ + readonly options: SlashCommandSubcommandBuilder[]; + /** + * Adds a new subcommand to this group. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ + addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): APIApplicationCommandSubcommandGroupOption; +} +interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription { +} +/** + * A builder that creates API-compatible JSON data for slash command subcommands. + * + * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups} + */ +declare class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions { + /** + * The name of this subcommand. + */ + readonly name: string; + /** + * The description of this subcommand. + */ + readonly description: string; + /** + * The options within this subcommand. + */ + readonly options: ApplicationCommandOptionBase[]; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): APIApplicationCommandSubcommandOption; +} +interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { +} + +/** + * A builder that creates API-compatible JSON data for slash commands. + */ +declare class SlashCommandBuilder { + /** + * The name of this command. + */ + readonly name: string; + /** + * The name localizations of this command. + */ + readonly name_localizations?: LocalizationMap; + /** + * The description of this command. + */ + readonly description: string; + /** + * The description localizations of this command. + */ + readonly description_localizations?: LocalizationMap; + /** + * The options of this command. + */ + readonly options: ToAPIApplicationCommandOptions[]; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + readonly default_permission: boolean | undefined; + /** + * The set of permissions represented as a bit set for the command. + */ + readonly default_member_permissions: Permissions | null | undefined; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + readonly dm_permission: boolean | undefined; + /** + * Whether this command is NSFW. + */ + readonly nsfw: boolean | undefined; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether or not to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. + */ + setDefaultPermission(value: boolean): this; + /** + * Sets the default permissions a member should have in order to run the command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined): this; + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDMPermission(enabled: boolean | null | undefined): this; + /** + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw?: boolean): this; + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder + */ + addSubcommandGroup(input: SlashCommandSubcommandGroupBuilder | ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder)): SlashCommandSubcommandsOnlyBuilder; + /** + * Adds a new subcommand to this command. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ + addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): SlashCommandSubcommandsOnlyBuilder; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody; +} +interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { +} +/** + * An interface specifically for slash command subcommands. + */ +interface SlashCommandSubcommandsOnlyBuilder extends Omit> { +} +/** + * An interface specifically for slash command options. + */ +interface SlashCommandOptionsOnlyBuilder extends SharedNameAndDescription, SharedSlashCommandOptions, Pick { +} +/** + * An interface that ensures the `toJSON()` call will return something + * that can be serialized into API-compatible data. + */ +interface ToAPIApplicationCommandOptions { + toJSON(): APIApplicationCommandOption; +} + +declare function validateName$1(name: unknown): asserts name is string; +declare function validateDescription(description: unknown): asserts description is string; +declare function validateLocale(locale: unknown): Locale; +declare function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[]; +declare function validateRequiredParameters$1(name: string, description: string, options: ToAPIApplicationCommandOptions[]): void; +declare function validateDefaultPermission$1(value: unknown): asserts value is boolean; +declare function validateRequired(required: unknown): asserts required is boolean; +declare function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void; +declare function assertReturnOfBuilder(input: unknown, ExpectedInstanceOf: new () => ReturnType): asserts input is ReturnType; +declare const localizationMapPredicate: _sapphire_shapeshift.UnionValidator<_sapphire_shapeshift.UndefinedToOptional>> | null | undefined>; +declare function validateLocalizationMap(value: unknown): asserts value is LocalizationMap; +declare function validateDMPermission$1(value: unknown): asserts value is boolean | null | undefined; +declare function validateDefaultMemberPermissions$1(permissions: unknown): string | null | undefined; +declare function validateNSFW(value: unknown): asserts value is boolean; + +declare const Assertions$1_assertReturnOfBuilder: typeof assertReturnOfBuilder; +declare const Assertions$1_localizationMapPredicate: typeof localizationMapPredicate; +declare const Assertions$1_validateChoicesLength: typeof validateChoicesLength; +declare const Assertions$1_validateDescription: typeof validateDescription; +declare const Assertions$1_validateLocale: typeof validateLocale; +declare const Assertions$1_validateLocalizationMap: typeof validateLocalizationMap; +declare const Assertions$1_validateMaxOptionsLength: typeof validateMaxOptionsLength; +declare const Assertions$1_validateNSFW: typeof validateNSFW; +declare const Assertions$1_validateRequired: typeof validateRequired; +declare namespace Assertions$1 { + export { + Assertions$1_assertReturnOfBuilder as assertReturnOfBuilder, + Assertions$1_localizationMapPredicate as localizationMapPredicate, + Assertions$1_validateChoicesLength as validateChoicesLength, + validateDMPermission$1 as validateDMPermission, + validateDefaultMemberPermissions$1 as validateDefaultMemberPermissions, + validateDefaultPermission$1 as validateDefaultPermission, + Assertions$1_validateDescription as validateDescription, + Assertions$1_validateLocale as validateLocale, + Assertions$1_validateLocalizationMap as validateLocalizationMap, + Assertions$1_validateMaxOptionsLength as validateMaxOptionsLength, + Assertions$1_validateNSFW as validateNSFW, + validateName$1 as validateName, + Assertions$1_validateRequired as validateRequired, + validateRequiredParameters$1 as validateRequiredParameters, + }; +} + +/** + * The type a context menu command can be. + */ +type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User; +/** + * A builder that creates API-compatible JSON data for context menu commands. + */ +declare class ContextMenuCommandBuilder { + /** + * The name of this command. + */ + readonly name: string; + /** + * The name localizations of this command. + */ + readonly name_localizations?: LocalizationMap; + /** + * The type of this command. + */ + readonly type: ContextMenuCommandType; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + readonly default_permission: boolean | undefined; + /** + * The set of permissions represented as a bit set for the command. + */ + readonly default_member_permissions: Permissions | null | undefined; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + readonly dm_permission: boolean | undefined; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ + setName(name: string): this; + /** + * Sets the type of this command. + * + * @param type - The type to use + */ + setType(type: ContextMenuCommandType): this; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + setDefaultPermission(value: boolean): this; + /** + * Sets the default permissions a member should have in order to run this command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined): this; + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDMPermission(enabled: boolean | null | undefined): this; + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ + setNameLocalization(locale: LocaleString, localizedName: string | null): this; + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ + setNameLocalizations(localizedNames: LocalizationMap | null): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody; +} + +declare function validateDefaultPermission(value: unknown): asserts value is boolean; +declare function validateName(name: unknown): asserts name is string; +declare function validateType(type: unknown): asserts type is ContextMenuCommandType; +declare function validateRequiredParameters(name: string, type: number): void; +declare function validateDMPermission(value: unknown): asserts value is boolean | null | undefined; +declare function validateDefaultMemberPermissions(permissions: unknown): string | null | undefined; + +declare const Assertions_validateDMPermission: typeof validateDMPermission; +declare const Assertions_validateDefaultMemberPermissions: typeof validateDefaultMemberPermissions; +declare const Assertions_validateDefaultPermission: typeof validateDefaultPermission; +declare const Assertions_validateName: typeof validateName; +declare const Assertions_validateRequiredParameters: typeof validateRequiredParameters; +declare const Assertions_validateType: typeof validateType; +declare namespace Assertions { + export { + Assertions_validateDMPermission as validateDMPermission, + Assertions_validateDefaultMemberPermissions as validateDefaultMemberPermissions, + Assertions_validateDefaultPermission as validateDefaultPermission, + Assertions_validateName as validateName, + Assertions_validateRequiredParameters as validateRequiredParameters, + Assertions_validateType as validateType, + }; +} + +/** + * Calculates the length of the embed. + * + * @param data - The embed data to check + */ +declare function embedLength(data: APIEmbed): number; + +/** + * Enables validators. + * + * @returns Whether validation is occurring. + */ +declare function enableValidators(): boolean; +/** + * Disables validators. + * + * @returns Whether validation is occurring. + */ +declare function disableValidators(): boolean; +/** + * Checks whether validation is occurring. + */ +declare function isValidationEnabled(): boolean; + +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version + * that you are currently using. + * + * @privateRemarks This needs to explicitly be `string` so it is not typed as a "const string" that gets injected by esbuild. + */ +declare const version: string; + +export { ActionRowBuilder, AnyAPIActionRowComponent, AnyComponentBuilder, ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionAllowedChannelTypes, ApplicationCommandOptionBase, ApplicationCommandOptionChannelTypesMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin, BaseSelectMenuBuilder, ButtonBuilder, ChannelSelectMenuBuilder, Assertions$4 as ComponentAssertions, ComponentBuilder, Assertions as ContextMenuCommandAssertions, ContextMenuCommandBuilder, ContextMenuCommandType, Assertions$5 as EmbedAssertions, EmbedAuthorData, EmbedAuthorOptions, EmbedBuilder, EmbedFooterData, EmbedFooterOptions, EmbedImageData, IconData, MappedComponentTypes, MentionableSelectMenuBuilder, MessageActionRowComponentBuilder, MessageComponentBuilder, ModalActionRowComponentBuilder, Assertions$2 as ModalAssertions, ModalBuilder, ModalComponentBuilder, RGBTuple, RestOrArray, RoleSelectMenuBuilder, StringSelectMenuBuilder as SelectMenuBuilder, StringSelectMenuOptionBuilder as SelectMenuOptionBuilder, SharedNameAndDescription, SharedSlashCommandOptions, Assertions$1 as SlashCommandAssertions, SlashCommandAttachmentOption, SlashCommandBooleanOption, SlashCommandBuilder, SlashCommandChannelOption, SlashCommandIntegerOption, SlashCommandMentionableOption, SlashCommandNumberOption, SlashCommandOptionsOnlyBuilder, SlashCommandRoleOption, SlashCommandStringOption, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder, SlashCommandSubcommandsOnlyBuilder, SlashCommandUserOption, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, Assertions$3 as TextInputAssertions, TextInputBuilder, ToAPIApplicationCommandOptions, UserSelectMenuBuilder, createComponentBuilder, disableValidators, embedLength, enableValidators, isValidationEnabled, normalizeArray, version }; diff --git a/node_modules/@discordjs/builders/dist/index.d.ts b/node_modules/@discordjs/builders/dist/index.d.ts new file mode 100644 index 0000000..0280fc5 --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.d.ts @@ -0,0 +1,2008 @@ +import * as _sapphire_shapeshift from '@sapphire/shapeshift'; +import { APIEmbedField, APIEmbedAuthor, APIEmbedFooter, APIEmbedImage, APIEmbed, APISelectMenuOption, APIMessageComponentEmoji, ButtonStyle, ChannelType, APIActionRowComponent, APIActionRowComponentTypes, APIBaseComponent, ComponentType, APIButtonComponent, APISelectMenuComponent, APIChannelSelectComponent, Snowflake, APIMentionableSelectComponent, APISelectMenuDefaultValue, SelectMenuDefaultValueType, APIRoleSelectComponent, APIStringSelectComponent, APIUserSelectComponent, APITextInputComponent, TextInputStyle, APIMessageActionRowComponent, APIModalActionRowComponent, APIModalComponent, APIMessageComponent, APIModalInteractionResponseCallbackData, LocalizationMap, LocaleString, ApplicationCommandOptionType, APIApplicationCommandBasicOption, APIApplicationCommandAttachmentOption, APIApplicationCommandBooleanOption, APIApplicationCommandChannelOption, APIApplicationCommandOptionChoice, APIApplicationCommandIntegerOption, APIApplicationCommandMentionableOption, APIApplicationCommandNumberOption, APIApplicationCommandRoleOption, APIApplicationCommandStringOption, APIApplicationCommandUserOption, APIApplicationCommandSubcommandGroupOption, APIApplicationCommandSubcommandOption, Permissions, RESTPostAPIChatInputApplicationCommandsJSONBody, APIApplicationCommandOption, Locale, ApplicationCommandType, RESTPostAPIContextMenuApplicationCommandsJSONBody } from 'discord-api-types/v10'; +export * from '@discordjs/formatters'; +import { JSONEncodable, Equatable } from '@discordjs/util'; + +declare const fieldNamePredicate: _sapphire_shapeshift.StringValidator; +declare const fieldValuePredicate: _sapphire_shapeshift.StringValidator; +declare const fieldInlinePredicate: _sapphire_shapeshift.UnionValidator; +declare const embedFieldPredicate: _sapphire_shapeshift.ObjectValidator<{ + name: string; + value: string; + inline: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>>; +declare const embedFieldsArrayPredicate: _sapphire_shapeshift.ArrayValidator<_sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>[], _sapphire_shapeshift.UndefinedToOptional<{ + name: string; + value: string; + inline: boolean | undefined; +}>>; +declare const fieldLengthPredicate: _sapphire_shapeshift.NumberValidator; +declare function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void; +declare const authorNamePredicate: _sapphire_shapeshift.UnionValidator; +declare const imageURLPredicate: _sapphire_shapeshift.UnionValidator; +declare const urlPredicate: _sapphire_shapeshift.UnionValidator; +declare const embedAuthorPredicate: _sapphire_shapeshift.ObjectValidator<{ + name: string | null; + iconURL: string | null | undefined; + url: string | null | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name: string | null; + iconURL: string | null | undefined; + url: string | null | undefined; +}>>; +declare const RGBPredicate: _sapphire_shapeshift.NumberValidator; +declare const colorPredicate: _sapphire_shapeshift.UnionValidator; +declare const descriptionPredicate: _sapphire_shapeshift.UnionValidator; +declare const footerTextPredicate: _sapphire_shapeshift.UnionValidator; +declare const embedFooterPredicate: _sapphire_shapeshift.ObjectValidator<{ + text: string | null; + iconURL: string | null | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + text: string | null; + iconURL: string | null | undefined; +}>>; +declare const timestampPredicate: _sapphire_shapeshift.UnionValidator; +declare const titlePredicate: _sapphire_shapeshift.UnionValidator; + +declare const Assertions$5_RGBPredicate: typeof RGBPredicate; +declare const Assertions$5_authorNamePredicate: typeof authorNamePredicate; +declare const Assertions$5_colorPredicate: typeof colorPredicate; +declare const Assertions$5_descriptionPredicate: typeof descriptionPredicate; +declare const Assertions$5_embedAuthorPredicate: typeof embedAuthorPredicate; +declare const Assertions$5_embedFieldPredicate: typeof embedFieldPredicate; +declare const Assertions$5_embedFieldsArrayPredicate: typeof embedFieldsArrayPredicate; +declare const Assertions$5_embedFooterPredicate: typeof embedFooterPredicate; +declare const Assertions$5_fieldInlinePredicate: typeof fieldInlinePredicate; +declare const Assertions$5_fieldLengthPredicate: typeof fieldLengthPredicate; +declare const Assertions$5_fieldNamePredicate: typeof fieldNamePredicate; +declare const Assertions$5_fieldValuePredicate: typeof fieldValuePredicate; +declare const Assertions$5_footerTextPredicate: typeof footerTextPredicate; +declare const Assertions$5_imageURLPredicate: typeof imageURLPredicate; +declare const Assertions$5_timestampPredicate: typeof timestampPredicate; +declare const Assertions$5_titlePredicate: typeof titlePredicate; +declare const Assertions$5_urlPredicate: typeof urlPredicate; +declare const Assertions$5_validateFieldLength: typeof validateFieldLength; +declare namespace Assertions$5 { + export { + Assertions$5_RGBPredicate as RGBPredicate, + Assertions$5_authorNamePredicate as authorNamePredicate, + Assertions$5_colorPredicate as colorPredicate, + Assertions$5_descriptionPredicate as descriptionPredicate, + Assertions$5_embedAuthorPredicate as embedAuthorPredicate, + Assertions$5_embedFieldPredicate as embedFieldPredicate, + Assertions$5_embedFieldsArrayPredicate as embedFieldsArrayPredicate, + Assertions$5_embedFooterPredicate as embedFooterPredicate, + Assertions$5_fieldInlinePredicate as fieldInlinePredicate, + Assertions$5_fieldLengthPredicate as fieldLengthPredicate, + Assertions$5_fieldNamePredicate as fieldNamePredicate, + Assertions$5_fieldValuePredicate as fieldValuePredicate, + Assertions$5_footerTextPredicate as footerTextPredicate, + Assertions$5_imageURLPredicate as imageURLPredicate, + Assertions$5_timestampPredicate as timestampPredicate, + Assertions$5_titlePredicate as titlePredicate, + Assertions$5_urlPredicate as urlPredicate, + Assertions$5_validateFieldLength as validateFieldLength, + }; +} + +/** + * Normalizes data that is a rest parameter or an array into an array with a depth of 1. + * + * @typeParam ItemType - The data that must satisfy {@link RestOrArray}. + * @param arr - The (possibly variadic) data to normalize + */ +declare function normalizeArray(arr: RestOrArray): ItemType[]; +/** + * Represents data that may be an array or came from a rest parameter. + * + * @remarks + * This type is used throughout builders to ensure both an array and variadic arguments + * may be used. It is normalized with {@link normalizeArray}. + */ +type RestOrArray = Type[] | [Type[]]; + +/** + * A tuple satisfying the RGB color model. + * + * @see {@link https://developer.mozilla.org/docs/Glossary/RGB} + */ +type RGBTuple = [red: number, green: number, blue: number]; +/** + * The base icon data typically used in payloads. + */ +interface IconData { + /** + * The URL of the icon. + */ + iconURL?: string; + /** + * The proxy URL of the icon. + */ + proxyIconURL?: string; +} +/** + * Represents the author data of an embed. + */ +type EmbedAuthorData = IconData & Omit; +/** + * Represents the author options of an embed. + */ +type EmbedAuthorOptions = Omit; +/** + * Represents the footer data of an embed. + */ +type EmbedFooterData = IconData & Omit; +/** + * Represents the footer options of an embed. + */ +type EmbedFooterOptions = Omit; +/** + * Represents the image data of an embed. + */ +interface EmbedImageData extends Omit { + /** + * The proxy URL for the image. + */ + proxyURL?: string; +} +/** + * A builder that creates API-compatible JSON data for embeds. + */ +declare class EmbedBuilder { + /** + * The API data associated with this embed. + */ + readonly data: APIEmbed; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ + constructor(data?: APIEmbed); + /** + * Appends fields to the embed. + * + * @remarks + * This method accepts either an array of fields or a variable number of field parameters. + * The maximum amount of fields that can be added is 25. + * @example + * Using an array: + * ```ts + * const fields: APIEmbedField[] = ...; + * const embed = new EmbedBuilder() + * .addFields(fields); + * ``` + * @example + * Using rest parameters (variadic): + * ```ts + * const embed = new EmbedBuilder() + * .addFields( + * { name: 'Field 1', value: 'Value 1' }, + * { name: 'Field 2', value: 'Value 2' }, + * ); + * ``` + * @param fields - The fields to add + */ + addFields(...fields: RestOrArray): this; + /** + * Removes, replaces, or inserts fields for this embed. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. + * The maximum amount of fields that can be added is 25. + * + * It's useful for modifying and adjusting order of the already-existing fields of an embed. + * @example + * Remove the first field: + * ```ts + * embed.spliceFields(0, 1); + * ``` + * @example + * Remove the first n fields: + * ```ts + * const n = 4; + * embed.spliceFields(0, n); + * ``` + * @example + * Remove the last field: + * ```ts + * embed.spliceFields(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of fields to remove + * @param fields - The replacing field objects + */ + spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this; + /** + * Sets the fields for this embed. + * + * @remarks + * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, + * it splices the entire array of fields, replacing them with the provided fields. + * + * You can set a maximum of 25 fields. + * @param fields - The fields to set + */ + setFields(...fields: RestOrArray): this; + /** + * Sets the author of this embed. + * + * @param options - The options to use + */ + setAuthor(options: EmbedAuthorOptions | null): this; + /** + * Sets the color of this embed. + * + * @param color - The color to use + */ + setColor(color: RGBTuple | number | null): this; + /** + * Sets the description of this embed. + * + * @param description - The description to use + */ + setDescription(description: string | null): this; + /** + * Sets the footer of this embed. + * + * @param options - The footer to use + */ + setFooter(options: EmbedFooterOptions | null): this; + /** + * Sets the image of this embed. + * + * @param url - The image URL to use + */ + setImage(url: string | null): this; + /** + * Sets the thumbnail of this embed. + * + * @param url - The thumbnail URL to use + */ + setThumbnail(url: string | null): this; + /** + * Sets the timestamp of this embed. + * + * @param timestamp - The timestamp or date to use + */ + setTimestamp(timestamp?: Date | number | null): this; + /** + * Sets the title for this embed. + * + * @param title - The title to use + */ + setTitle(title: string | null): this; + /** + * Sets the URL of this embed. + * + * @param url - The URL to use + */ + setURL(url: string | null): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): APIEmbed; +} + +/** + * A builder that creates API-compatible JSON data for string select menu options. + */ +declare class StringSelectMenuOptionBuilder implements JSONEncodable { + data: Partial; + /** + * Creates a new string select menu option from API data. + * + * @param data - The API data to create this string select menu option with + * @example + * Creating a string select menu option from an API data object: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * label: 'catchy label', + * value: '1', + * }); + * ``` + * @example + * Creating a string select menu option using setters and API data: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * default: true, + * value: '1', + * }) + * .setLabel('woah'); + * ``` + */ + constructor(data?: Partial); + /** + * Sets the label for this option. + * + * @param label - The label to use + */ + setLabel(label: string): this; + /** + * Sets the value for this option. + * + * @param value - The value to use + */ + setValue(value: string): this; + /** + * Sets the description for this option. + * + * @param description - The description to use + */ + setDescription(description: string): this; + /** + * Sets whether this option is selected by default. + * + * @param isDefault - Whether this option is selected by default + */ + setDefault(isDefault?: boolean): this; + /** + * Sets the emoji to display for this option. + * + * @param emoji - The emoji to use + */ + setEmoji(emoji: APIMessageComponentEmoji): this; + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON(): APISelectMenuOption; +} + +declare const customIdValidator: _sapphire_shapeshift.StringValidator; +declare const emojiValidator: _sapphire_shapeshift.ObjectValidator<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; +}>>; +declare const disabledValidator: _sapphire_shapeshift.BooleanValidator; +declare const buttonLabelValidator: _sapphire_shapeshift.StringValidator; +declare const buttonStyleValidator: _sapphire_shapeshift.NativeEnumValidator; +declare const placeholderValidator$1: _sapphire_shapeshift.StringValidator; +declare const minMaxValidator: _sapphire_shapeshift.NumberValidator; +declare const labelValueDescriptionValidator: _sapphire_shapeshift.StringValidator; +declare const jsonOptionValidator: _sapphire_shapeshift.ObjectValidator<{ + label: string; + value: string; + description: string | undefined; + emoji: _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; + }> | undefined; + default: boolean | undefined; +}, _sapphire_shapeshift.UndefinedToOptional<{ + label: string; + value: string; + description: string | undefined; + emoji: _sapphire_shapeshift.UndefinedToOptional<{ + name?: string | undefined; + id?: string | undefined; + animated?: boolean | undefined; + }> | undefined; + default: boolean | undefined; +}>>; +declare const optionValidator: _sapphire_shapeshift.InstanceValidator; +declare const optionsValidator: _sapphire_shapeshift.ArrayValidator; +declare const optionsLengthValidator: _sapphire_shapeshift.NumberValidator; +declare function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string): void; +declare const defaultValidator: _sapphire_shapeshift.BooleanValidator; +declare function validateRequiredSelectMenuOptionParameters(label?: string, value?: string): void; +declare const channelTypesValidator: _sapphire_shapeshift.ArrayValidator; +declare const urlValidator: _sapphire_shapeshift.StringValidator; +declare function validateRequiredButtonParameters(style?: ButtonStyle, label?: string, emoji?: APIMessageComponentEmoji, customId?: string, url?: string): void; + +declare const Assertions$4_buttonLabelValidator: typeof buttonLabelValidator; +declare const Assertions$4_buttonStyleValidator: typeof buttonStyleValidator; +declare const Assertions$4_channelTypesValidator: typeof channelTypesValidator; +declare const Assertions$4_customIdValidator: typeof customIdValidator; +declare const Assertions$4_defaultValidator: typeof defaultValidator; +declare const Assertions$4_disabledValidator: typeof disabledValidator; +declare const Assertions$4_emojiValidator: typeof emojiValidator; +declare const Assertions$4_jsonOptionValidator: typeof jsonOptionValidator; +declare const Assertions$4_labelValueDescriptionValidator: typeof labelValueDescriptionValidator; +declare const Assertions$4_minMaxValidator: typeof minMaxValidator; +declare const Assertions$4_optionValidator: typeof optionValidator; +declare const Assertions$4_optionsLengthValidator: typeof optionsLengthValidator; +declare const Assertions$4_optionsValidator: typeof optionsValidator; +declare const Assertions$4_urlValidator: typeof urlValidator; +declare const Assertions$4_validateRequiredButtonParameters: typeof validateRequiredButtonParameters; +declare const Assertions$4_validateRequiredSelectMenuOptionParameters: typeof validateRequiredSelectMenuOptionParameters; +declare const Assertions$4_validateRequiredSelectMenuParameters: typeof validateRequiredSelectMenuParameters; +declare namespace Assertions$4 { + export { + Assertions$4_buttonLabelValidator as buttonLabelValidator, + Assertions$4_buttonStyleValidator as buttonStyleValidator, + Assertions$4_channelTypesValidator as channelTypesValidator, + Assertions$4_customIdValidator as customIdValidator, + Assertions$4_defaultValidator as defaultValidator, + Assertions$4_disabledValidator as disabledValidator, + Assertions$4_emojiValidator as emojiValidator, + Assertions$4_jsonOptionValidator as jsonOptionValidator, + Assertions$4_labelValueDescriptionValidator as labelValueDescriptionValidator, + Assertions$4_minMaxValidator as minMaxValidator, + Assertions$4_optionValidator as optionValidator, + Assertions$4_optionsLengthValidator as optionsLengthValidator, + Assertions$4_optionsValidator as optionsValidator, + placeholderValidator$1 as placeholderValidator, + Assertions$4_urlValidator as urlValidator, + Assertions$4_validateRequiredButtonParameters as validateRequiredButtonParameters, + Assertions$4_validateRequiredSelectMenuOptionParameters as validateRequiredSelectMenuOptionParameters, + Assertions$4_validateRequiredSelectMenuParameters as validateRequiredSelectMenuParameters, + }; +} + +/** + * Any action row component data represented as an object. + */ +type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes; +/** + * The base component builder that contains common symbols for all sorts of components. + * + * @typeParam DataType - The type of internal API data that is stored within the component + */ +declare abstract class ComponentBuilder> = APIBaseComponent> implements JSONEncodable { + /** + * The API data associated with this component. + */ + readonly data: Partial; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + abstract toJSON(): AnyAPIActionRowComponent; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ + constructor(data: Partial); +} + +/** + * A builder that creates API-compatible JSON data for buttons. + */ +declare class ButtonBuilder extends ComponentBuilder { + /** + * Creates a new button from API data. + * + * @param data - The API data to create this button with + * @example + * Creating a button from an API data object: + * ```ts + * const button = new ButtonBuilder({ + * custom_id: 'a cool button', + * style: ButtonStyle.Primary, + * label: 'Click Me', + * emoji: { + * name: 'smile', + * id: '123456789012345678', + * }, + * }); + * ``` + * @example + * Creating a button using setters and API data: + * ```ts + * const button = new ButtonBuilder({ + * style: ButtonStyle.Secondary, + * label: 'Click Me', + * }) + * .setEmoji({ name: '🙂' }) + * .setCustomId('another cool button'); + * ``` + */ + constructor(data?: Partial); + /** + * Sets the style of this button. + * + * @param style - The style to use + */ + setStyle(style: ButtonStyle): this; + /** + * Sets the URL for this button. + * + * @remarks + * This method is only available to buttons using the `Link` button style. + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use + */ + setURL(url: string): this; + /** + * Sets the custom id for this button. + * + * @remarks + * This method is only applicable to buttons that are not using the `Link` button style. + * @param customId - The custom id to use + */ + setCustomId(customId: string): this; + /** + * Sets the emoji to display on this button. + * + * @param emoji - The emoji to use + */ + setEmoji(emoji: APIMessageComponentEmoji): this; + /** + * Sets whether this button is disabled. + * + * @param disabled - Whether to disable this button + */ + setDisabled(disabled?: boolean): this; + /** + * Sets the label for this button. + * + * @param label - The label to use + */ + setLabel(label: string): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIButtonComponent; +} + +/** + * The base select menu builder that contains common symbols for select menu builders. + * + * @typeParam SelectMenuType - The type of select menu this would be instantiated for. + */ +declare abstract class BaseSelectMenuBuilder extends ComponentBuilder { + /** + * Sets the placeholder for this select menu. + * + * @param placeholder - The placeholder to use + */ + setPlaceholder(placeholder: string): this; + /** + * Sets the minimum values that must be selected in the select menu. + * + * @param minValues - The minimum values that must be selected + */ + setMinValues(minValues: number): this; + /** + * Sets the maximum values that must be selected in the select menu. + * + * @param maxValues - The maximum values that must be selected + */ + setMaxValues(maxValues: number): this; + /** + * Sets the custom id for this select menu. + * + * @param customId - The custom id to use + */ + setCustomId(customId: string): this; + /** + * Sets whether this select menu is disabled. + * + * @param disabled - Whether this select menu is disabled + */ + setDisabled(disabled?: boolean): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): SelectMenuType; +} + +/** + * A builder that creates API-compatible JSON data for channel select menus. + */ +declare class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) + * .setMinValues(2); + * ``` + */ + constructor(data?: Partial); + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ + addChannelTypes(...types: RestOrArray): this; + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ + setChannelTypes(...types: RestOrArray): this; + /** + * Adds default channels to this auto populated select menu. + * + * @param channels - The channels to add + */ + addDefaultChannels(...channels: RestOrArray): this; + /** + * Sets default channels to this auto populated select menu. + * + * @param channels - The channels to set + */ + setDefaultChannels(...channels: RestOrArray): this; + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON(): APIChannelSelectComponent; +} + +/** + * A builder that creates API-compatible JSON data for mentionable select menus. + */ +declare class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data?: Partial); + /** + * Adds default roles to this auto populated select menu. + * + * @param roles - The roles to add + */ + addDefaultRoles(...roles: RestOrArray): this; + /** + * Adds default users to this auto populated select menu. + * + * @param users - The users to add + */ + addDefaultUsers(...users: RestOrArray): this; + /** + * Adds default values to this auto populated select menu. + * + * @param values - The values to add + */ + addDefaultValues(...values: RestOrArray | APISelectMenuDefaultValue>): this; + /** + * Sets default values to this auto populated select menu. + * + * @param values - The values to set + */ + setDefaultValues(...values: RestOrArray | APISelectMenuDefaultValue>): this; +} + +/** + * A builder that creates API-compatible JSON data for role select menus. + */ +declare class RoleSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data?: Partial); + /** + * Adds default roles to this auto populated select menu. + * + * @param roles - The roles to add + */ + addDefaultRoles(...roles: RestOrArray): this; + /** + * Sets default roles to this auto populated select menu. + * + * @param roles - The roles to set + */ + setDefaultRoles(...roles: RestOrArray): this; +} + +/** + * A builder that creates API-compatible JSON data for string select menus. + */ +declare class StringSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * The options within this select menu. + */ + readonly options: StringSelectMenuOptionBuilder[]; + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * options: [ + * { label: 'option 1', value: '1' }, + * { label: 'option 2', value: '2' }, + * { label: 'option 3', value: '3' }, + * ], + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1) + * .addOptions({ + * label: 'Catchy', + * value: 'catch', + * }); + * ``` + */ + constructor(data?: Partial); + /** + * Adds options to this select menu. + * + * @param options - The options to add + */ + addOptions(...options: RestOrArray): this; + /** + * Sets the options for this select menu. + * + * @param options - The options to set + */ + setOptions(...options: RestOrArray): this; + /** + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index: number, deleteCount: number, ...options: RestOrArray): this; + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON(): APIStringSelectComponent; +} + +/** + * A builder that creates API-compatible JSON data for user select menus. + */ +declare class UserSelectMenuBuilder extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data?: Partial); + /** + * Adds default users to this auto populated select menu. + * + * @param users - The users to add + */ + addDefaultUsers(...users: RestOrArray): this; + /** + * Sets default users to this auto populated select menu. + * + * @param users - The users to set + */ + setDefaultUsers(...users: RestOrArray): this; +} + +/** + * A builder that creates API-compatible JSON data for text inputs. + */ +declare class TextInputBuilder extends ComponentBuilder implements Equatable> { + /** + * Creates a new text input from API data. + * + * @param data - The API data to create this text input with + * @example + * Creating a select menu option from an API data object: + * ```ts + * const textInput = new TextInputBuilder({ + * custom_id: 'a cool select menu', + * label: 'Type something', + * style: TextInputStyle.Short, + * }); + * ``` + * @example + * Creating a select menu option using setters and API data: + * ```ts + * const textInput = new TextInputBuilder({ + * label: 'Type something else', + * }) + * .setCustomId('woah') + * .setStyle(TextInputStyle.Paragraph); + * ``` + */ + constructor(data?: APITextInputComponent & { + type?: ComponentType.TextInput; + }); + /** + * Sets the custom id for this text input. + * + * @param customId - The custom id to use + */ + setCustomId(customId: string): this; + /** + * Sets the label for this text input. + * + * @param label - The label to use + */ + setLabel(label: string): this; + /** + * Sets the style for this text input. + * + * @param style - The style to use + */ + setStyle(style: TextInputStyle): this; + /** + * Sets the minimum length of text for this text input. + * + * @param minLength - The minimum length of text for this text input + */ + setMinLength(minLength: number): this; + /** + * Sets the maximum length of text for this text input. + * + * @param maxLength - The maximum length of text for this text input + */ + setMaxLength(maxLength: number): this; + /** + * Sets the placeholder for this text input. + * + * @param placeholder - The placeholder to use + */ + setPlaceholder(placeholder: string): this; + /** + * Sets the value for this text input. + * + * @param value - The value to use + */ + setValue(value: string): this; + /** + * Sets whether this text input is required. + * + * @param required - Whether this text input is required + */ + setRequired(required?: boolean): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APITextInputComponent; + /** + * {@inheritDoc Equatable.equals} + */ + equals(other: APITextInputComponent | JSONEncodable): boolean; +} + +/** + * The builders that may be used for messages. + */ +type MessageComponentBuilder = ActionRowBuilder | MessageActionRowComponentBuilder; +/** + * The builders that may be used for modals. + */ +type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder; +/** + * The builders that may be used within an action row for messages. + */ +type MessageActionRowComponentBuilder = ButtonBuilder | ChannelSelectMenuBuilder | MentionableSelectMenuBuilder | RoleSelectMenuBuilder | StringSelectMenuBuilder | UserSelectMenuBuilder; +/** + * The builders that may be used within an action row for modals. + */ +type ModalActionRowComponentBuilder = TextInputBuilder; +/** + * Any builder. + */ +type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder; +/** + * A builder that creates API-compatible JSON data for action rows. + * + * @typeParam ComponentType - The types of components this action row holds + */ +declare class ActionRowBuilder extends ComponentBuilder> { + /** + * The components within this action row. + */ + readonly components: ComponentType[]; + /** + * Creates a new action row from API data. + * + * @param data - The API data to create this action row with + * @example + * Creating an action row from an API data object: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Type something", + * style: TextInputStyle.Short, + * type: ComponentType.TextInput, + * }, + * ], + * }); + * ``` + * @example + * Creating an action row using setters and API data: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Click me", + * style: ButtonStyle.Primary, + * type: ComponentType.Button, + * }, + * ], + * }) + * .addComponents(button2, button3); + * ``` + */ + constructor({ components, ...data }?: Partial>); + /** + * Adds components to this action row. + * + * @param components - The components to add + */ + addComponents(...components: RestOrArray): this; + /** + * Sets components for this action row. + * + * @param components - The components to set + */ + setComponents(...components: RestOrArray): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIActionRowComponent>; +} + +/** + * Components here are mapped to their respective builder. + */ +interface MappedComponentTypes { + /** + * The action row component type is associated with an {@link ActionRowBuilder}. + */ + [ComponentType.ActionRow]: ActionRowBuilder; + /** + * The button component type is associated with an {@link ButtonBuilder}. + */ + [ComponentType.Button]: ButtonBuilder; + /** + * The string select component type is associated with an {@link StringSelectMenuBuilder}. + */ + [ComponentType.StringSelect]: StringSelectMenuBuilder; + /** + * The text inpiut component type is associated with an {@link TextInputBuilder}. + */ + [ComponentType.TextInput]: TextInputBuilder; + /** + * The user select component type is associated with an {@link UserSelectMenuBuilder}. + */ + [ComponentType.UserSelect]: UserSelectMenuBuilder; + /** + * The role select component type is associated with an {@link RoleSelectMenuBuilder}. + */ + [ComponentType.RoleSelect]: RoleSelectMenuBuilder; + /** + * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}. + */ + [ComponentType.MentionableSelect]: MentionableSelectMenuBuilder; + /** + * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}. + */ + [ComponentType.ChannelSelect]: ChannelSelectMenuBuilder; +} +/** + * Factory for creating components from API data. + * + * @typeParam ComponentType - The type of component to use + * @param data - The API data to transform to a component class + */ +declare function createComponentBuilder(data: (APIModalComponent | APIMessageComponent) & { + type: ComponentType; +}): MappedComponentTypes[ComponentType]; +/** + * Factory for creating components from API data. + * + * @typeParam ComponentBuilder - The type of component to use + * @param data - The API data to transform to a component class + */ +declare function createComponentBuilder(data: ComponentBuilder): ComponentBuilder; + +declare const textInputStyleValidator: _sapphire_shapeshift.NativeEnumValidator; +declare const minLengthValidator: _sapphire_shapeshift.NumberValidator; +declare const maxLengthValidator: _sapphire_shapeshift.NumberValidator; +declare const requiredValidator: _sapphire_shapeshift.BooleanValidator; +declare const valueValidator: _sapphire_shapeshift.StringValidator; +declare const placeholderValidator: _sapphire_shapeshift.StringValidator; +declare const labelValidator: _sapphire_shapeshift.StringValidator; +declare function validateRequiredParameters$3(customId?: string, style?: TextInputStyle, label?: string): void; + +declare const Assertions$3_labelValidator: typeof labelValidator; +declare const Assertions$3_maxLengthValidator: typeof maxLengthValidator; +declare const Assertions$3_minLengthValidator: typeof minLengthValidator; +declare const Assertions$3_placeholderValidator: typeof placeholderValidator; +declare const Assertions$3_requiredValidator: typeof requiredValidator; +declare const Assertions$3_textInputStyleValidator: typeof textInputStyleValidator; +declare const Assertions$3_valueValidator: typeof valueValidator; +declare namespace Assertions$3 { + export { + Assertions$3_labelValidator as labelValidator, + Assertions$3_maxLengthValidator as maxLengthValidator, + Assertions$3_minLengthValidator as minLengthValidator, + Assertions$3_placeholderValidator as placeholderValidator, + Assertions$3_requiredValidator as requiredValidator, + Assertions$3_textInputStyleValidator as textInputStyleValidator, + validateRequiredParameters$3 as validateRequiredParameters, + Assertions$3_valueValidator as valueValidator, + }; +} + +/** + * A builder that creates API-compatible JSON data for modals. + */ +declare class ModalBuilder implements JSONEncodable { + /** + * The API data associated with this modal. + */ + readonly data: Partial; + /** + * The components within this modal. + */ + readonly components: ActionRowBuilder[]; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ + constructor({ components, ...data }?: Partial); + /** + * Sets the title of this modal. + * + * @param title - The title to use + */ + setTitle(title: string): this; + /** + * Sets the custom id of this modal. + * + * @param customId - The custom id to use + */ + setCustomId(customId: string): this; + /** + * Adds components to this modal. + * + * @param components - The components to add + */ + addComponents(...components: RestOrArray | APIActionRowComponent>): this; + /** + * Sets components for this modal. + * + * @param components - The components to set + */ + setComponents(...components: RestOrArray>): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON(): APIModalInteractionResponseCallbackData; +} + +declare const titleValidator: _sapphire_shapeshift.StringValidator; +declare const componentsValidator: _sapphire_shapeshift.ArrayValidator<[ActionRowBuilder, ...ActionRowBuilder[]], ActionRowBuilder>; +declare function validateRequiredParameters$2(customId?: string, title?: string, components?: ActionRowBuilder[]): void; + +declare const Assertions$2_componentsValidator: typeof componentsValidator; +declare const Assertions$2_titleValidator: typeof titleValidator; +declare namespace Assertions$2 { + export { + Assertions$2_componentsValidator as componentsValidator, + Assertions$2_titleValidator as titleValidator, + validateRequiredParameters$2 as validateRequiredParameters, + }; +} + +/** + * This mixin holds name and description symbols for slash commands. + */ +declare class SharedNameAndDescription { + /** + * The name of this command. + */ + readonly name: string; + /** + * The name localizations of this command. + */ + readonly name_localizations?: LocalizationMap; + /** + * The description of this command. + */ + readonly description: string; + /** + * The description localizations of this command. + */ + readonly description_localizations?: LocalizationMap; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ + setName(name: string): this; + /** + * Sets the description of this command. + * + * @param description - The description to use + */ + setDescription(description: string): this; + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ + setNameLocalization(locale: LocaleString, localizedName: string | null): this; + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ + setNameLocalizations(localizedNames: LocalizationMap | null): this; + /** + * Sets a description localization for this command. + * + * @param locale - The locale to set + * @param localizedDescription - The localized description for the given locale + */ + setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null): this; + /** + * Sets the description localizations for this command. + * + * @param localizedDescriptions - The object of localized descriptions to set + */ + setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null): this; +} + +/** + * The base application command option builder that contains common symbols for application command builders. + */ +declare abstract class ApplicationCommandOptionBase extends SharedNameAndDescription { + /** + * The type of this option. + */ + abstract readonly type: ApplicationCommandOptionType; + /** + * Whether this option is required. + * + * @defaultValue `false` + */ + readonly required: boolean; + /** + * Sets whether this option is required. + * + * @param required - Whether this option should be required + */ + setRequired(required: boolean): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + abstract toJSON(): APIApplicationCommandBasicOption; + /** + * This method runs required validators on this builder. + */ + protected runRequiredValidations(): void; +} + +/** + * A slash command attachment option. + */ +declare class SlashCommandAttachmentOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandAttachmentOption; +} + +/** + * A slash command boolean option. + */ +declare class SlashCommandBooleanOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandBooleanOption; +} + +/** + * The allowed channel types used for a channel option in a slash command builder. + * + * @privateRemarks This can't be dynamic because const enums are erased at runtime. + * @internal + */ +declare const allowedChannelTypes: readonly [ChannelType.GuildText, ChannelType.GuildVoice, ChannelType.GuildCategory, ChannelType.GuildAnnouncement, ChannelType.AnnouncementThread, ChannelType.PublicThread, ChannelType.PrivateThread, ChannelType.GuildStageVoice, ChannelType.GuildForum, ChannelType.GuildMedia]; +/** + * The type of allowed channel types used for a channel option. + */ +type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number]; +/** + * This mixin holds channel type symbols used for options. + */ +declare class ApplicationCommandOptionChannelTypesMixin { + /** + * The channel types of this option. + */ + readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[]; + /** + * Adds channel types to this option. + * + * @param channelTypes - The channel types + */ + addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]): this; +} + +/** + * A slash command channel option. + */ +declare class SlashCommandChannelOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandChannelOption; +} +interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin { +} + +/** + * This mixin holds minimum and maximum symbols used for options. + */ +declare abstract class ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The maximum value of this option. + */ + readonly max_value?: number; + /** + * The minimum value of this option. + */ + readonly min_value?: number; + /** + * Sets the maximum number value of this option. + * + * @param max - The maximum value this option can be + */ + abstract setMaxValue(max: number): this; + /** + * Sets the minimum number value of this option. + * + * @param min - The minimum value this option can be + */ + abstract setMinValue(min: number): this; +} + +/** + * This mixin holds choices and autocomplete symbols used for options. + */ +declare class ApplicationCommandOptionWithChoicesAndAutocompleteMixin { + /** + * The choices of this option. + */ + readonly choices?: APIApplicationCommandOptionChoice[]; + /** + * Whether this option utilizes autocomplete. + */ + readonly autocomplete?: boolean; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ + readonly type: ApplicationCommandOptionType; + /** + * Adds multiple choices to this option. + * + * @param choices - The choices to add + */ + addChoices(...choices: APIApplicationCommandOptionChoice[]): this; + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ + setChoices[]>(...choices: Input): this; + /** + * Whether this option uses autocomplete. + * + * @param autocomplete - Whether this option should use autocomplete + */ + setAutocomplete(autocomplete: boolean): this; +} + +/** + * A slash command integer option. + */ +declare class SlashCommandIntegerOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max: number): this; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandIntegerOption; +} +interface SlashCommandIntegerOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +/** + * A slash command mentionable option. + */ +declare class SlashCommandMentionableOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandMentionableOption; +} + +/** + * A slash command number option. + */ +declare class SlashCommandNumberOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max: number): this; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandNumberOption; +} +interface SlashCommandNumberOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +/** + * A slash command role option. + */ +declare class SlashCommandRoleOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandRoleOption; +} + +/** + * A slash command string option. + */ +declare class SlashCommandStringOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.String; + /** + * The maximum length of this option. + */ + readonly max_length?: number; + /** + * The minimum length of this option. + */ + readonly min_length?: number; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ + setMaxLength(max: number): this; + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ + setMinLength(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandStringOption; +} +interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin { +} + +/** + * A slash command user option. + */ +declare class SlashCommandUserOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + readonly type: ApplicationCommandOptionType.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON(): APIApplicationCommandUserOption; +} + +/** + * This mixin holds symbols that can be shared in slash command options. + * + * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions. + */ +declare class SharedSlashCommandOptions { + readonly options: ToAPIApplicationCommandOptions[]; + /** + * Adds a boolean option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addBooleanOption(input: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a user option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a channel option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addChannelOption(input: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a role option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds an attachment option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addAttachmentOption(input: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a mentionable option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addMentionableOption(input: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a string option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addStringOption(input: Omit | Omit | SlashCommandStringOption | ((builder: SlashCommandStringOption) => Omit | Omit | SlashCommandStringOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds an integer option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addIntegerOption(input: Omit | Omit | SlashCommandIntegerOption | ((builder: SlashCommandIntegerOption) => Omit | Omit | SlashCommandIntegerOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Adds a number option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addNumberOption(input: Omit | Omit | SlashCommandNumberOption | ((builder: SlashCommandNumberOption) => Omit | Omit | SlashCommandNumberOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ + private _sharedAddOptionMethod; +} + +/** + * Represents a folder for subcommands. + * + * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups} + */ +declare class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions { + /** + * The name of this subcommand group. + */ + readonly name: string; + /** + * The description of this subcommand group. + */ + readonly description: string; + /** + * The subcommands within this subcommand group. + */ + readonly options: SlashCommandSubcommandBuilder[]; + /** + * Adds a new subcommand to this group. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ + addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): APIApplicationCommandSubcommandGroupOption; +} +interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription { +} +/** + * A builder that creates API-compatible JSON data for slash command subcommands. + * + * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups} + */ +declare class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions { + /** + * The name of this subcommand. + */ + readonly name: string; + /** + * The description of this subcommand. + */ + readonly description: string; + /** + * The options within this subcommand. + */ + readonly options: ApplicationCommandOptionBase[]; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): APIApplicationCommandSubcommandOption; +} +interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { +} + +/** + * A builder that creates API-compatible JSON data for slash commands. + */ +declare class SlashCommandBuilder { + /** + * The name of this command. + */ + readonly name: string; + /** + * The name localizations of this command. + */ + readonly name_localizations?: LocalizationMap; + /** + * The description of this command. + */ + readonly description: string; + /** + * The description localizations of this command. + */ + readonly description_localizations?: LocalizationMap; + /** + * The options of this command. + */ + readonly options: ToAPIApplicationCommandOptions[]; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + readonly default_permission: boolean | undefined; + /** + * The set of permissions represented as a bit set for the command. + */ + readonly default_member_permissions: Permissions | null | undefined; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + readonly dm_permission: boolean | undefined; + /** + * Whether this command is NSFW. + */ + readonly nsfw: boolean | undefined; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether or not to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. + */ + setDefaultPermission(value: boolean): this; + /** + * Sets the default permissions a member should have in order to run the command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined): this; + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDMPermission(enabled: boolean | null | undefined): this; + /** + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw?: boolean): this; + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder + */ + addSubcommandGroup(input: SlashCommandSubcommandGroupBuilder | ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder)): SlashCommandSubcommandsOnlyBuilder; + /** + * Adds a new subcommand to this command. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ + addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): SlashCommandSubcommandsOnlyBuilder; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody; +} +interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { +} +/** + * An interface specifically for slash command subcommands. + */ +interface SlashCommandSubcommandsOnlyBuilder extends Omit> { +} +/** + * An interface specifically for slash command options. + */ +interface SlashCommandOptionsOnlyBuilder extends SharedNameAndDescription, SharedSlashCommandOptions, Pick { +} +/** + * An interface that ensures the `toJSON()` call will return something + * that can be serialized into API-compatible data. + */ +interface ToAPIApplicationCommandOptions { + toJSON(): APIApplicationCommandOption; +} + +declare function validateName$1(name: unknown): asserts name is string; +declare function validateDescription(description: unknown): asserts description is string; +declare function validateLocale(locale: unknown): Locale; +declare function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[]; +declare function validateRequiredParameters$1(name: string, description: string, options: ToAPIApplicationCommandOptions[]): void; +declare function validateDefaultPermission$1(value: unknown): asserts value is boolean; +declare function validateRequired(required: unknown): asserts required is boolean; +declare function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void; +declare function assertReturnOfBuilder(input: unknown, ExpectedInstanceOf: new () => ReturnType): asserts input is ReturnType; +declare const localizationMapPredicate: _sapphire_shapeshift.UnionValidator<_sapphire_shapeshift.UndefinedToOptional>> | null | undefined>; +declare function validateLocalizationMap(value: unknown): asserts value is LocalizationMap; +declare function validateDMPermission$1(value: unknown): asserts value is boolean | null | undefined; +declare function validateDefaultMemberPermissions$1(permissions: unknown): string | null | undefined; +declare function validateNSFW(value: unknown): asserts value is boolean; + +declare const Assertions$1_assertReturnOfBuilder: typeof assertReturnOfBuilder; +declare const Assertions$1_localizationMapPredicate: typeof localizationMapPredicate; +declare const Assertions$1_validateChoicesLength: typeof validateChoicesLength; +declare const Assertions$1_validateDescription: typeof validateDescription; +declare const Assertions$1_validateLocale: typeof validateLocale; +declare const Assertions$1_validateLocalizationMap: typeof validateLocalizationMap; +declare const Assertions$1_validateMaxOptionsLength: typeof validateMaxOptionsLength; +declare const Assertions$1_validateNSFW: typeof validateNSFW; +declare const Assertions$1_validateRequired: typeof validateRequired; +declare namespace Assertions$1 { + export { + Assertions$1_assertReturnOfBuilder as assertReturnOfBuilder, + Assertions$1_localizationMapPredicate as localizationMapPredicate, + Assertions$1_validateChoicesLength as validateChoicesLength, + validateDMPermission$1 as validateDMPermission, + validateDefaultMemberPermissions$1 as validateDefaultMemberPermissions, + validateDefaultPermission$1 as validateDefaultPermission, + Assertions$1_validateDescription as validateDescription, + Assertions$1_validateLocale as validateLocale, + Assertions$1_validateLocalizationMap as validateLocalizationMap, + Assertions$1_validateMaxOptionsLength as validateMaxOptionsLength, + Assertions$1_validateNSFW as validateNSFW, + validateName$1 as validateName, + Assertions$1_validateRequired as validateRequired, + validateRequiredParameters$1 as validateRequiredParameters, + }; +} + +/** + * The type a context menu command can be. + */ +type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User; +/** + * A builder that creates API-compatible JSON data for context menu commands. + */ +declare class ContextMenuCommandBuilder { + /** + * The name of this command. + */ + readonly name: string; + /** + * The name localizations of this command. + */ + readonly name_localizations?: LocalizationMap; + /** + * The type of this command. + */ + readonly type: ContextMenuCommandType; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + readonly default_permission: boolean | undefined; + /** + * The set of permissions represented as a bit set for the command. + */ + readonly default_member_permissions: Permissions | null | undefined; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + readonly dm_permission: boolean | undefined; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ + setName(name: string): this; + /** + * Sets the type of this command. + * + * @param type - The type to use + */ + setType(type: ContextMenuCommandType): this; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + setDefaultPermission(value: boolean): this; + /** + * Sets the default permissions a member should have in order to run this command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined): this; + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDMPermission(enabled: boolean | null | undefined): this; + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ + setNameLocalization(locale: LocaleString, localizedName: string | null): this; + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ + setNameLocalizations(localizedNames: LocalizationMap | null): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody; +} + +declare function validateDefaultPermission(value: unknown): asserts value is boolean; +declare function validateName(name: unknown): asserts name is string; +declare function validateType(type: unknown): asserts type is ContextMenuCommandType; +declare function validateRequiredParameters(name: string, type: number): void; +declare function validateDMPermission(value: unknown): asserts value is boolean | null | undefined; +declare function validateDefaultMemberPermissions(permissions: unknown): string | null | undefined; + +declare const Assertions_validateDMPermission: typeof validateDMPermission; +declare const Assertions_validateDefaultMemberPermissions: typeof validateDefaultMemberPermissions; +declare const Assertions_validateDefaultPermission: typeof validateDefaultPermission; +declare const Assertions_validateName: typeof validateName; +declare const Assertions_validateRequiredParameters: typeof validateRequiredParameters; +declare const Assertions_validateType: typeof validateType; +declare namespace Assertions { + export { + Assertions_validateDMPermission as validateDMPermission, + Assertions_validateDefaultMemberPermissions as validateDefaultMemberPermissions, + Assertions_validateDefaultPermission as validateDefaultPermission, + Assertions_validateName as validateName, + Assertions_validateRequiredParameters as validateRequiredParameters, + Assertions_validateType as validateType, + }; +} + +/** + * Calculates the length of the embed. + * + * @param data - The embed data to check + */ +declare function embedLength(data: APIEmbed): number; + +/** + * Enables validators. + * + * @returns Whether validation is occurring. + */ +declare function enableValidators(): boolean; +/** + * Disables validators. + * + * @returns Whether validation is occurring. + */ +declare function disableValidators(): boolean; +/** + * Checks whether validation is occurring. + */ +declare function isValidationEnabled(): boolean; + +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version + * that you are currently using. + * + * @privateRemarks This needs to explicitly be `string` so it is not typed as a "const string" that gets injected by esbuild. + */ +declare const version: string; + +export { ActionRowBuilder, AnyAPIActionRowComponent, AnyComponentBuilder, ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionAllowedChannelTypes, ApplicationCommandOptionBase, ApplicationCommandOptionChannelTypesMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin, BaseSelectMenuBuilder, ButtonBuilder, ChannelSelectMenuBuilder, Assertions$4 as ComponentAssertions, ComponentBuilder, Assertions as ContextMenuCommandAssertions, ContextMenuCommandBuilder, ContextMenuCommandType, Assertions$5 as EmbedAssertions, EmbedAuthorData, EmbedAuthorOptions, EmbedBuilder, EmbedFooterData, EmbedFooterOptions, EmbedImageData, IconData, MappedComponentTypes, MentionableSelectMenuBuilder, MessageActionRowComponentBuilder, MessageComponentBuilder, ModalActionRowComponentBuilder, Assertions$2 as ModalAssertions, ModalBuilder, ModalComponentBuilder, RGBTuple, RestOrArray, RoleSelectMenuBuilder, StringSelectMenuBuilder as SelectMenuBuilder, StringSelectMenuOptionBuilder as SelectMenuOptionBuilder, SharedNameAndDescription, SharedSlashCommandOptions, Assertions$1 as SlashCommandAssertions, SlashCommandAttachmentOption, SlashCommandBooleanOption, SlashCommandBuilder, SlashCommandChannelOption, SlashCommandIntegerOption, SlashCommandMentionableOption, SlashCommandNumberOption, SlashCommandOptionsOnlyBuilder, SlashCommandRoleOption, SlashCommandStringOption, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder, SlashCommandSubcommandsOnlyBuilder, SlashCommandUserOption, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, Assertions$3 as TextInputAssertions, TextInputBuilder, ToAPIApplicationCommandOptions, UserSelectMenuBuilder, createComponentBuilder, disableValidators, embedLength, enableValidators, isValidationEnabled, normalizeArray, version }; diff --git a/node_modules/@discordjs/builders/dist/index.js b/node_modules/@discordjs/builders/dist/index.js new file mode 100644 index 0000000..5bd7a7b --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.js @@ -0,0 +1,2763 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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 __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __decorateClass = (decorators, target, key, kind) => { + var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; + for (var i = decorators.length - 1, decorator; i >= 0; i--) + if (decorator = decorators[i]) + result = (kind ? decorator(target, key, result) : decorator(result)) || result; + if (kind && result) + __defProp(target, key, result); + return result; +}; + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + ActionRowBuilder: () => ActionRowBuilder, + ApplicationCommandNumericOptionMinMaxValueMixin: () => ApplicationCommandNumericOptionMinMaxValueMixin, + ApplicationCommandOptionBase: () => ApplicationCommandOptionBase, + ApplicationCommandOptionChannelTypesMixin: () => ApplicationCommandOptionChannelTypesMixin, + ApplicationCommandOptionWithChoicesAndAutocompleteMixin: () => ApplicationCommandOptionWithChoicesAndAutocompleteMixin, + BaseSelectMenuBuilder: () => BaseSelectMenuBuilder, + ButtonBuilder: () => ButtonBuilder, + ChannelSelectMenuBuilder: () => ChannelSelectMenuBuilder, + ComponentAssertions: () => Assertions_exports2, + ComponentBuilder: () => ComponentBuilder, + ContextMenuCommandAssertions: () => Assertions_exports6, + ContextMenuCommandBuilder: () => ContextMenuCommandBuilder, + EmbedAssertions: () => Assertions_exports, + EmbedBuilder: () => EmbedBuilder, + MentionableSelectMenuBuilder: () => MentionableSelectMenuBuilder, + ModalAssertions: () => Assertions_exports4, + ModalBuilder: () => ModalBuilder, + RoleSelectMenuBuilder: () => RoleSelectMenuBuilder, + SelectMenuBuilder: () => StringSelectMenuBuilder, + SelectMenuOptionBuilder: () => StringSelectMenuOptionBuilder, + SharedNameAndDescription: () => SharedNameAndDescription, + SharedSlashCommandOptions: () => SharedSlashCommandOptions, + SlashCommandAssertions: () => Assertions_exports5, + SlashCommandAttachmentOption: () => SlashCommandAttachmentOption, + SlashCommandBooleanOption: () => SlashCommandBooleanOption, + SlashCommandBuilder: () => SlashCommandBuilder, + SlashCommandChannelOption: () => SlashCommandChannelOption, + SlashCommandIntegerOption: () => SlashCommandIntegerOption, + SlashCommandMentionableOption: () => SlashCommandMentionableOption, + SlashCommandNumberOption: () => SlashCommandNumberOption, + SlashCommandRoleOption: () => SlashCommandRoleOption, + SlashCommandStringOption: () => SlashCommandStringOption, + SlashCommandSubcommandBuilder: () => SlashCommandSubcommandBuilder, + SlashCommandSubcommandGroupBuilder: () => SlashCommandSubcommandGroupBuilder, + SlashCommandUserOption: () => SlashCommandUserOption, + StringSelectMenuBuilder: () => StringSelectMenuBuilder, + StringSelectMenuOptionBuilder: () => StringSelectMenuOptionBuilder, + TextInputAssertions: () => Assertions_exports3, + TextInputBuilder: () => TextInputBuilder, + UserSelectMenuBuilder: () => UserSelectMenuBuilder, + createComponentBuilder: () => createComponentBuilder, + disableValidators: () => disableValidators, + embedLength: () => embedLength, + enableValidators: () => enableValidators, + isValidationEnabled: () => isValidationEnabled, + normalizeArray: () => normalizeArray, + version: () => version +}); +module.exports = __toCommonJS(src_exports); + +// src/messages/embed/Assertions.ts +var Assertions_exports = {}; +__export(Assertions_exports, { + RGBPredicate: () => RGBPredicate, + authorNamePredicate: () => authorNamePredicate, + colorPredicate: () => colorPredicate, + descriptionPredicate: () => descriptionPredicate, + embedAuthorPredicate: () => embedAuthorPredicate, + embedFieldPredicate: () => embedFieldPredicate, + embedFieldsArrayPredicate: () => embedFieldsArrayPredicate, + embedFooterPredicate: () => embedFooterPredicate, + fieldInlinePredicate: () => fieldInlinePredicate, + fieldLengthPredicate: () => fieldLengthPredicate, + fieldNamePredicate: () => fieldNamePredicate, + fieldValuePredicate: () => fieldValuePredicate, + footerTextPredicate: () => footerTextPredicate, + imageURLPredicate: () => imageURLPredicate, + timestampPredicate: () => timestampPredicate, + titlePredicate: () => titlePredicate, + urlPredicate: () => urlPredicate, + validateFieldLength: () => validateFieldLength +}); +var import_shapeshift = require("@sapphire/shapeshift"); + +// src/util/validation.ts +var validate = true; +function enableValidators() { + return validate = true; +} +__name(enableValidators, "enableValidators"); +function disableValidators() { + return validate = false; +} +__name(disableValidators, "disableValidators"); +function isValidationEnabled() { + return validate; +} +__name(isValidationEnabled, "isValidationEnabled"); + +// src/messages/embed/Assertions.ts +var fieldNamePredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(256).setValidationEnabled(isValidationEnabled); +var fieldValuePredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(1024).setValidationEnabled(isValidationEnabled); +var fieldInlinePredicate = import_shapeshift.s.boolean.optional; +var embedFieldPredicate = import_shapeshift.s.object({ + name: fieldNamePredicate, + value: fieldValuePredicate, + inline: fieldInlinePredicate +}).setValidationEnabled(isValidationEnabled); +var embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled); +var fieldLengthPredicate = import_shapeshift.s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateFieldLength(amountAdding, fields) { + fieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding); +} +__name(validateFieldLength, "validateFieldLength"); +var authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled); +var imageURLPredicate = import_shapeshift.s.string.url({ + allowedProtocols: ["http:", "https:", "attachment:"] +}).nullish.setValidationEnabled(isValidationEnabled); +var urlPredicate = import_shapeshift.s.string.url({ + allowedProtocols: ["http:", "https:"] +}).nullish.setValidationEnabled(isValidationEnabled); +var embedAuthorPredicate = import_shapeshift.s.object({ + name: authorNamePredicate, + iconURL: imageURLPredicate, + url: urlPredicate +}).setValidationEnabled(isValidationEnabled); +var RGBPredicate = import_shapeshift.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(255).setValidationEnabled(isValidationEnabled); +var colorPredicate = import_shapeshift.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(16777215).or(import_shapeshift.s.tuple([RGBPredicate, RGBPredicate, RGBPredicate])).nullable.setValidationEnabled(isValidationEnabled); +var descriptionPredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(4096).nullable.setValidationEnabled(isValidationEnabled); +var footerTextPredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(2048).nullable.setValidationEnabled(isValidationEnabled); +var embedFooterPredicate = import_shapeshift.s.object({ + text: footerTextPredicate, + iconURL: imageURLPredicate +}).setValidationEnabled(isValidationEnabled); +var timestampPredicate = import_shapeshift.s.union(import_shapeshift.s.number, import_shapeshift.s.date).nullable.setValidationEnabled(isValidationEnabled); +var titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled); + +// src/util/normalizeArray.ts +function normalizeArray(arr) { + if (Array.isArray(arr[0])) + return arr[0]; + return arr; +} +__name(normalizeArray, "normalizeArray"); + +// src/messages/embed/Embed.ts +var EmbedBuilder = class { + static { + __name(this, "EmbedBuilder"); + } + /** + * The API data associated with this embed. + */ + data; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ + constructor(data = {}) { + this.data = { ...data }; + if (data.timestamp) + this.data.timestamp = new Date(data.timestamp).toISOString(); + } + /** + * Appends fields to the embed. + * + * @remarks + * This method accepts either an array of fields or a variable number of field parameters. + * The maximum amount of fields that can be added is 25. + * @example + * Using an array: + * ```ts + * const fields: APIEmbedField[] = ...; + * const embed = new EmbedBuilder() + * .addFields(fields); + * ``` + * @example + * Using rest parameters (variadic): + * ```ts + * const embed = new EmbedBuilder() + * .addFields( + * { name: 'Field 1', value: 'Value 1' }, + * { name: 'Field 2', value: 'Value 2' }, + * ); + * ``` + * @param fields - The fields to add + */ + addFields(...fields) { + const normalizedFields = normalizeArray(fields); + validateFieldLength(normalizedFields.length, this.data.fields); + embedFieldsArrayPredicate.parse(normalizedFields); + if (this.data.fields) + this.data.fields.push(...normalizedFields); + else + this.data.fields = normalizedFields; + return this; + } + /** + * Removes, replaces, or inserts fields for this embed. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. + * The maximum amount of fields that can be added is 25. + * + * It's useful for modifying and adjusting order of the already-existing fields of an embed. + * @example + * Remove the first field: + * ```ts + * embed.spliceFields(0, 1); + * ``` + * @example + * Remove the first n fields: + * ```ts + * const n = 4; + * embed.spliceFields(0, n); + * ``` + * @example + * Remove the last field: + * ```ts + * embed.spliceFields(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of fields to remove + * @param fields - The replacing field objects + */ + spliceFields(index, deleteCount, ...fields) { + validateFieldLength(fields.length - deleteCount, this.data.fields); + embedFieldsArrayPredicate.parse(fields); + if (this.data.fields) + this.data.fields.splice(index, deleteCount, ...fields); + else + this.data.fields = fields; + return this; + } + /** + * Sets the fields for this embed. + * + * @remarks + * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, + * it splices the entire array of fields, replacing them with the provided fields. + * + * You can set a maximum of 25 fields. + * @param fields - The fields to set + */ + setFields(...fields) { + this.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields)); + return this; + } + /** + * Sets the author of this embed. + * + * @param options - The options to use + */ + setAuthor(options) { + if (options === null) { + this.data.author = void 0; + return this; + } + embedAuthorPredicate.parse(options); + this.data.author = { name: options.name, url: options.url, icon_url: options.iconURL }; + return this; + } + /** + * Sets the color of this embed. + * + * @param color - The color to use + */ + setColor(color) { + colorPredicate.parse(color); + if (Array.isArray(color)) { + const [red, green, blue] = color; + this.data.color = (red << 16) + (green << 8) + blue; + return this; + } + this.data.color = color ?? void 0; + return this; + } + /** + * Sets the description of this embed. + * + * @param description - The description to use + */ + setDescription(description) { + descriptionPredicate.parse(description); + this.data.description = description ?? void 0; + return this; + } + /** + * Sets the footer of this embed. + * + * @param options - The footer to use + */ + setFooter(options) { + if (options === null) { + this.data.footer = void 0; + return this; + } + embedFooterPredicate.parse(options); + this.data.footer = { text: options.text, icon_url: options.iconURL }; + return this; + } + /** + * Sets the image of this embed. + * + * @param url - The image URL to use + */ + setImage(url) { + imageURLPredicate.parse(url); + this.data.image = url ? { url } : void 0; + return this; + } + /** + * Sets the thumbnail of this embed. + * + * @param url - The thumbnail URL to use + */ + setThumbnail(url) { + imageURLPredicate.parse(url); + this.data.thumbnail = url ? { url } : void 0; + return this; + } + /** + * Sets the timestamp of this embed. + * + * @param timestamp - The timestamp or date to use + */ + setTimestamp(timestamp = Date.now()) { + timestampPredicate.parse(timestamp); + this.data.timestamp = timestamp ? new Date(timestamp).toISOString() : void 0; + return this; + } + /** + * Sets the title for this embed. + * + * @param title - The title to use + */ + setTitle(title) { + titlePredicate.parse(title); + this.data.title = title ?? void 0; + return this; + } + /** + * Sets the URL of this embed. + * + * @param url - The URL to use + */ + setURL(url) { + urlPredicate.parse(url); + this.data.url = url ?? void 0; + return this; + } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + return { ...this.data }; + } +}; + +// src/index.ts +__reExport(src_exports, require("@discordjs/formatters"), module.exports); + +// src/components/Assertions.ts +var Assertions_exports2 = {}; +__export(Assertions_exports2, { + buttonLabelValidator: () => buttonLabelValidator, + buttonStyleValidator: () => buttonStyleValidator, + channelTypesValidator: () => channelTypesValidator, + customIdValidator: () => customIdValidator, + defaultValidator: () => defaultValidator, + disabledValidator: () => disabledValidator, + emojiValidator: () => emojiValidator, + jsonOptionValidator: () => jsonOptionValidator, + labelValueDescriptionValidator: () => labelValueDescriptionValidator, + minMaxValidator: () => minMaxValidator, + optionValidator: () => optionValidator, + optionsLengthValidator: () => optionsLengthValidator, + optionsValidator: () => optionsValidator, + placeholderValidator: () => placeholderValidator, + urlValidator: () => urlValidator, + validateRequiredButtonParameters: () => validateRequiredButtonParameters, + validateRequiredSelectMenuOptionParameters: () => validateRequiredSelectMenuOptionParameters, + validateRequiredSelectMenuParameters: () => validateRequiredSelectMenuParameters +}); +var import_shapeshift2 = require("@sapphire/shapeshift"); +var import_v10 = require("discord-api-types/v10"); + +// src/components/selectMenu/StringSelectMenuOption.ts +var StringSelectMenuOptionBuilder = class { + /** + * Creates a new string select menu option from API data. + * + * @param data - The API data to create this string select menu option with + * @example + * Creating a string select menu option from an API data object: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * label: 'catchy label', + * value: '1', + * }); + * ``` + * @example + * Creating a string select menu option using setters and API data: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * default: true, + * value: '1', + * }) + * .setLabel('woah'); + * ``` + */ + constructor(data = {}) { + this.data = data; + } + static { + __name(this, "StringSelectMenuOptionBuilder"); + } + /** + * Sets the label for this option. + * + * @param label - The label to use + */ + setLabel(label) { + this.data.label = labelValueDescriptionValidator.parse(label); + return this; + } + /** + * Sets the value for this option. + * + * @param value - The value to use + */ + setValue(value) { + this.data.value = labelValueDescriptionValidator.parse(value); + return this; + } + /** + * Sets the description for this option. + * + * @param description - The description to use + */ + setDescription(description) { + this.data.description = labelValueDescriptionValidator.parse(description); + return this; + } + /** + * Sets whether this option is selected by default. + * + * @param isDefault - Whether this option is selected by default + */ + setDefault(isDefault = true) { + this.data.default = defaultValidator.parse(isDefault); + return this; + } + /** + * Sets the emoji to display for this option. + * + * @param emoji - The emoji to use + */ + setEmoji(emoji) { + this.data.emoji = emojiValidator.parse(emoji); + return this; + } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON() { + validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); + return { + ...this.data + }; + } +}; + +// src/components/Assertions.ts +var customIdValidator = import_shapeshift2.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var emojiValidator = import_shapeshift2.s.object({ + id: import_shapeshift2.s.string, + name: import_shapeshift2.s.string, + animated: import_shapeshift2.s.boolean +}).partial.strict.setValidationEnabled(isValidationEnabled); +var disabledValidator = import_shapeshift2.s.boolean; +var buttonLabelValidator = import_shapeshift2.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(80).setValidationEnabled(isValidationEnabled); +var buttonStyleValidator = import_shapeshift2.s.nativeEnum(import_v10.ButtonStyle); +var placeholderValidator = import_shapeshift2.s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled); +var minMaxValidator = import_shapeshift2.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +var labelValueDescriptionValidator = import_shapeshift2.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var jsonOptionValidator = import_shapeshift2.s.object({ + label: labelValueDescriptionValidator, + value: labelValueDescriptionValidator, + description: labelValueDescriptionValidator.optional, + emoji: emojiValidator.optional, + default: import_shapeshift2.s.boolean.optional +}).setValidationEnabled(isValidationEnabled); +var optionValidator = import_shapeshift2.s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled); +var optionsValidator = optionValidator.array.lengthGreaterThanOrEqual(0).setValidationEnabled(isValidationEnabled); +var optionsLengthValidator = import_shapeshift2.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateRequiredSelectMenuParameters(options, customId) { + customIdValidator.parse(customId); + optionsValidator.parse(options); +} +__name(validateRequiredSelectMenuParameters, "validateRequiredSelectMenuParameters"); +var defaultValidator = import_shapeshift2.s.boolean; +function validateRequiredSelectMenuOptionParameters(label, value) { + labelValueDescriptionValidator.parse(label); + labelValueDescriptionValidator.parse(value); +} +__name(validateRequiredSelectMenuOptionParameters, "validateRequiredSelectMenuOptionParameters"); +var channelTypesValidator = import_shapeshift2.s.nativeEnum(import_v10.ChannelType).array.setValidationEnabled(isValidationEnabled); +var urlValidator = import_shapeshift2.s.string.url({ + allowedProtocols: ["http:", "https:", "discord:"] +}).setValidationEnabled(isValidationEnabled); +function validateRequiredButtonParameters(style, label, emoji, customId, url) { + if (url && customId) { + throw new RangeError("URL and custom id are mutually exclusive"); + } + if (!label && !emoji) { + throw new RangeError("Buttons must have a label and/or an emoji"); + } + if (style === import_v10.ButtonStyle.Link) { + if (!url) { + throw new RangeError("Link buttons must have a url"); + } + } else if (url) { + throw new RangeError("Non-link buttons cannot have a url"); + } +} +__name(validateRequiredButtonParameters, "validateRequiredButtonParameters"); + +// src/components/ActionRow.ts +var import_v1011 = require("discord-api-types/v10"); + +// src/components/Component.ts +var ComponentBuilder = class { + static { + __name(this, "ComponentBuilder"); + } + /** + * The API data associated with this component. + */ + data; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ + constructor(data) { + this.data = data; + } +}; + +// src/components/Components.ts +var import_v1010 = require("discord-api-types/v10"); + +// src/components/button/Button.ts +var import_v102 = require("discord-api-types/v10"); +var ButtonBuilder = class extends ComponentBuilder { + static { + __name(this, "ButtonBuilder"); + } + /** + * Creates a new button from API data. + * + * @param data - The API data to create this button with + * @example + * Creating a button from an API data object: + * ```ts + * const button = new ButtonBuilder({ + * custom_id: 'a cool button', + * style: ButtonStyle.Primary, + * label: 'Click Me', + * emoji: { + * name: 'smile', + * id: '123456789012345678', + * }, + * }); + * ``` + * @example + * Creating a button using setters and API data: + * ```ts + * const button = new ButtonBuilder({ + * style: ButtonStyle.Secondary, + * label: 'Click Me', + * }) + * .setEmoji({ name: '🙂' }) + * .setCustomId('another cool button'); + * ``` + */ + constructor(data) { + super({ type: import_v102.ComponentType.Button, ...data }); + } + /** + * Sets the style of this button. + * + * @param style - The style to use + */ + setStyle(style) { + this.data.style = buttonStyleValidator.parse(style); + return this; + } + /** + * Sets the URL for this button. + * + * @remarks + * This method is only available to buttons using the `Link` button style. + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use + */ + setURL(url) { + this.data.url = urlValidator.parse(url); + return this; + } + /** + * Sets the custom id for this button. + * + * @remarks + * This method is only applicable to buttons that are not using the `Link` button style. + * @param customId - The custom id to use + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets the emoji to display on this button. + * + * @param emoji - The emoji to use + */ + setEmoji(emoji) { + this.data.emoji = emojiValidator.parse(emoji); + return this; + } + /** + * Sets whether this button is disabled. + * + * @param disabled - Whether to disable this button + */ + setDisabled(disabled = true) { + this.data.disabled = disabledValidator.parse(disabled); + return this; + } + /** + * Sets the label for this button. + * + * @param label - The label to use + */ + setLabel(label) { + this.data.label = buttonLabelValidator.parse(label); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredButtonParameters( + this.data.style, + this.data.label, + this.data.emoji, + this.data.custom_id, + this.data.url + ); + return { + ...this.data + }; + } +}; + +// src/components/selectMenu/ChannelSelectMenu.ts +var import_v103 = require("discord-api-types/v10"); + +// src/components/selectMenu/BaseSelectMenu.ts +var BaseSelectMenuBuilder = class extends ComponentBuilder { + static { + __name(this, "BaseSelectMenuBuilder"); + } + /** + * Sets the placeholder for this select menu. + * + * @param placeholder - The placeholder to use + */ + setPlaceholder(placeholder) { + this.data.placeholder = placeholderValidator.parse(placeholder); + return this; + } + /** + * Sets the minimum values that must be selected in the select menu. + * + * @param minValues - The minimum values that must be selected + */ + setMinValues(minValues) { + this.data.min_values = minMaxValidator.parse(minValues); + return this; + } + /** + * Sets the maximum values that must be selected in the select menu. + * + * @param maxValues - The maximum values that must be selected + */ + setMaxValues(maxValues) { + this.data.max_values = minMaxValidator.parse(maxValues); + return this; + } + /** + * Sets the custom id for this select menu. + * + * @param customId - The custom id to use + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets whether this select menu is disabled. + * + * @param disabled - Whether this select menu is disabled + */ + setDisabled(disabled = true) { + this.data.disabled = disabledValidator.parse(disabled); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + customIdValidator.parse(this.data.custom_id); + return { + ...this.data + }; + } +}; + +// src/components/selectMenu/ChannelSelectMenu.ts +var ChannelSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "ChannelSelectMenuBuilder"); + } + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) + * .setMinValues(2); + * ``` + */ + constructor(data) { + super({ ...data, type: import_v103.ComponentType.ChannelSelect }); + } + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ + addChannelTypes(...types) { + const normalizedTypes = normalizeArray(types); + this.data.channel_types ??= []; + this.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes)); + return this; + } + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ + setChannelTypes(...types) { + const normalizedTypes = normalizeArray(types); + this.data.channel_types ??= []; + this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes)); + return this; + } + /** + * Adds default channels to this auto populated select menu. + * + * @param channels - The channels to add + */ + addDefaultChannels(...channels) { + const normalizedValues = normalizeArray(channels); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: import_v103.SelectMenuDefaultValueType.Channel + })) + ); + return this; + } + /** + * Sets default channels to this auto populated select menu. + * + * @param channels - The channels to set + */ + setDefaultChannels(...channels) { + const normalizedValues = normalizeArray(channels); + optionsLengthValidator.parse(normalizedValues.length); + this.data.default_values = normalizedValues.map((id) => ({ + id, + type: import_v103.SelectMenuDefaultValueType.Channel + })); + return this; + } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON() { + customIdValidator.parse(this.data.custom_id); + return { + ...this.data + }; + } +}; + +// src/components/selectMenu/MentionableSelectMenu.ts +var import_v104 = require("discord-api-types/v10"); +var MentionableSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "MentionableSelectMenuBuilder"); + } + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data) { + super({ ...data, type: import_v104.ComponentType.MentionableSelect }); + } + /** + * Adds default roles to this auto populated select menu. + * + * @param roles - The roles to add + */ + addDefaultRoles(...roles) { + const normalizedValues = normalizeArray(roles); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: import_v104.SelectMenuDefaultValueType.Role + })) + ); + return this; + } + /** + * Adds default users to this auto populated select menu. + * + * @param users - The users to add + */ + addDefaultUsers(...users) { + const normalizedValues = normalizeArray(users); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: import_v104.SelectMenuDefaultValueType.User + })) + ); + return this; + } + /** + * Adds default values to this auto populated select menu. + * + * @param values - The values to add + */ + addDefaultValues(...values) { + const normalizedValues = normalizeArray(values); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push(...normalizedValues); + return this; + } + /** + * Sets default values to this auto populated select menu. + * + * @param values - The values to set + */ + setDefaultValues(...values) { + const normalizedValues = normalizeArray(values); + optionsLengthValidator.parse(normalizedValues.length); + this.data.default_values = normalizedValues.slice(); + return this; + } +}; + +// src/components/selectMenu/RoleSelectMenu.ts +var import_v105 = require("discord-api-types/v10"); +var RoleSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "RoleSelectMenuBuilder"); + } + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data) { + super({ ...data, type: import_v105.ComponentType.RoleSelect }); + } + /** + * Adds default roles to this auto populated select menu. + * + * @param roles - The roles to add + */ + addDefaultRoles(...roles) { + const normalizedValues = normalizeArray(roles); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: import_v105.SelectMenuDefaultValueType.Role + })) + ); + return this; + } + /** + * Sets default roles to this auto populated select menu. + * + * @param roles - The roles to set + */ + setDefaultRoles(...roles) { + const normalizedValues = normalizeArray(roles); + optionsLengthValidator.parse(normalizedValues.length); + this.data.default_values = normalizedValues.map((id) => ({ + id, + type: import_v105.SelectMenuDefaultValueType.Role + })); + return this; + } +}; + +// src/components/selectMenu/StringSelectMenu.ts +var import_v106 = require("discord-api-types/v10"); +var StringSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "StringSelectMenuBuilder"); + } + /** + * The options within this select menu. + */ + options; + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * options: [ + * { label: 'option 1', value: '1' }, + * { label: 'option 2', value: '2' }, + * { label: 'option 3', value: '3' }, + * ], + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1) + * .addOptions({ + * label: 'Catchy', + * value: 'catch', + * }); + * ``` + */ + constructor(data) { + const { options, ...initData } = data ?? {}; + super({ ...initData, type: import_v106.ComponentType.StringSelect }); + this.options = options?.map((option) => new StringSelectMenuOptionBuilder(option)) ?? []; + } + /** + * Adds options to this select menu. + * + * @param options - The options to add + */ + addOptions(...options) { + const normalizedOptions = normalizeArray(options); + optionsLengthValidator.parse(this.options.length + normalizedOptions.length); + this.options.push( + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) + ) + ); + return this; + } + /** + * Sets the options for this select menu. + * + * @param options - The options to set + */ + setOptions(...options) { + return this.spliceOptions(0, this.options.length, ...options); + } + /** + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index, deleteCount, ...options) { + const normalizedOptions = normalizeArray(options); + const clone = [...this.options]; + clone.splice( + index, + deleteCount, + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) + ) + ); + optionsLengthValidator.parse(clone.length); + this.options.splice(0, this.options.length, ...clone); + return this; + } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON() { + validateRequiredSelectMenuParameters(this.options, this.data.custom_id); + return { + ...this.data, + options: this.options.map((option) => option.toJSON()) + }; + } +}; + +// src/components/selectMenu/UserSelectMenu.ts +var import_v107 = require("discord-api-types/v10"); +var UserSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "UserSelectMenuBuilder"); + } + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data) { + super({ ...data, type: import_v107.ComponentType.UserSelect }); + } + /** + * Adds default users to this auto populated select menu. + * + * @param users - The users to add + */ + addDefaultUsers(...users) { + const normalizedValues = normalizeArray(users); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: import_v107.SelectMenuDefaultValueType.User + })) + ); + return this; + } + /** + * Sets default users to this auto populated select menu. + * + * @param users - The users to set + */ + setDefaultUsers(...users) { + const normalizedValues = normalizeArray(users); + optionsLengthValidator.parse(normalizedValues.length); + this.data.default_values = normalizedValues.map((id) => ({ + id, + type: import_v107.SelectMenuDefaultValueType.User + })); + return this; + } +}; + +// src/components/textInput/TextInput.ts +var import_util = require("@discordjs/util"); +var import_v109 = require("discord-api-types/v10"); +var import_fast_deep_equal = __toESM(require("fast-deep-equal")); + +// src/components/textInput/Assertions.ts +var Assertions_exports3 = {}; +__export(Assertions_exports3, { + labelValidator: () => labelValidator, + maxLengthValidator: () => maxLengthValidator, + minLengthValidator: () => minLengthValidator, + placeholderValidator: () => placeholderValidator2, + requiredValidator: () => requiredValidator, + textInputStyleValidator: () => textInputStyleValidator, + validateRequiredParameters: () => validateRequiredParameters, + valueValidator: () => valueValidator +}); +var import_shapeshift3 = require("@sapphire/shapeshift"); +var import_v108 = require("discord-api-types/v10"); +var textInputStyleValidator = import_shapeshift3.s.nativeEnum(import_v108.TextInputStyle); +var minLengthValidator = import_shapeshift3.s.number.int.greaterThanOrEqual(0).lessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var maxLengthValidator = import_shapeshift3.s.number.int.greaterThanOrEqual(1).lessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var requiredValidator = import_shapeshift3.s.boolean; +var valueValidator = import_shapeshift3.s.string.lengthLessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var placeholderValidator2 = import_shapeshift3.s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var labelValidator = import_shapeshift3.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(45).setValidationEnabled(isValidationEnabled); +function validateRequiredParameters(customId, style, label) { + customIdValidator.parse(customId); + textInputStyleValidator.parse(style); + labelValidator.parse(label); +} +__name(validateRequiredParameters, "validateRequiredParameters"); + +// src/components/textInput/TextInput.ts +var TextInputBuilder = class extends ComponentBuilder { + static { + __name(this, "TextInputBuilder"); + } + /** + * Creates a new text input from API data. + * + * @param data - The API data to create this text input with + * @example + * Creating a select menu option from an API data object: + * ```ts + * const textInput = new TextInputBuilder({ + * custom_id: 'a cool select menu', + * label: 'Type something', + * style: TextInputStyle.Short, + * }); + * ``` + * @example + * Creating a select menu option using setters and API data: + * ```ts + * const textInput = new TextInputBuilder({ + * label: 'Type something else', + * }) + * .setCustomId('woah') + * .setStyle(TextInputStyle.Paragraph); + * ``` + */ + constructor(data) { + super({ type: import_v109.ComponentType.TextInput, ...data }); + } + /** + * Sets the custom id for this text input. + * + * @param customId - The custom id to use + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets the label for this text input. + * + * @param label - The label to use + */ + setLabel(label) { + this.data.label = labelValidator.parse(label); + return this; + } + /** + * Sets the style for this text input. + * + * @param style - The style to use + */ + setStyle(style) { + this.data.style = textInputStyleValidator.parse(style); + return this; + } + /** + * Sets the minimum length of text for this text input. + * + * @param minLength - The minimum length of text for this text input + */ + setMinLength(minLength) { + this.data.min_length = minLengthValidator.parse(minLength); + return this; + } + /** + * Sets the maximum length of text for this text input. + * + * @param maxLength - The maximum length of text for this text input + */ + setMaxLength(maxLength) { + this.data.max_length = maxLengthValidator.parse(maxLength); + return this; + } + /** + * Sets the placeholder for this text input. + * + * @param placeholder - The placeholder to use + */ + setPlaceholder(placeholder) { + this.data.placeholder = placeholderValidator2.parse(placeholder); + return this; + } + /** + * Sets the value for this text input. + * + * @param value - The value to use + */ + setValue(value) { + this.data.value = valueValidator.parse(value); + return this; + } + /** + * Sets whether this text input is required. + * + * @param required - Whether this text input is required + */ + setRequired(required = true) { + this.data.required = requiredValidator.parse(required); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label); + return { + ...this.data + }; + } + /** + * {@inheritDoc Equatable.equals} + */ + equals(other) { + if ((0, import_util.isJSONEncodable)(other)) { + return (0, import_fast_deep_equal.default)(other.toJSON(), this.data); + } + return (0, import_fast_deep_equal.default)(other, this.data); + } +}; + +// src/components/Components.ts +function createComponentBuilder(data) { + if (data instanceof ComponentBuilder) { + return data; + } + switch (data.type) { + case import_v1010.ComponentType.ActionRow: + return new ActionRowBuilder(data); + case import_v1010.ComponentType.Button: + return new ButtonBuilder(data); + case import_v1010.ComponentType.StringSelect: + return new StringSelectMenuBuilder(data); + case import_v1010.ComponentType.TextInput: + return new TextInputBuilder(data); + case import_v1010.ComponentType.UserSelect: + return new UserSelectMenuBuilder(data); + case import_v1010.ComponentType.RoleSelect: + return new RoleSelectMenuBuilder(data); + case import_v1010.ComponentType.MentionableSelect: + return new MentionableSelectMenuBuilder(data); + case import_v1010.ComponentType.ChannelSelect: + return new ChannelSelectMenuBuilder(data); + default: + throw new Error(`Cannot properly serialize component type: ${data.type}`); + } +} +__name(createComponentBuilder, "createComponentBuilder"); + +// src/components/ActionRow.ts +var ActionRowBuilder = class extends ComponentBuilder { + static { + __name(this, "ActionRowBuilder"); + } + /** + * The components within this action row. + */ + components; + /** + * Creates a new action row from API data. + * + * @param data - The API data to create this action row with + * @example + * Creating an action row from an API data object: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Type something", + * style: TextInputStyle.Short, + * type: ComponentType.TextInput, + * }, + * ], + * }); + * ``` + * @example + * Creating an action row using setters and API data: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Click me", + * style: ButtonStyle.Primary, + * type: ComponentType.Button, + * }, + * ], + * }) + * .addComponents(button2, button3); + * ``` + */ + constructor({ components, ...data } = {}) { + super({ type: import_v1011.ComponentType.ActionRow, ...data }); + this.components = components?.map((component) => createComponentBuilder(component)) ?? []; + } + /** + * Adds components to this action row. + * + * @param components - The components to add + */ + addComponents(...components) { + this.components.push(...normalizeArray(components)); + return this; + } + /** + * Sets components for this action row. + * + * @param components - The components to set + */ + setComponents(...components) { + this.components.splice(0, this.components.length, ...normalizeArray(components)); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + return { + ...this.data, + components: this.components.map((component) => component.toJSON()) + }; + } +}; + +// src/interactions/modals/Assertions.ts +var Assertions_exports4 = {}; +__export(Assertions_exports4, { + componentsValidator: () => componentsValidator, + titleValidator: () => titleValidator, + validateRequiredParameters: () => validateRequiredParameters2 +}); +var import_shapeshift4 = require("@sapphire/shapeshift"); +var titleValidator = import_shapeshift4.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(45).setValidationEnabled(isValidationEnabled); +var componentsValidator = import_shapeshift4.s.instance(ActionRowBuilder).array.lengthGreaterThanOrEqual(1).setValidationEnabled(isValidationEnabled); +function validateRequiredParameters2(customId, title, components) { + customIdValidator.parse(customId); + titleValidator.parse(title); + componentsValidator.parse(components); +} +__name(validateRequiredParameters2, "validateRequiredParameters"); + +// src/interactions/modals/Modal.ts +var ModalBuilder = class { + static { + __name(this, "ModalBuilder"); + } + /** + * The API data associated with this modal. + */ + data; + /** + * The components within this modal. + */ + components = []; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ + constructor({ components, ...data } = {}) { + this.data = { ...data }; + this.components = components?.map((component) => createComponentBuilder(component)) ?? []; + } + /** + * Sets the title of this modal. + * + * @param title - The title to use + */ + setTitle(title) { + this.data.title = titleValidator.parse(title); + return this; + } + /** + * Sets the custom id of this modal. + * + * @param customId - The custom id to use + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Adds components to this modal. + * + * @param components - The components to add + */ + addComponents(...components) { + this.components.push( + ...normalizeArray(components).map( + (component) => component instanceof ActionRowBuilder ? component : new ActionRowBuilder(component) + ) + ); + return this; + } + /** + * Sets components for this modal. + * + * @param components - The components to set + */ + setComponents(...components) { + this.components.splice(0, this.components.length, ...normalizeArray(components)); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredParameters2(this.data.custom_id, this.data.title, this.components); + return { + ...this.data, + components: this.components.map((component) => component.toJSON()) + }; + } +}; + +// src/interactions/slashCommands/Assertions.ts +var Assertions_exports5 = {}; +__export(Assertions_exports5, { + assertReturnOfBuilder: () => assertReturnOfBuilder, + localizationMapPredicate: () => localizationMapPredicate, + validateChoicesLength: () => validateChoicesLength, + validateDMPermission: () => validateDMPermission, + validateDefaultMemberPermissions: () => validateDefaultMemberPermissions, + validateDefaultPermission: () => validateDefaultPermission, + validateDescription: () => validateDescription, + validateLocale: () => validateLocale, + validateLocalizationMap: () => validateLocalizationMap, + validateMaxOptionsLength: () => validateMaxOptionsLength, + validateNSFW: () => validateNSFW, + validateName: () => validateName, + validateRequired: () => validateRequired, + validateRequiredParameters: () => validateRequiredParameters3 +}); +var import_shapeshift5 = require("@sapphire/shapeshift"); +var import_v1012 = require("discord-api-types/v10"); +var namePredicate = import_shapeshift5.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(32).regex(/^[\p{Ll}\p{Lm}\p{Lo}\p{N}\p{sc=Devanagari}\p{sc=Thai}_-]+$/u).setValidationEnabled(isValidationEnabled); +function validateName(name) { + namePredicate.parse(name); +} +__name(validateName, "validateName"); +var descriptionPredicate2 = import_shapeshift5.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var localePredicate = import_shapeshift5.s.nativeEnum(import_v1012.Locale); +function validateDescription(description) { + descriptionPredicate2.parse(description); +} +__name(validateDescription, "validateDescription"); +var maxArrayLengthPredicate = import_shapeshift5.s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateLocale(locale) { + return localePredicate.parse(locale); +} +__name(validateLocale, "validateLocale"); +function validateMaxOptionsLength(options) { + maxArrayLengthPredicate.parse(options); +} +__name(validateMaxOptionsLength, "validateMaxOptionsLength"); +function validateRequiredParameters3(name, description, options) { + validateName(name); + validateDescription(description); + validateMaxOptionsLength(options); +} +__name(validateRequiredParameters3, "validateRequiredParameters"); +var booleanPredicate = import_shapeshift5.s.boolean; +function validateDefaultPermission(value) { + booleanPredicate.parse(value); +} +__name(validateDefaultPermission, "validateDefaultPermission"); +function validateRequired(required) { + booleanPredicate.parse(required); +} +__name(validateRequired, "validateRequired"); +var choicesLengthPredicate = import_shapeshift5.s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateChoicesLength(amountAdding, choices) { + choicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding); +} +__name(validateChoicesLength, "validateChoicesLength"); +function assertReturnOfBuilder(input, ExpectedInstanceOf) { + import_shapeshift5.s.instance(ExpectedInstanceOf).parse(input); +} +__name(assertReturnOfBuilder, "assertReturnOfBuilder"); +var localizationMapPredicate = import_shapeshift5.s.object(Object.fromEntries(Object.values(import_v1012.Locale).map((locale) => [locale, import_shapeshift5.s.string.nullish]))).strict.nullish.setValidationEnabled(isValidationEnabled); +function validateLocalizationMap(value) { + localizationMapPredicate.parse(value); +} +__name(validateLocalizationMap, "validateLocalizationMap"); +var dmPermissionPredicate = import_shapeshift5.s.boolean.nullish; +function validateDMPermission(value) { + dmPermissionPredicate.parse(value); +} +__name(validateDMPermission, "validateDMPermission"); +var memberPermissionPredicate = import_shapeshift5.s.union( + import_shapeshift5.s.bigint.transform((value) => value.toString()), + import_shapeshift5.s.number.safeInt.transform((value) => value.toString()), + import_shapeshift5.s.string.regex(/^\d+$/) +).nullish; +function validateDefaultMemberPermissions(permissions) { + return memberPermissionPredicate.parse(permissions); +} +__name(validateDefaultMemberPermissions, "validateDefaultMemberPermissions"); +function validateNSFW(value) { + booleanPredicate.parse(value); +} +__name(validateNSFW, "validateNSFW"); + +// src/interactions/slashCommands/SlashCommandBuilder.ts +var import_ts_mixer6 = require("ts-mixer"); + +// src/interactions/slashCommands/SlashCommandSubcommands.ts +var import_v1024 = require("discord-api-types/v10"); +var import_ts_mixer5 = require("ts-mixer"); + +// src/interactions/slashCommands/mixins/NameAndDescription.ts +var SharedNameAndDescription = class { + static { + __name(this, "SharedNameAndDescription"); + } + /** + * The name of this command. + */ + name; + /** + * The name localizations of this command. + */ + name_localizations; + /** + * The description of this command. + */ + description; + /** + * The description localizations of this command. + */ + description_localizations; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ + setName(name) { + validateName(name); + Reflect.set(this, "name", name); + return this; + } + /** + * Sets the description of this command. + * + * @param description - The description to use + */ + setDescription(description) { + validateDescription(description); + Reflect.set(this, "description", description); + return this; + } + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ + setNameLocalization(locale, localizedName) { + if (!this.name_localizations) { + Reflect.set(this, "name_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedName === null) { + this.name_localizations[parsedLocale] = null; + return this; + } + validateName(localizedName); + this.name_localizations[parsedLocale] = localizedName; + return this; + } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ + setNameLocalizations(localizedNames) { + if (localizedNames === null) { + Reflect.set(this, "name_localizations", null); + return this; + } + Reflect.set(this, "name_localizations", {}); + for (const args of Object.entries(localizedNames)) { + this.setNameLocalization(...args); + } + return this; + } + /** + * Sets a description localization for this command. + * + * @param locale - The locale to set + * @param localizedDescription - The localized description for the given locale + */ + setDescriptionLocalization(locale, localizedDescription) { + if (!this.description_localizations) { + Reflect.set(this, "description_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedDescription === null) { + this.description_localizations[parsedLocale] = null; + return this; + } + validateDescription(localizedDescription); + this.description_localizations[parsedLocale] = localizedDescription; + return this; + } + /** + * Sets the description localizations for this command. + * + * @param localizedDescriptions - The object of localized descriptions to set + */ + setDescriptionLocalizations(localizedDescriptions) { + if (localizedDescriptions === null) { + Reflect.set(this, "description_localizations", null); + return this; + } + Reflect.set(this, "description_localizations", {}); + for (const args of Object.entries(localizedDescriptions)) { + this.setDescriptionLocalization(...args); + } + return this; + } +}; + +// src/interactions/slashCommands/options/attachment.ts +var import_v1013 = require("discord-api-types/v10"); + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts +var ApplicationCommandOptionBase = class extends SharedNameAndDescription { + static { + __name(this, "ApplicationCommandOptionBase"); + } + /** + * Whether this option is required. + * + * @defaultValue `false` + */ + required = false; + /** + * Sets whether this option is required. + * + * @param required - Whether this option should be required + */ + setRequired(required) { + validateRequired(required); + Reflect.set(this, "required", required); + return this; + } + /** + * This method runs required validators on this builder. + */ + runRequiredValidations() { + validateRequiredParameters3(this.name, this.description, []); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + validateRequired(this.required); + } +}; + +// src/interactions/slashCommands/options/attachment.ts +var SlashCommandAttachmentOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandAttachmentOption"); + } + /** + * The type of this option. + */ + type = import_v1013.ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/options/boolean.ts +var import_v1014 = require("discord-api-types/v10"); +var SlashCommandBooleanOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandBooleanOption"); + } + /** + * The type of this option. + */ + type = import_v1014.ApplicationCommandOptionType.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/options/channel.ts +var import_v1016 = require("discord-api-types/v10"); +var import_ts_mixer = require("ts-mixer"); + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts +var import_shapeshift6 = require("@sapphire/shapeshift"); +var import_v1015 = require("discord-api-types/v10"); +var allowedChannelTypes = [ + import_v1015.ChannelType.GuildText, + import_v1015.ChannelType.GuildVoice, + import_v1015.ChannelType.GuildCategory, + import_v1015.ChannelType.GuildAnnouncement, + import_v1015.ChannelType.AnnouncementThread, + import_v1015.ChannelType.PublicThread, + import_v1015.ChannelType.PrivateThread, + import_v1015.ChannelType.GuildStageVoice, + import_v1015.ChannelType.GuildForum, + import_v1015.ChannelType.GuildMedia +]; +var channelTypesPredicate = import_shapeshift6.s.array(import_shapeshift6.s.union(...allowedChannelTypes.map((type) => import_shapeshift6.s.literal(type)))); +var ApplicationCommandOptionChannelTypesMixin = class { + static { + __name(this, "ApplicationCommandOptionChannelTypesMixin"); + } + /** + * The channel types of this option. + */ + channel_types; + /** + * Adds channel types to this option. + * + * @param channelTypes - The channel types + */ + addChannelTypes(...channelTypes) { + if (this.channel_types === void 0) { + Reflect.set(this, "channel_types", []); + } + this.channel_types.push(...channelTypesPredicate.parse(channelTypes)); + return this; + } +}; + +// src/interactions/slashCommands/options/channel.ts +var SlashCommandChannelOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + type = import_v1016.ApplicationCommandOptionType.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; +__name(SlashCommandChannelOption, "SlashCommandChannelOption"); +SlashCommandChannelOption = __decorateClass([ + (0, import_ts_mixer.mix)(ApplicationCommandOptionChannelTypesMixin) +], SlashCommandChannelOption); + +// src/interactions/slashCommands/options/integer.ts +var import_shapeshift8 = require("@sapphire/shapeshift"); +var import_v1018 = require("discord-api-types/v10"); +var import_ts_mixer2 = require("ts-mixer"); + +// src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts +var ApplicationCommandNumericOptionMinMaxValueMixin = class { + static { + __name(this, "ApplicationCommandNumericOptionMinMaxValueMixin"); + } + /** + * The maximum value of this option. + */ + max_value; + /** + * The minimum value of this option. + */ + min_value; +}; + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts +var import_shapeshift7 = require("@sapphire/shapeshift"); +var import_v1017 = require("discord-api-types/v10"); +var stringPredicate = import_shapeshift7.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100); +var numberPredicate = import_shapeshift7.s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY); +var choicesPredicate = import_shapeshift7.s.object({ + name: stringPredicate, + name_localizations: localizationMapPredicate, + value: import_shapeshift7.s.union(stringPredicate, numberPredicate) +}).array; +var booleanPredicate2 = import_shapeshift7.s.boolean; +var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { + static { + __name(this, "ApplicationCommandOptionWithChoicesAndAutocompleteMixin"); + } + /** + * The choices of this option. + */ + choices; + /** + * Whether this option utilizes autocomplete. + */ + autocomplete; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ + type; + /** + * Adds multiple choices to this option. + * + * @param choices - The choices to add + */ + addChoices(...choices) { + if (choices.length > 0 && this.autocomplete) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + choicesPredicate.parse(choices); + if (this.choices === void 0) { + Reflect.set(this, "choices", []); + } + validateChoicesLength(choices.length, this.choices); + for (const { name, name_localizations, value } of choices) { + if (this.type === import_v1017.ApplicationCommandOptionType.String) { + stringPredicate.parse(value); + } else { + numberPredicate.parse(value); + } + this.choices.push({ name, name_localizations, value }); + } + return this; + } + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ + setChoices(...choices) { + if (choices.length > 0 && this.autocomplete) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + choicesPredicate.parse(choices); + Reflect.set(this, "choices", []); + this.addChoices(...choices); + return this; + } + /** + * Whether this option uses autocomplete. + * + * @param autocomplete - Whether this option should use autocomplete + */ + setAutocomplete(autocomplete) { + booleanPredicate2.parse(autocomplete); + if (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + Reflect.set(this, "autocomplete", autocomplete); + return this; + } +}; + +// src/interactions/slashCommands/options/integer.ts +var numberValidator = import_shapeshift8.s.number.int; +var SlashCommandIntegerOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + type = import_v1018.ApplicationCommandOptionType.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max) { + numberValidator.parse(max); + Reflect.set(this, "max_value", max); + return this; + } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min) { + numberValidator.parse(min); + Reflect.set(this, "min_value", min); + return this; + } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { ...this }; + } +}; +__name(SlashCommandIntegerOption, "SlashCommandIntegerOption"); +SlashCommandIntegerOption = __decorateClass([ + (0, import_ts_mixer2.mix)(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandIntegerOption); + +// src/interactions/slashCommands/options/mentionable.ts +var import_v1019 = require("discord-api-types/v10"); +var SlashCommandMentionableOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandMentionableOption"); + } + /** + * The type of this option. + */ + type = import_v1019.ApplicationCommandOptionType.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/options/number.ts +var import_shapeshift9 = require("@sapphire/shapeshift"); +var import_v1020 = require("discord-api-types/v10"); +var import_ts_mixer3 = require("ts-mixer"); +var numberValidator2 = import_shapeshift9.s.number; +var SlashCommandNumberOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + type = import_v1020.ApplicationCommandOptionType.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max) { + numberValidator2.parse(max); + Reflect.set(this, "max_value", max); + return this; + } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min) { + numberValidator2.parse(min); + Reflect.set(this, "min_value", min); + return this; + } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { ...this }; + } +}; +__name(SlashCommandNumberOption, "SlashCommandNumberOption"); +SlashCommandNumberOption = __decorateClass([ + (0, import_ts_mixer3.mix)(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandNumberOption); + +// src/interactions/slashCommands/options/role.ts +var import_v1021 = require("discord-api-types/v10"); +var SlashCommandRoleOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandRoleOption"); + } + /** + * The type of this option. + */ + type = import_v1021.ApplicationCommandOptionType.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/options/string.ts +var import_shapeshift10 = require("@sapphire/shapeshift"); +var import_v1022 = require("discord-api-types/v10"); +var import_ts_mixer4 = require("ts-mixer"); +var minLengthValidator2 = import_shapeshift10.s.number.greaterThanOrEqual(0).lessThanOrEqual(6e3); +var maxLengthValidator2 = import_shapeshift10.s.number.greaterThanOrEqual(1).lessThanOrEqual(6e3); +var SlashCommandStringOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + type = import_v1022.ApplicationCommandOptionType.String; + /** + * The maximum length of this option. + */ + max_length; + /** + * The minimum length of this option. + */ + min_length; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ + setMaxLength(max) { + maxLengthValidator2.parse(max); + Reflect.set(this, "max_length", max); + return this; + } + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ + setMinLength(min) { + minLengthValidator2.parse(min); + Reflect.set(this, "min_length", min); + return this; + } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { ...this }; + } +}; +__name(SlashCommandStringOption, "SlashCommandStringOption"); +SlashCommandStringOption = __decorateClass([ + (0, import_ts_mixer4.mix)(ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandStringOption); + +// src/interactions/slashCommands/options/user.ts +var import_v1023 = require("discord-api-types/v10"); +var SlashCommandUserOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandUserOption"); + } + /** + * The type of this option. + */ + type = import_v1023.ApplicationCommandOptionType.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts +var SharedSlashCommandOptions = class { + static { + __name(this, "SharedSlashCommandOptions"); + } + options; + /** + * Adds a boolean option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addBooleanOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandBooleanOption); + } + /** + * Adds a user option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addUserOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandUserOption); + } + /** + * Adds a channel option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addChannelOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandChannelOption); + } + /** + * Adds a role option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addRoleOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandRoleOption); + } + /** + * Adds an attachment option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addAttachmentOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandAttachmentOption); + } + /** + * Adds a mentionable option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addMentionableOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandMentionableOption); + } + /** + * Adds a string option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addStringOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandStringOption); + } + /** + * Adds an integer option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addIntegerOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandIntegerOption); + } + /** + * Adds a number option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addNumberOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandNumberOption); + } + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ + _sharedAddOptionMethod(input, Instance) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new Instance()) : input; + assertReturnOfBuilder(result, Instance); + options.push(result); + return this; + } +}; + +// src/interactions/slashCommands/SlashCommandSubcommands.ts +var SlashCommandSubcommandGroupBuilder = class { + /** + * The name of this subcommand group. + */ + name = void 0; + /** + * The description of this subcommand group. + */ + description = void 0; + /** + * The subcommands within this subcommand group. + */ + options = []; + /** + * Adds a new subcommand to this group. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ + addSubcommand(input) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new SlashCommandSubcommandBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandBuilder); + options.push(result); + return this; + } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + return { + type: import_v1024.ApplicationCommandOptionType.SubcommandGroup, + name: this.name, + name_localizations: this.name_localizations, + description: this.description, + description_localizations: this.description_localizations, + options: this.options.map((option) => option.toJSON()) + }; + } +}; +__name(SlashCommandSubcommandGroupBuilder, "SlashCommandSubcommandGroupBuilder"); +SlashCommandSubcommandGroupBuilder = __decorateClass([ + (0, import_ts_mixer5.mix)(SharedNameAndDescription) +], SlashCommandSubcommandGroupBuilder); +var SlashCommandSubcommandBuilder = class { + /** + * The name of this subcommand. + */ + name = void 0; + /** + * The description of this subcommand. + */ + description = void 0; + /** + * The options within this subcommand. + */ + options = []; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + return { + type: import_v1024.ApplicationCommandOptionType.Subcommand, + name: this.name, + name_localizations: this.name_localizations, + description: this.description, + description_localizations: this.description_localizations, + options: this.options.map((option) => option.toJSON()) + }; + } +}; +__name(SlashCommandSubcommandBuilder, "SlashCommandSubcommandBuilder"); +SlashCommandSubcommandBuilder = __decorateClass([ + (0, import_ts_mixer5.mix)(SharedNameAndDescription, SharedSlashCommandOptions) +], SlashCommandSubcommandBuilder); + +// src/interactions/slashCommands/SlashCommandBuilder.ts +var SlashCommandBuilder = class { + /** + * The name of this command. + */ + name = void 0; + /** + * The name localizations of this command. + */ + name_localizations; + /** + * The description of this command. + */ + description = void 0; + /** + * The description localizations of this command. + */ + description_localizations; + /** + * The options of this command. + */ + options = []; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ + default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + dm_permission = void 0; + /** + * Whether this command is NSFW. + */ + nsfw = void 0; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether or not to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. + */ + setDefaultPermission(value) { + validateDefaultPermission(value); + Reflect.set(this, "default_permission", value); + return this; + } + /** + * Sets the default permissions a member should have in order to run the command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDefaultMemberPermissions(permissions) { + const permissionValue = validateDefaultMemberPermissions(permissions); + Reflect.set(this, "default_member_permissions", permissionValue); + return this; + } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDMPermission(enabled) { + validateDMPermission(enabled); + Reflect.set(this, "dm_permission", enabled); + return this; + } + /** + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw = true) { + validateNSFW(nsfw); + Reflect.set(this, "nsfw", nsfw); + return this; + } + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder + */ + addSubcommandGroup(input) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new SlashCommandSubcommandGroupBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder); + options.push(result); + return this; + } + /** + * Adds a new subcommand to this command. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ + addSubcommand(input) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new SlashCommandSubcommandBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandBuilder); + options.push(result); + return this; + } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + return { + ...this, + options: this.options.map((option) => option.toJSON()) + }; + } +}; +__name(SlashCommandBuilder, "SlashCommandBuilder"); +SlashCommandBuilder = __decorateClass([ + (0, import_ts_mixer6.mix)(SharedSlashCommandOptions, SharedNameAndDescription) +], SlashCommandBuilder); + +// src/interactions/contextMenuCommands/Assertions.ts +var Assertions_exports6 = {}; +__export(Assertions_exports6, { + validateDMPermission: () => validateDMPermission2, + validateDefaultMemberPermissions: () => validateDefaultMemberPermissions2, + validateDefaultPermission: () => validateDefaultPermission2, + validateName: () => validateName2, + validateRequiredParameters: () => validateRequiredParameters4, + validateType: () => validateType +}); +var import_shapeshift11 = require("@sapphire/shapeshift"); +var import_v1025 = require("discord-api-types/v10"); +var namePredicate2 = import_shapeshift11.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(32).regex(/^( *[\p{P}\p{L}\p{N}\p{sc=Devanagari}\p{sc=Thai}]+ *)+$/u).setValidationEnabled(isValidationEnabled); +var typePredicate = import_shapeshift11.s.union(import_shapeshift11.s.literal(import_v1025.ApplicationCommandType.User), import_shapeshift11.s.literal(import_v1025.ApplicationCommandType.Message)).setValidationEnabled(isValidationEnabled); +var booleanPredicate3 = import_shapeshift11.s.boolean; +function validateDefaultPermission2(value) { + booleanPredicate3.parse(value); +} +__name(validateDefaultPermission2, "validateDefaultPermission"); +function validateName2(name) { + namePredicate2.parse(name); +} +__name(validateName2, "validateName"); +function validateType(type) { + typePredicate.parse(type); +} +__name(validateType, "validateType"); +function validateRequiredParameters4(name, type) { + validateName2(name); + validateType(type); +} +__name(validateRequiredParameters4, "validateRequiredParameters"); +var dmPermissionPredicate2 = import_shapeshift11.s.boolean.nullish; +function validateDMPermission2(value) { + dmPermissionPredicate2.parse(value); +} +__name(validateDMPermission2, "validateDMPermission"); +var memberPermissionPredicate2 = import_shapeshift11.s.union( + import_shapeshift11.s.bigint.transform((value) => value.toString()), + import_shapeshift11.s.number.safeInt.transform((value) => value.toString()), + import_shapeshift11.s.string.regex(/^\d+$/) +).nullish; +function validateDefaultMemberPermissions2(permissions) { + return memberPermissionPredicate2.parse(permissions); +} +__name(validateDefaultMemberPermissions2, "validateDefaultMemberPermissions"); + +// src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts +var ContextMenuCommandBuilder = class { + static { + __name(this, "ContextMenuCommandBuilder"); + } + /** + * The name of this command. + */ + name = void 0; + /** + * The name localizations of this command. + */ + name_localizations; + /** + * The type of this command. + */ + type = void 0; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ + default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + dm_permission = void 0; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ + setName(name) { + validateName2(name); + Reflect.set(this, "name", name); + return this; + } + /** + * Sets the type of this command. + * + * @param type - The type to use + */ + setType(type) { + validateType(type); + Reflect.set(this, "type", type); + return this; + } + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + setDefaultPermission(value) { + validateDefaultPermission2(value); + Reflect.set(this, "default_permission", value); + return this; + } + /** + * Sets the default permissions a member should have in order to run this command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDefaultMemberPermissions(permissions) { + const permissionValue = validateDefaultMemberPermissions2(permissions); + Reflect.set(this, "default_member_permissions", permissionValue); + return this; + } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDMPermission(enabled) { + validateDMPermission2(enabled); + Reflect.set(this, "dm_permission", enabled); + return this; + } + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ + setNameLocalization(locale, localizedName) { + if (!this.name_localizations) { + Reflect.set(this, "name_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedName === null) { + this.name_localizations[parsedLocale] = null; + return this; + } + validateName2(localizedName); + this.name_localizations[parsedLocale] = localizedName; + return this; + } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ + setNameLocalizations(localizedNames) { + if (localizedNames === null) { + Reflect.set(this, "name_localizations", null); + return this; + } + Reflect.set(this, "name_localizations", {}); + for (const args of Object.entries(localizedNames)) + this.setNameLocalization(...args); + return this; + } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters4(this.name, this.type); + validateLocalizationMap(this.name_localizations); + return { ...this }; + } +}; + +// src/util/componentUtil.ts +function embedLength(data) { + return (data.title?.length ?? 0) + (data.description?.length ?? 0) + (data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) + (data.footer?.text.length ?? 0) + (data.author?.name.length ?? 0); +} +__name(embedLength, "embedLength"); + +// src/index.ts +var version = "1.7.0"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + ActionRowBuilder, + ApplicationCommandNumericOptionMinMaxValueMixin, + ApplicationCommandOptionBase, + ApplicationCommandOptionChannelTypesMixin, + ApplicationCommandOptionWithChoicesAndAutocompleteMixin, + BaseSelectMenuBuilder, + ButtonBuilder, + ChannelSelectMenuBuilder, + ComponentAssertions, + ComponentBuilder, + ContextMenuCommandAssertions, + ContextMenuCommandBuilder, + EmbedAssertions, + EmbedBuilder, + MentionableSelectMenuBuilder, + ModalAssertions, + ModalBuilder, + RoleSelectMenuBuilder, + SelectMenuBuilder, + SelectMenuOptionBuilder, + SharedNameAndDescription, + SharedSlashCommandOptions, + SlashCommandAssertions, + SlashCommandAttachmentOption, + SlashCommandBooleanOption, + SlashCommandBuilder, + SlashCommandChannelOption, + SlashCommandIntegerOption, + SlashCommandMentionableOption, + SlashCommandNumberOption, + SlashCommandRoleOption, + SlashCommandStringOption, + SlashCommandSubcommandBuilder, + SlashCommandSubcommandGroupBuilder, + SlashCommandUserOption, + StringSelectMenuBuilder, + StringSelectMenuOptionBuilder, + TextInputAssertions, + TextInputBuilder, + UserSelectMenuBuilder, + createComponentBuilder, + disableValidators, + embedLength, + enableValidators, + isValidationEnabled, + normalizeArray, + version, + ...require("@discordjs/formatters") +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.js.map b/node_modules/@discordjs/builders/dist/index.js.map new file mode 100644 index 0000000..e452c66 --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts"],"sourcesContent":["export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\n// TODO: Consider removing this dep in the next major version\nexport * from '@discordjs/formatters';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version\n * that you are currently using.\n *\n * @privateRemarks This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild.\n */\nexport const version = '1.7.0' as string;\n","import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\n/**\n * Enables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function enableValidators() {\n\treturn (validate = true);\n}\n\n/**\n * Disables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function disableValidators() {\n\treturn (validate = false);\n}\n\n/**\n * Checks whether validation is occurring.\n */\nexport function isValidationEnabled() {\n\treturn validate;\n}\n","/**\n * Normalizes data that is a rest parameter or an array into an array with a depth of 1.\n *\n * @typeParam ItemType - The data that must satisfy {@link RestOrArray}.\n * @param arr - The (possibly variadic) data to normalize\n */\nexport function normalizeArray(arr: RestOrArray): ItemType[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as ItemType[];\n}\n\n/**\n * Represents data that may be an array or came from a rest parameter.\n *\n * @remarks\n * This type is used throughout builders to ensure both an array and variadic arguments\n * may be used. It is normalized with {@link normalizeArray}.\n */\nexport type RestOrArray = Type[] | [Type[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\n/**\n * A tuple satisfying the RGB color model.\n *\n * @see {@link https://developer.mozilla.org/docs/Glossary/RGB}\n */\nexport type RGBTuple = [red: number, green: number, blue: number];\n\n/**\n * The base icon data typically used in payloads.\n */\nexport interface IconData {\n\t/**\n\t * The URL of the icon.\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon.\n\t */\n\tproxyIconURL?: string;\n}\n\n/**\n * Represents the author data of an embed.\n */\nexport type EmbedAuthorData = IconData & Omit;\n\n/**\n * Represents the author options of an embed.\n */\nexport type EmbedAuthorOptions = Omit;\n\n/**\n * Represents the footer data of an embed.\n */\nexport type EmbedFooterData = IconData & Omit;\n\n/**\n * Represents the footer options of an embed.\n */\nexport type EmbedFooterOptions = Omit;\n\n/**\n * Represents the image data of an embed.\n */\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image.\n\t */\n\tproxyURL?: string;\n}\n\n/**\n * A builder that creates API-compatible JSON data for embeds.\n */\nexport class EmbedBuilder {\n\t/**\n\t * The API data associated with this embed.\n\t */\n\tpublic readonly data: APIEmbed;\n\n\t/**\n\t * Creates a new embed from API data.\n\t *\n\t * @param data - The API data to create this embed with\n\t */\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed.\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array:\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic):\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\tconst normalizedFields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(normalizedFields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(normalizedFields);\n\n\t\tif (this.data.fields) this.data.fields.push(...normalizedFields);\n\t\telse this.data.fields = normalizedFields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields for this embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field:\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields:\n\t * ```ts\n\t * const n = 4;\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field:\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the fields for this embed.\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed.\n\t *\n\t * @param options - The options to use\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed.\n\t *\n\t * @param color - The color to use\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed.\n\t *\n\t * @param options - The footer to use\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed.\n\t *\n\t * @param url - The image URL to use\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed.\n\t *\n\t * @param url - The thumbnail URL to use\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed.\n\t *\n\t * @param timestamp - The timestamp or date to use\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title for this embed.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed.\n\t *\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menu options.\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data.\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah');\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label for this option.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this option.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description for this option.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default.\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display for this option.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * The builders that may be used for messages.\n */\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\n\n/**\n * The builders that may be used for modals.\n */\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\n\n/**\n * The builders that may be used within an action row for messages.\n */\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\n\n/**\n * The builders that may be used within an action row for modals.\n */\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\n\n/**\n * Any builder.\n */\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * A builder that creates API-compatible JSON data for action rows.\n *\n * @typeParam ComponentType - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row.\n\t */\n\tpublic readonly components: ComponentType[];\n\n\t/**\n\t * Creates a new action row from API data.\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as ComponentType[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this action row.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\n/**\n * Any action row component data represented as an object.\n */\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * The base component builder that contains common symbols for all sorts of components.\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\t/**\n\t * Constructs a new kind of component.\n\t *\n\t * @param data - The data to construct a component out of\n\t */\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * Components here are mapped to their respective builder.\n */\nexport interface MappedComponentTypes {\n\t/**\n\t * The action row component type is associated with an {@link ActionRowBuilder}.\n\t */\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t/**\n\t * The button component type is associated with an {@link ButtonBuilder}.\n\t */\n\t[ComponentType.Button]: ButtonBuilder;\n\t/**\n\t * The string select component type is associated with an {@link StringSelectMenuBuilder}.\n\t */\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t/**\n\t * The text inpiut component type is associated with an {@link TextInputBuilder}.\n\t */\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t/**\n\t * The user select component type is associated with an {@link UserSelectMenuBuilder}.\n\t */\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t/**\n\t * The role select component type is associated with an {@link RoleSelectMenuBuilder}.\n\t */\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t/**\n\t * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}.\n\t */\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t/**\n\t * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}.\n\t */\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam ComponentType - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-constituents\n\tdata: (APIModalComponent | APIMessageComponent) & { type: ComponentType },\n): MappedComponentTypes[ComponentType];\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam ComponentBuilder - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(\n\tdata: ComponentBuilder,\n): ComponentBuilder;\n\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * A builder that creates API-compatible JSON data for buttons.\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data.\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: '🙂' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button.\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`.\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button.\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled.\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import {\n\ttype APIChannelSelectComponent,\n\ttype ChannelType,\n\ttype Snowflake,\n\tComponentType,\n\tSelectMenuDefaultValueType,\n} from 'discord-api-types/v10';\nimport { type RestOrArray, normalizeArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator, optionsLengthValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for channel select menus.\n */\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\t/**\n\t * Adds channel types to this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets channel types for this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds default channels to this auto populated select menu.\n\t *\n\t * @param channels - The channels to add\n\t */\n\tpublic addDefaultChannels(...channels: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(channels);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.Channel as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets default channels to this auto populated select menu.\n\t *\n\t * @param channels - The channels to set\n\t */\n\tpublic setDefaultChannels(...channels: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(channels);\n\t\toptionsLengthValidator.parse(normalizedValues.length);\n\n\t\tthis.data.default_values = normalizedValues.map((id) => ({\n\t\t\tid,\n\t\t\ttype: SelectMenuDefaultValueType.Channel as const,\n\t\t}));\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * The base select menu builder that contains common symbols for select menu builders.\n *\n * @typeParam SelectMenuType - The type of select menu this would be instantiated for.\n */\nexport abstract class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu.\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu.\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled.\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import {\n\ttype APIMentionableSelectComponent,\n\ttype APISelectMenuDefaultValue,\n\ttype Snowflake,\n\tComponentType,\n\tSelectMenuDefaultValueType,\n} from 'discord-api-types/v10';\nimport { type RestOrArray, normalizeArray } from '../../util/normalizeArray.js';\nimport { optionsLengthValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for mentionable select menus.\n */\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n\n\t/**\n\t * Adds default roles to this auto populated select menu.\n\t *\n\t * @param roles - The roles to add\n\t */\n\tpublic addDefaultRoles(...roles: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(roles);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.Role as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds default users to this auto populated select menu.\n\t *\n\t * @param users - The users to add\n\t */\n\tpublic addDefaultUsers(...users: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(users);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.User as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds default values to this auto populated select menu.\n\t *\n\t * @param values - The values to add\n\t */\n\tpublic addDefaultValues(\n\t\t...values: RestOrArray<\n\t\t\t| APISelectMenuDefaultValue\n\t\t\t| APISelectMenuDefaultValue\n\t\t>\n\t) {\n\t\tconst normalizedValues = normalizeArray(values);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\t\tthis.data.default_values.push(...normalizedValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets default values to this auto populated select menu.\n\t *\n\t * @param values - The values to set\n\t */\n\tpublic setDefaultValues(\n\t\t...values: RestOrArray<\n\t\t\t| APISelectMenuDefaultValue\n\t\t\t| APISelectMenuDefaultValue\n\t\t>\n\t) {\n\t\tconst normalizedValues = normalizeArray(values);\n\t\toptionsLengthValidator.parse(normalizedValues.length);\n\t\tthis.data.default_values = normalizedValues.slice();\n\t\treturn this;\n\t}\n}\n","import {\n\ttype APIRoleSelectComponent,\n\ttype Snowflake,\n\tComponentType,\n\tSelectMenuDefaultValueType,\n} from 'discord-api-types/v10';\nimport { type RestOrArray, normalizeArray } from '../../util/normalizeArray.js';\nimport { optionsLengthValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for role select menus.\n */\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n\n\t/**\n\t * Adds default roles to this auto populated select menu.\n\t *\n\t * @param roles - The roles to add\n\t */\n\tpublic addDefaultRoles(...roles: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(roles);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.Role as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets default roles to this auto populated select menu.\n\t *\n\t * @param roles - The roles to set\n\t */\n\tpublic setDefaultRoles(...roles: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(roles);\n\t\toptionsLengthValidator.parse(normalizedValues.length);\n\n\t\tthis.data.default_values = normalizedValues.map((id) => ({\n\t\t\tid,\n\t\t\ttype: SelectMenuDefaultValueType.Role as const,\n\t\t}));\n\n\t\treturn this;\n\t}\n}\n","import { ComponentType } from 'discord-api-types/v10';\nimport type { APIStringSelectComponent, APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menus.\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu.\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu.\n\t *\n\t * @param options - The options to add\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + normalizedOptions.length);\n\t\tthis.options.push(\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options for this select menu.\n\t *\n\t * @param options - The options to set\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\treturn this.spliceOptions(0, this.options.length, ...options);\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts options for this select menu.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}.\n\t * It's useful for modifying and adjusting the order of existing options.\n\t * @example\n\t * Remove the first option:\n\t * ```ts\n\t * selectMenu.spliceOptions(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n option:\n\t * ```ts\n\t * const n = 4;\n\t * selectMenu.spliceOptions(0, n);\n\t * ```\n\t * @example\n\t * Remove the last option:\n\t * ```ts\n\t * selectMenu.spliceOptions(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of options to remove\n\t * @param options - The replacing option objects or builders\n\t */\n\tpublic spliceOptions(\n\t\tindex: number,\n\t\tdeleteCount: number,\n\t\t...options: RestOrArray\n\t) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\n\t\tconst clone = [...this.options];\n\n\t\tclone.splice(\n\t\t\tindex,\n\t\t\tdeleteCount,\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\n\t\toptionsLengthValidator.parse(clone.length);\n\t\tthis.options.splice(0, this.options.length, ...clone);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import {\n\ttype APIUserSelectComponent,\n\ttype Snowflake,\n\tComponentType,\n\tSelectMenuDefaultValueType,\n} from 'discord-api-types/v10';\nimport { type RestOrArray, normalizeArray } from '../../util/normalizeArray.js';\nimport { optionsLengthValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for user select menus.\n */\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n\n\t/**\n\t * Adds default users to this auto populated select menu.\n\t *\n\t * @param users - The users to add\n\t */\n\tpublic addDefaultUsers(...users: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(users);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.User as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets default users to this auto populated select menu.\n\t *\n\t * @param users - The users to set\n\t */\n\tpublic setDefaultUsers(...users: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(users);\n\t\toptionsLengthValidator.parse(normalizedValues.length);\n\n\t\tthis.data.default_values = normalizedValues.map((id) => ({\n\t\t\tid,\n\t\t\ttype: SelectMenuDefaultValueType.User as const,\n\t\t}));\n\n\t\treturn this;\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for text inputs.\n */\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data.\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input.\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input.\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder for this text input.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this text input.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required.\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for modals.\n */\nexport class ModalBuilder implements JSONEncodable {\n\t/**\n\t * The API data associated with this modal.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * The components within this modal.\n\t */\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\t/**\n\t * Creates a new modal from API data.\n\t *\n\t * @param data - The API data to create this modal with\n\t */\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of this modal.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of this modal.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this modal.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tReturnType extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => ReturnType): asserts input is ReturnType {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n\nexport function validateNSFW(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n\tvalidateNSFW,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * A builder that creates API-compatible JSON data for slash commands.\n */\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this command.\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Whether this command is NSFW.\n\t */\n\tpublic readonly nsfw: boolean | undefined = undefined;\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this command is NSFW.\n\t *\n\t * @param nsfw - Whether this command is NSFW\n\t */\n\tpublic setNSFW(nsfw = true) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateNSFW(nsfw);\n\t\tReflect.set(this, 'nsfw', nsfw);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command.\n\t *\n\t * @param input - A function that returns a subcommand group builder or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\n/**\n * An interface specifically for slash command subcommands.\n */\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\n/**\n * An interface specifically for slash command options.\n */\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\n/**\n * An interface that ensures the `toJSON()` call will return something\n * that can be serialized into API-compatible data.\n */\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands within this subcommand group.\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * A builder that creates API-compatible JSON data for slash command subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options within this subcommand.\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\n/**\n * This mixin holds name and description symbols for slash commands.\n */\nexport class SharedNameAndDescription {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name!: string;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description!: string;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this command.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations for this command.\n\t *\n\t * @param localizedDescriptions - The object of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command attachment option.\n */\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\n/**\n * The base application command option builder that contains common symbols for application command builders.\n */\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\t/**\n\t * Whether this option is required.\n\t *\n\t * @defaultValue `false`\n\t */\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Sets whether this option is required.\n\t *\n\t * @param required - Whether this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\t/**\n\t * This method runs required validators on this builder.\n\t */\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command boolean option.\n */\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n/**\n * A slash command channel option.\n */\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n/**\n * The allowed channel types used for a channel option in a slash command builder.\n *\n * @privateRemarks This can't be dynamic because const enums are erased at runtime.\n * @internal\n */\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n\tChannelType.GuildMedia,\n] as const;\n\n/**\n * The type of allowed channel types used for a channel option.\n */\nexport type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\n/**\n * This mixin holds channel type symbols used for options.\n */\nexport class ApplicationCommandOptionChannelTypesMixin {\n\t/**\n\t * The channel types of this option.\n\t */\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option.\n\t *\n\t * @param channelTypes - The channel types\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n/**\n * A slash command integer option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this } as APIApplicationCommandIntegerOption;\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","/**\n * This mixin holds minimum and maximum symbols used for options.\n */\nexport abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\t/**\n\t * The maximum value of this option.\n\t */\n\tpublic readonly max_value?: number;\n\n\t/**\n\t * The minimum value of this option.\n\t */\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option.\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option.\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\n/**\n * This mixin holds choices and autocomplete symbols used for options.\n */\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\t/**\n\t * The choices of this option.\n\t */\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\t/**\n\t * Whether this option utilizes autocomplete.\n\t */\n\tpublic readonly autocomplete?: boolean;\n\n\t/**\n\t * The type of this option.\n\t *\n\t * @privateRemarks Since this is present and this is a mixin, this is needed.\n\t */\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices to this option.\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets multiple choices for this option.\n\t *\n\t * @param choices - The choices to set\n\t */\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Whether this option uses autocomplete.\n\t *\n\t * @param autocomplete - Whether this option should use autocomplete\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command mentionable option.\n */\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n/**\n * A slash command number option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this } as APIApplicationCommandNumberOption;\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command role option.\n */\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n/**\n * A slash command string option.\n */\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\t/**\n\t * The maximum length of this option.\n\t */\n\tpublic readonly max_length?: number;\n\n\t/**\n\t * The minimum length of this option.\n\t */\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this } as APIApplicationCommandStringOption;\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command user option.\n */\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\n/**\n * This mixin holds symbols that can be shared in slash command options.\n *\n * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions.\n */\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\t/**\n\t * Where the actual adding magic happens. ✨\n\t *\n\t * @param input - The input. What else?\n\t * @param Instance - The instance of whatever is being added\n\t * @internal\n\t */\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| OptionBuilder\n\t\t\t| ((\n\t\t\t\t\tbuilder: OptionBuilder,\n\t\t\t ) => Omit | Omit | OptionBuilder),\n\t\tInstance: new () => OptionBuilder,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\n/**\n * The type a context menu command can be.\n */\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n\n/**\n * A builder that creates API-compatible JSON data for context menu commands.\n */\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this command.\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type of this command.\n\t *\n\t * @param type - The type to use\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run this command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIEmbed } from 'discord-api-types/v10';\n\n/**\n * Calculates the length of the embed.\n *\n * @param data - The embed data to check\n */\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AqB,gBAAwC;AACnE,QAAI,mBAAmB,MAAM;AAC5B,cAAQ,IAAI,MAAM,sBAAsB,IAAI;AAC5C,aAAO;AAAA,IACR;AAEA,YAAQ,IAAI,MAAM,sBAAsB,CAAC,CAAC;AAE1C,eAAW,QAAQ,OAAO,QAAQ,cAAc;AAC/C,WAAK,oBAAoB,GAAI,IAAsC;AACpE,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,SAA4D;AAClE,IAAAI,4BAA2B,KAAK,MAAM,KAAK,IAAI;AAE/C,4BAAwB,KAAK,kBAAkB;AAE/C,WAAO,EAAE,GAAG,KAAK;AAAA,EAClB;AACD;;;AC9LO,SAAS,YAAY,MAAgB;AAC3C,UACE,KAAK,OAAO,UAAU,MACtB,KAAK,aAAa,UAAU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;AzC6DT,IAAM,UAAU;","names":["Assertions_exports","Assertions_exports","import_shapeshift","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","Assertions_exports","placeholderValidator","import_shapeshift","import_v10","placeholderValidator","placeholderValidator","isEqual","Assertions_exports","validateRequiredParameters","import_shapeshift","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","import_shapeshift","import_v10","descriptionPredicate","validateRequiredParameters","import_ts_mixer","import_v10","import_ts_mixer","import_v10","validateRequiredParameters","import_v10","import_v10","import_shapeshift","import_v10","import_shapeshift","import_v10","import_ts_mixer","import_shapeshift","import_v10","booleanPredicate","import_v10","import_shapeshift","import_v10","import_ts_mixer","numberValidator","import_v10","import_shapeshift","import_v10","import_ts_mixer","minLengthValidator","maxLengthValidator","import_v10","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","import_shapeshift","import_v10","namePredicate","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.mjs b/node_modules/@discordjs/builders/dist/index.mjs new file mode 100644 index 0000000..6112a1a --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.mjs @@ -0,0 +1,2703 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __decorateClass = (decorators, target, key, kind) => { + var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; + for (var i = decorators.length - 1, decorator; i >= 0; i--) + if (decorator = decorators[i]) + result = (kind ? decorator(target, key, result) : decorator(result)) || result; + if (kind && result) + __defProp(target, key, result); + return result; +}; + +// src/messages/embed/Assertions.ts +var Assertions_exports = {}; +__export(Assertions_exports, { + RGBPredicate: () => RGBPredicate, + authorNamePredicate: () => authorNamePredicate, + colorPredicate: () => colorPredicate, + descriptionPredicate: () => descriptionPredicate, + embedAuthorPredicate: () => embedAuthorPredicate, + embedFieldPredicate: () => embedFieldPredicate, + embedFieldsArrayPredicate: () => embedFieldsArrayPredicate, + embedFooterPredicate: () => embedFooterPredicate, + fieldInlinePredicate: () => fieldInlinePredicate, + fieldLengthPredicate: () => fieldLengthPredicate, + fieldNamePredicate: () => fieldNamePredicate, + fieldValuePredicate: () => fieldValuePredicate, + footerTextPredicate: () => footerTextPredicate, + imageURLPredicate: () => imageURLPredicate, + timestampPredicate: () => timestampPredicate, + titlePredicate: () => titlePredicate, + urlPredicate: () => urlPredicate, + validateFieldLength: () => validateFieldLength +}); +import { s } from "@sapphire/shapeshift"; + +// src/util/validation.ts +var validate = true; +function enableValidators() { + return validate = true; +} +__name(enableValidators, "enableValidators"); +function disableValidators() { + return validate = false; +} +__name(disableValidators, "disableValidators"); +function isValidationEnabled() { + return validate; +} +__name(isValidationEnabled, "isValidationEnabled"); + +// src/messages/embed/Assertions.ts +var fieldNamePredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(256).setValidationEnabled(isValidationEnabled); +var fieldValuePredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(1024).setValidationEnabled(isValidationEnabled); +var fieldInlinePredicate = s.boolean.optional; +var embedFieldPredicate = s.object({ + name: fieldNamePredicate, + value: fieldValuePredicate, + inline: fieldInlinePredicate +}).setValidationEnabled(isValidationEnabled); +var embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled); +var fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateFieldLength(amountAdding, fields) { + fieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding); +} +__name(validateFieldLength, "validateFieldLength"); +var authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled); +var imageURLPredicate = s.string.url({ + allowedProtocols: ["http:", "https:", "attachment:"] +}).nullish.setValidationEnabled(isValidationEnabled); +var urlPredicate = s.string.url({ + allowedProtocols: ["http:", "https:"] +}).nullish.setValidationEnabled(isValidationEnabled); +var embedAuthorPredicate = s.object({ + name: authorNamePredicate, + iconURL: imageURLPredicate, + url: urlPredicate +}).setValidationEnabled(isValidationEnabled); +var RGBPredicate = s.number.int.greaterThanOrEqual(0).lessThanOrEqual(255).setValidationEnabled(isValidationEnabled); +var colorPredicate = s.number.int.greaterThanOrEqual(0).lessThanOrEqual(16777215).or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate])).nullable.setValidationEnabled(isValidationEnabled); +var descriptionPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(4096).nullable.setValidationEnabled(isValidationEnabled); +var footerTextPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(2048).nullable.setValidationEnabled(isValidationEnabled); +var embedFooterPredicate = s.object({ + text: footerTextPredicate, + iconURL: imageURLPredicate +}).setValidationEnabled(isValidationEnabled); +var timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled); +var titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled); + +// src/util/normalizeArray.ts +function normalizeArray(arr) { + if (Array.isArray(arr[0])) + return arr[0]; + return arr; +} +__name(normalizeArray, "normalizeArray"); + +// src/messages/embed/Embed.ts +var EmbedBuilder = class { + static { + __name(this, "EmbedBuilder"); + } + /** + * The API data associated with this embed. + */ + data; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ + constructor(data = {}) { + this.data = { ...data }; + if (data.timestamp) + this.data.timestamp = new Date(data.timestamp).toISOString(); + } + /** + * Appends fields to the embed. + * + * @remarks + * This method accepts either an array of fields or a variable number of field parameters. + * The maximum amount of fields that can be added is 25. + * @example + * Using an array: + * ```ts + * const fields: APIEmbedField[] = ...; + * const embed = new EmbedBuilder() + * .addFields(fields); + * ``` + * @example + * Using rest parameters (variadic): + * ```ts + * const embed = new EmbedBuilder() + * .addFields( + * { name: 'Field 1', value: 'Value 1' }, + * { name: 'Field 2', value: 'Value 2' }, + * ); + * ``` + * @param fields - The fields to add + */ + addFields(...fields) { + const normalizedFields = normalizeArray(fields); + validateFieldLength(normalizedFields.length, this.data.fields); + embedFieldsArrayPredicate.parse(normalizedFields); + if (this.data.fields) + this.data.fields.push(...normalizedFields); + else + this.data.fields = normalizedFields; + return this; + } + /** + * Removes, replaces, or inserts fields for this embed. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. + * The maximum amount of fields that can be added is 25. + * + * It's useful for modifying and adjusting order of the already-existing fields of an embed. + * @example + * Remove the first field: + * ```ts + * embed.spliceFields(0, 1); + * ``` + * @example + * Remove the first n fields: + * ```ts + * const n = 4; + * embed.spliceFields(0, n); + * ``` + * @example + * Remove the last field: + * ```ts + * embed.spliceFields(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of fields to remove + * @param fields - The replacing field objects + */ + spliceFields(index, deleteCount, ...fields) { + validateFieldLength(fields.length - deleteCount, this.data.fields); + embedFieldsArrayPredicate.parse(fields); + if (this.data.fields) + this.data.fields.splice(index, deleteCount, ...fields); + else + this.data.fields = fields; + return this; + } + /** + * Sets the fields for this embed. + * + * @remarks + * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, + * it splices the entire array of fields, replacing them with the provided fields. + * + * You can set a maximum of 25 fields. + * @param fields - The fields to set + */ + setFields(...fields) { + this.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields)); + return this; + } + /** + * Sets the author of this embed. + * + * @param options - The options to use + */ + setAuthor(options) { + if (options === null) { + this.data.author = void 0; + return this; + } + embedAuthorPredicate.parse(options); + this.data.author = { name: options.name, url: options.url, icon_url: options.iconURL }; + return this; + } + /** + * Sets the color of this embed. + * + * @param color - The color to use + */ + setColor(color) { + colorPredicate.parse(color); + if (Array.isArray(color)) { + const [red, green, blue] = color; + this.data.color = (red << 16) + (green << 8) + blue; + return this; + } + this.data.color = color ?? void 0; + return this; + } + /** + * Sets the description of this embed. + * + * @param description - The description to use + */ + setDescription(description) { + descriptionPredicate.parse(description); + this.data.description = description ?? void 0; + return this; + } + /** + * Sets the footer of this embed. + * + * @param options - The footer to use + */ + setFooter(options) { + if (options === null) { + this.data.footer = void 0; + return this; + } + embedFooterPredicate.parse(options); + this.data.footer = { text: options.text, icon_url: options.iconURL }; + return this; + } + /** + * Sets the image of this embed. + * + * @param url - The image URL to use + */ + setImage(url) { + imageURLPredicate.parse(url); + this.data.image = url ? { url } : void 0; + return this; + } + /** + * Sets the thumbnail of this embed. + * + * @param url - The thumbnail URL to use + */ + setThumbnail(url) { + imageURLPredicate.parse(url); + this.data.thumbnail = url ? { url } : void 0; + return this; + } + /** + * Sets the timestamp of this embed. + * + * @param timestamp - The timestamp or date to use + */ + setTimestamp(timestamp = Date.now()) { + timestampPredicate.parse(timestamp); + this.data.timestamp = timestamp ? new Date(timestamp).toISOString() : void 0; + return this; + } + /** + * Sets the title for this embed. + * + * @param title - The title to use + */ + setTitle(title) { + titlePredicate.parse(title); + this.data.title = title ?? void 0; + return this; + } + /** + * Sets the URL of this embed. + * + * @param url - The URL to use + */ + setURL(url) { + urlPredicate.parse(url); + this.data.url = url ?? void 0; + return this; + } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + return { ...this.data }; + } +}; + +// src/index.ts +export * from "@discordjs/formatters"; + +// src/components/Assertions.ts +var Assertions_exports2 = {}; +__export(Assertions_exports2, { + buttonLabelValidator: () => buttonLabelValidator, + buttonStyleValidator: () => buttonStyleValidator, + channelTypesValidator: () => channelTypesValidator, + customIdValidator: () => customIdValidator, + defaultValidator: () => defaultValidator, + disabledValidator: () => disabledValidator, + emojiValidator: () => emojiValidator, + jsonOptionValidator: () => jsonOptionValidator, + labelValueDescriptionValidator: () => labelValueDescriptionValidator, + minMaxValidator: () => minMaxValidator, + optionValidator: () => optionValidator, + optionsLengthValidator: () => optionsLengthValidator, + optionsValidator: () => optionsValidator, + placeholderValidator: () => placeholderValidator, + urlValidator: () => urlValidator, + validateRequiredButtonParameters: () => validateRequiredButtonParameters, + validateRequiredSelectMenuOptionParameters: () => validateRequiredSelectMenuOptionParameters, + validateRequiredSelectMenuParameters: () => validateRequiredSelectMenuParameters +}); +import { s as s2 } from "@sapphire/shapeshift"; +import { ButtonStyle, ChannelType } from "discord-api-types/v10"; + +// src/components/selectMenu/StringSelectMenuOption.ts +var StringSelectMenuOptionBuilder = class { + /** + * Creates a new string select menu option from API data. + * + * @param data - The API data to create this string select menu option with + * @example + * Creating a string select menu option from an API data object: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * label: 'catchy label', + * value: '1', + * }); + * ``` + * @example + * Creating a string select menu option using setters and API data: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * default: true, + * value: '1', + * }) + * .setLabel('woah'); + * ``` + */ + constructor(data = {}) { + this.data = data; + } + static { + __name(this, "StringSelectMenuOptionBuilder"); + } + /** + * Sets the label for this option. + * + * @param label - The label to use + */ + setLabel(label) { + this.data.label = labelValueDescriptionValidator.parse(label); + return this; + } + /** + * Sets the value for this option. + * + * @param value - The value to use + */ + setValue(value) { + this.data.value = labelValueDescriptionValidator.parse(value); + return this; + } + /** + * Sets the description for this option. + * + * @param description - The description to use + */ + setDescription(description) { + this.data.description = labelValueDescriptionValidator.parse(description); + return this; + } + /** + * Sets whether this option is selected by default. + * + * @param isDefault - Whether this option is selected by default + */ + setDefault(isDefault = true) { + this.data.default = defaultValidator.parse(isDefault); + return this; + } + /** + * Sets the emoji to display for this option. + * + * @param emoji - The emoji to use + */ + setEmoji(emoji) { + this.data.emoji = emojiValidator.parse(emoji); + return this; + } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON() { + validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); + return { + ...this.data + }; + } +}; + +// src/components/Assertions.ts +var customIdValidator = s2.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var emojiValidator = s2.object({ + id: s2.string, + name: s2.string, + animated: s2.boolean +}).partial.strict.setValidationEnabled(isValidationEnabled); +var disabledValidator = s2.boolean; +var buttonLabelValidator = s2.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(80).setValidationEnabled(isValidationEnabled); +var buttonStyleValidator = s2.nativeEnum(ButtonStyle); +var placeholderValidator = s2.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled); +var minMaxValidator = s2.number.int.greaterThanOrEqual(0).lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +var labelValueDescriptionValidator = s2.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var jsonOptionValidator = s2.object({ + label: labelValueDescriptionValidator, + value: labelValueDescriptionValidator, + description: labelValueDescriptionValidator.optional, + emoji: emojiValidator.optional, + default: s2.boolean.optional +}).setValidationEnabled(isValidationEnabled); +var optionValidator = s2.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled); +var optionsValidator = optionValidator.array.lengthGreaterThanOrEqual(0).setValidationEnabled(isValidationEnabled); +var optionsLengthValidator = s2.number.int.greaterThanOrEqual(0).lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateRequiredSelectMenuParameters(options, customId) { + customIdValidator.parse(customId); + optionsValidator.parse(options); +} +__name(validateRequiredSelectMenuParameters, "validateRequiredSelectMenuParameters"); +var defaultValidator = s2.boolean; +function validateRequiredSelectMenuOptionParameters(label, value) { + labelValueDescriptionValidator.parse(label); + labelValueDescriptionValidator.parse(value); +} +__name(validateRequiredSelectMenuOptionParameters, "validateRequiredSelectMenuOptionParameters"); +var channelTypesValidator = s2.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled); +var urlValidator = s2.string.url({ + allowedProtocols: ["http:", "https:", "discord:"] +}).setValidationEnabled(isValidationEnabled); +function validateRequiredButtonParameters(style, label, emoji, customId, url) { + if (url && customId) { + throw new RangeError("URL and custom id are mutually exclusive"); + } + if (!label && !emoji) { + throw new RangeError("Buttons must have a label and/or an emoji"); + } + if (style === ButtonStyle.Link) { + if (!url) { + throw new RangeError("Link buttons must have a url"); + } + } else if (url) { + throw new RangeError("Non-link buttons cannot have a url"); + } +} +__name(validateRequiredButtonParameters, "validateRequiredButtonParameters"); + +// src/components/ActionRow.ts +import { + ComponentType as ComponentType9 +} from "discord-api-types/v10"; + +// src/components/Component.ts +var ComponentBuilder = class { + static { + __name(this, "ComponentBuilder"); + } + /** + * The API data associated with this component. + */ + data; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ + constructor(data) { + this.data = data; + } +}; + +// src/components/Components.ts +import { ComponentType as ComponentType8 } from "discord-api-types/v10"; + +// src/components/button/Button.ts +import { + ComponentType +} from "discord-api-types/v10"; +var ButtonBuilder = class extends ComponentBuilder { + static { + __name(this, "ButtonBuilder"); + } + /** + * Creates a new button from API data. + * + * @param data - The API data to create this button with + * @example + * Creating a button from an API data object: + * ```ts + * const button = new ButtonBuilder({ + * custom_id: 'a cool button', + * style: ButtonStyle.Primary, + * label: 'Click Me', + * emoji: { + * name: 'smile', + * id: '123456789012345678', + * }, + * }); + * ``` + * @example + * Creating a button using setters and API data: + * ```ts + * const button = new ButtonBuilder({ + * style: ButtonStyle.Secondary, + * label: 'Click Me', + * }) + * .setEmoji({ name: '🙂' }) + * .setCustomId('another cool button'); + * ``` + */ + constructor(data) { + super({ type: ComponentType.Button, ...data }); + } + /** + * Sets the style of this button. + * + * @param style - The style to use + */ + setStyle(style) { + this.data.style = buttonStyleValidator.parse(style); + return this; + } + /** + * Sets the URL for this button. + * + * @remarks + * This method is only available to buttons using the `Link` button style. + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use + */ + setURL(url) { + this.data.url = urlValidator.parse(url); + return this; + } + /** + * Sets the custom id for this button. + * + * @remarks + * This method is only applicable to buttons that are not using the `Link` button style. + * @param customId - The custom id to use + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets the emoji to display on this button. + * + * @param emoji - The emoji to use + */ + setEmoji(emoji) { + this.data.emoji = emojiValidator.parse(emoji); + return this; + } + /** + * Sets whether this button is disabled. + * + * @param disabled - Whether to disable this button + */ + setDisabled(disabled = true) { + this.data.disabled = disabledValidator.parse(disabled); + return this; + } + /** + * Sets the label for this button. + * + * @param label - The label to use + */ + setLabel(label) { + this.data.label = buttonLabelValidator.parse(label); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredButtonParameters( + this.data.style, + this.data.label, + this.data.emoji, + this.data.custom_id, + this.data.url + ); + return { + ...this.data + }; + } +}; + +// src/components/selectMenu/ChannelSelectMenu.ts +import { + ComponentType as ComponentType2, + SelectMenuDefaultValueType +} from "discord-api-types/v10"; + +// src/components/selectMenu/BaseSelectMenu.ts +var BaseSelectMenuBuilder = class extends ComponentBuilder { + static { + __name(this, "BaseSelectMenuBuilder"); + } + /** + * Sets the placeholder for this select menu. + * + * @param placeholder - The placeholder to use + */ + setPlaceholder(placeholder) { + this.data.placeholder = placeholderValidator.parse(placeholder); + return this; + } + /** + * Sets the minimum values that must be selected in the select menu. + * + * @param minValues - The minimum values that must be selected + */ + setMinValues(minValues) { + this.data.min_values = minMaxValidator.parse(minValues); + return this; + } + /** + * Sets the maximum values that must be selected in the select menu. + * + * @param maxValues - The maximum values that must be selected + */ + setMaxValues(maxValues) { + this.data.max_values = minMaxValidator.parse(maxValues); + return this; + } + /** + * Sets the custom id for this select menu. + * + * @param customId - The custom id to use + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets whether this select menu is disabled. + * + * @param disabled - Whether this select menu is disabled + */ + setDisabled(disabled = true) { + this.data.disabled = disabledValidator.parse(disabled); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + customIdValidator.parse(this.data.custom_id); + return { + ...this.data + }; + } +}; + +// src/components/selectMenu/ChannelSelectMenu.ts +var ChannelSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "ChannelSelectMenuBuilder"); + } + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) + * .setMinValues(2); + * ``` + */ + constructor(data) { + super({ ...data, type: ComponentType2.ChannelSelect }); + } + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ + addChannelTypes(...types) { + const normalizedTypes = normalizeArray(types); + this.data.channel_types ??= []; + this.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes)); + return this; + } + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ + setChannelTypes(...types) { + const normalizedTypes = normalizeArray(types); + this.data.channel_types ??= []; + this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes)); + return this; + } + /** + * Adds default channels to this auto populated select menu. + * + * @param channels - The channels to add + */ + addDefaultChannels(...channels) { + const normalizedValues = normalizeArray(channels); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: SelectMenuDefaultValueType.Channel + })) + ); + return this; + } + /** + * Sets default channels to this auto populated select menu. + * + * @param channels - The channels to set + */ + setDefaultChannels(...channels) { + const normalizedValues = normalizeArray(channels); + optionsLengthValidator.parse(normalizedValues.length); + this.data.default_values = normalizedValues.map((id) => ({ + id, + type: SelectMenuDefaultValueType.Channel + })); + return this; + } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON() { + customIdValidator.parse(this.data.custom_id); + return { + ...this.data + }; + } +}; + +// src/components/selectMenu/MentionableSelectMenu.ts +import { + ComponentType as ComponentType3, + SelectMenuDefaultValueType as SelectMenuDefaultValueType2 +} from "discord-api-types/v10"; +var MentionableSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "MentionableSelectMenuBuilder"); + } + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data) { + super({ ...data, type: ComponentType3.MentionableSelect }); + } + /** + * Adds default roles to this auto populated select menu. + * + * @param roles - The roles to add + */ + addDefaultRoles(...roles) { + const normalizedValues = normalizeArray(roles); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: SelectMenuDefaultValueType2.Role + })) + ); + return this; + } + /** + * Adds default users to this auto populated select menu. + * + * @param users - The users to add + */ + addDefaultUsers(...users) { + const normalizedValues = normalizeArray(users); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: SelectMenuDefaultValueType2.User + })) + ); + return this; + } + /** + * Adds default values to this auto populated select menu. + * + * @param values - The values to add + */ + addDefaultValues(...values) { + const normalizedValues = normalizeArray(values); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push(...normalizedValues); + return this; + } + /** + * Sets default values to this auto populated select menu. + * + * @param values - The values to set + */ + setDefaultValues(...values) { + const normalizedValues = normalizeArray(values); + optionsLengthValidator.parse(normalizedValues.length); + this.data.default_values = normalizedValues.slice(); + return this; + } +}; + +// src/components/selectMenu/RoleSelectMenu.ts +import { + ComponentType as ComponentType4, + SelectMenuDefaultValueType as SelectMenuDefaultValueType3 +} from "discord-api-types/v10"; +var RoleSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "RoleSelectMenuBuilder"); + } + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data) { + super({ ...data, type: ComponentType4.RoleSelect }); + } + /** + * Adds default roles to this auto populated select menu. + * + * @param roles - The roles to add + */ + addDefaultRoles(...roles) { + const normalizedValues = normalizeArray(roles); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: SelectMenuDefaultValueType3.Role + })) + ); + return this; + } + /** + * Sets default roles to this auto populated select menu. + * + * @param roles - The roles to set + */ + setDefaultRoles(...roles) { + const normalizedValues = normalizeArray(roles); + optionsLengthValidator.parse(normalizedValues.length); + this.data.default_values = normalizedValues.map((id) => ({ + id, + type: SelectMenuDefaultValueType3.Role + })); + return this; + } +}; + +// src/components/selectMenu/StringSelectMenu.ts +import { ComponentType as ComponentType5 } from "discord-api-types/v10"; +var StringSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "StringSelectMenuBuilder"); + } + /** + * The options within this select menu. + */ + options; + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * options: [ + * { label: 'option 1', value: '1' }, + * { label: 'option 2', value: '2' }, + * { label: 'option 3', value: '3' }, + * ], + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1) + * .addOptions({ + * label: 'Catchy', + * value: 'catch', + * }); + * ``` + */ + constructor(data) { + const { options, ...initData } = data ?? {}; + super({ ...initData, type: ComponentType5.StringSelect }); + this.options = options?.map((option) => new StringSelectMenuOptionBuilder(option)) ?? []; + } + /** + * Adds options to this select menu. + * + * @param options - The options to add + */ + addOptions(...options) { + const normalizedOptions = normalizeArray(options); + optionsLengthValidator.parse(this.options.length + normalizedOptions.length); + this.options.push( + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) + ) + ); + return this; + } + /** + * Sets the options for this select menu. + * + * @param options - The options to set + */ + setOptions(...options) { + return this.spliceOptions(0, this.options.length, ...options); + } + /** + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index, deleteCount, ...options) { + const normalizedOptions = normalizeArray(options); + const clone = [...this.options]; + clone.splice( + index, + deleteCount, + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) + ) + ); + optionsLengthValidator.parse(clone.length); + this.options.splice(0, this.options.length, ...clone); + return this; + } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ + toJSON() { + validateRequiredSelectMenuParameters(this.options, this.data.custom_id); + return { + ...this.data, + options: this.options.map((option) => option.toJSON()) + }; + } +}; + +// src/components/selectMenu/UserSelectMenu.ts +import { + ComponentType as ComponentType6, + SelectMenuDefaultValueType as SelectMenuDefaultValueType4 +} from "discord-api-types/v10"; +var UserSelectMenuBuilder = class extends BaseSelectMenuBuilder { + static { + __name(this, "UserSelectMenuBuilder"); + } + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ + constructor(data) { + super({ ...data, type: ComponentType6.UserSelect }); + } + /** + * Adds default users to this auto populated select menu. + * + * @param users - The users to add + */ + addDefaultUsers(...users) { + const normalizedValues = normalizeArray(users); + optionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length); + this.data.default_values ??= []; + this.data.default_values.push( + ...normalizedValues.map((id) => ({ + id, + type: SelectMenuDefaultValueType4.User + })) + ); + return this; + } + /** + * Sets default users to this auto populated select menu. + * + * @param users - The users to set + */ + setDefaultUsers(...users) { + const normalizedValues = normalizeArray(users); + optionsLengthValidator.parse(normalizedValues.length); + this.data.default_values = normalizedValues.map((id) => ({ + id, + type: SelectMenuDefaultValueType4.User + })); + return this; + } +}; + +// src/components/textInput/TextInput.ts +import { isJSONEncodable } from "@discordjs/util"; +import { ComponentType as ComponentType7 } from "discord-api-types/v10"; +import isEqual from "fast-deep-equal"; + +// src/components/textInput/Assertions.ts +var Assertions_exports3 = {}; +__export(Assertions_exports3, { + labelValidator: () => labelValidator, + maxLengthValidator: () => maxLengthValidator, + minLengthValidator: () => minLengthValidator, + placeholderValidator: () => placeholderValidator2, + requiredValidator: () => requiredValidator, + textInputStyleValidator: () => textInputStyleValidator, + validateRequiredParameters: () => validateRequiredParameters, + valueValidator: () => valueValidator +}); +import { s as s3 } from "@sapphire/shapeshift"; +import { TextInputStyle } from "discord-api-types/v10"; +var textInputStyleValidator = s3.nativeEnum(TextInputStyle); +var minLengthValidator = s3.number.int.greaterThanOrEqual(0).lessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var maxLengthValidator = s3.number.int.greaterThanOrEqual(1).lessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var requiredValidator = s3.boolean; +var valueValidator = s3.string.lengthLessThanOrEqual(4e3).setValidationEnabled(isValidationEnabled); +var placeholderValidator2 = s3.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var labelValidator = s3.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(45).setValidationEnabled(isValidationEnabled); +function validateRequiredParameters(customId, style, label) { + customIdValidator.parse(customId); + textInputStyleValidator.parse(style); + labelValidator.parse(label); +} +__name(validateRequiredParameters, "validateRequiredParameters"); + +// src/components/textInput/TextInput.ts +var TextInputBuilder = class extends ComponentBuilder { + static { + __name(this, "TextInputBuilder"); + } + /** + * Creates a new text input from API data. + * + * @param data - The API data to create this text input with + * @example + * Creating a select menu option from an API data object: + * ```ts + * const textInput = new TextInputBuilder({ + * custom_id: 'a cool select menu', + * label: 'Type something', + * style: TextInputStyle.Short, + * }); + * ``` + * @example + * Creating a select menu option using setters and API data: + * ```ts + * const textInput = new TextInputBuilder({ + * label: 'Type something else', + * }) + * .setCustomId('woah') + * .setStyle(TextInputStyle.Paragraph); + * ``` + */ + constructor(data) { + super({ type: ComponentType7.TextInput, ...data }); + } + /** + * Sets the custom id for this text input. + * + * @param customId - The custom id to use + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Sets the label for this text input. + * + * @param label - The label to use + */ + setLabel(label) { + this.data.label = labelValidator.parse(label); + return this; + } + /** + * Sets the style for this text input. + * + * @param style - The style to use + */ + setStyle(style) { + this.data.style = textInputStyleValidator.parse(style); + return this; + } + /** + * Sets the minimum length of text for this text input. + * + * @param minLength - The minimum length of text for this text input + */ + setMinLength(minLength) { + this.data.min_length = minLengthValidator.parse(minLength); + return this; + } + /** + * Sets the maximum length of text for this text input. + * + * @param maxLength - The maximum length of text for this text input + */ + setMaxLength(maxLength) { + this.data.max_length = maxLengthValidator.parse(maxLength); + return this; + } + /** + * Sets the placeholder for this text input. + * + * @param placeholder - The placeholder to use + */ + setPlaceholder(placeholder) { + this.data.placeholder = placeholderValidator2.parse(placeholder); + return this; + } + /** + * Sets the value for this text input. + * + * @param value - The value to use + */ + setValue(value) { + this.data.value = valueValidator.parse(value); + return this; + } + /** + * Sets whether this text input is required. + * + * @param required - Whether this text input is required + */ + setRequired(required = true) { + this.data.required = requiredValidator.parse(required); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label); + return { + ...this.data + }; + } + /** + * {@inheritDoc Equatable.equals} + */ + equals(other) { + if (isJSONEncodable(other)) { + return isEqual(other.toJSON(), this.data); + } + return isEqual(other, this.data); + } +}; + +// src/components/Components.ts +function createComponentBuilder(data) { + if (data instanceof ComponentBuilder) { + return data; + } + switch (data.type) { + case ComponentType8.ActionRow: + return new ActionRowBuilder(data); + case ComponentType8.Button: + return new ButtonBuilder(data); + case ComponentType8.StringSelect: + return new StringSelectMenuBuilder(data); + case ComponentType8.TextInput: + return new TextInputBuilder(data); + case ComponentType8.UserSelect: + return new UserSelectMenuBuilder(data); + case ComponentType8.RoleSelect: + return new RoleSelectMenuBuilder(data); + case ComponentType8.MentionableSelect: + return new MentionableSelectMenuBuilder(data); + case ComponentType8.ChannelSelect: + return new ChannelSelectMenuBuilder(data); + default: + throw new Error(`Cannot properly serialize component type: ${data.type}`); + } +} +__name(createComponentBuilder, "createComponentBuilder"); + +// src/components/ActionRow.ts +var ActionRowBuilder = class extends ComponentBuilder { + static { + __name(this, "ActionRowBuilder"); + } + /** + * The components within this action row. + */ + components; + /** + * Creates a new action row from API data. + * + * @param data - The API data to create this action row with + * @example + * Creating an action row from an API data object: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Type something", + * style: TextInputStyle.Short, + * type: ComponentType.TextInput, + * }, + * ], + * }); + * ``` + * @example + * Creating an action row using setters and API data: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Click me", + * style: ButtonStyle.Primary, + * type: ComponentType.Button, + * }, + * ], + * }) + * .addComponents(button2, button3); + * ``` + */ + constructor({ components, ...data } = {}) { + super({ type: ComponentType9.ActionRow, ...data }); + this.components = components?.map((component) => createComponentBuilder(component)) ?? []; + } + /** + * Adds components to this action row. + * + * @param components - The components to add + */ + addComponents(...components) { + this.components.push(...normalizeArray(components)); + return this; + } + /** + * Sets components for this action row. + * + * @param components - The components to set + */ + setComponents(...components) { + this.components.splice(0, this.components.length, ...normalizeArray(components)); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + return { + ...this.data, + components: this.components.map((component) => component.toJSON()) + }; + } +}; + +// src/interactions/modals/Assertions.ts +var Assertions_exports4 = {}; +__export(Assertions_exports4, { + componentsValidator: () => componentsValidator, + titleValidator: () => titleValidator, + validateRequiredParameters: () => validateRequiredParameters2 +}); +import { s as s4 } from "@sapphire/shapeshift"; +var titleValidator = s4.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(45).setValidationEnabled(isValidationEnabled); +var componentsValidator = s4.instance(ActionRowBuilder).array.lengthGreaterThanOrEqual(1).setValidationEnabled(isValidationEnabled); +function validateRequiredParameters2(customId, title, components) { + customIdValidator.parse(customId); + titleValidator.parse(title); + componentsValidator.parse(components); +} +__name(validateRequiredParameters2, "validateRequiredParameters"); + +// src/interactions/modals/Modal.ts +var ModalBuilder = class { + static { + __name(this, "ModalBuilder"); + } + /** + * The API data associated with this modal. + */ + data; + /** + * The components within this modal. + */ + components = []; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ + constructor({ components, ...data } = {}) { + this.data = { ...data }; + this.components = components?.map((component) => createComponentBuilder(component)) ?? []; + } + /** + * Sets the title of this modal. + * + * @param title - The title to use + */ + setTitle(title) { + this.data.title = titleValidator.parse(title); + return this; + } + /** + * Sets the custom id of this modal. + * + * @param customId - The custom id to use + */ + setCustomId(customId) { + this.data.custom_id = customIdValidator.parse(customId); + return this; + } + /** + * Adds components to this modal. + * + * @param components - The components to add + */ + addComponents(...components) { + this.components.push( + ...normalizeArray(components).map( + (component) => component instanceof ActionRowBuilder ? component : new ActionRowBuilder(component) + ) + ); + return this; + } + /** + * Sets components for this modal. + * + * @param components - The components to set + */ + setComponents(...components) { + this.components.splice(0, this.components.length, ...normalizeArray(components)); + return this; + } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ + toJSON() { + validateRequiredParameters2(this.data.custom_id, this.data.title, this.components); + return { + ...this.data, + components: this.components.map((component) => component.toJSON()) + }; + } +}; + +// src/interactions/slashCommands/Assertions.ts +var Assertions_exports5 = {}; +__export(Assertions_exports5, { + assertReturnOfBuilder: () => assertReturnOfBuilder, + localizationMapPredicate: () => localizationMapPredicate, + validateChoicesLength: () => validateChoicesLength, + validateDMPermission: () => validateDMPermission, + validateDefaultMemberPermissions: () => validateDefaultMemberPermissions, + validateDefaultPermission: () => validateDefaultPermission, + validateDescription: () => validateDescription, + validateLocale: () => validateLocale, + validateLocalizationMap: () => validateLocalizationMap, + validateMaxOptionsLength: () => validateMaxOptionsLength, + validateNSFW: () => validateNSFW, + validateName: () => validateName, + validateRequired: () => validateRequired, + validateRequiredParameters: () => validateRequiredParameters3 +}); +import { s as s5 } from "@sapphire/shapeshift"; +import { Locale } from "discord-api-types/v10"; +var namePredicate = s5.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(32).regex(/^[\p{Ll}\p{Lm}\p{Lo}\p{N}\p{sc=Devanagari}\p{sc=Thai}_-]+$/u).setValidationEnabled(isValidationEnabled); +function validateName(name) { + namePredicate.parse(name); +} +__name(validateName, "validateName"); +var descriptionPredicate2 = s5.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled); +var localePredicate = s5.nativeEnum(Locale); +function validateDescription(description) { + descriptionPredicate2.parse(description); +} +__name(validateDescription, "validateDescription"); +var maxArrayLengthPredicate = s5.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateLocale(locale) { + return localePredicate.parse(locale); +} +__name(validateLocale, "validateLocale"); +function validateMaxOptionsLength(options) { + maxArrayLengthPredicate.parse(options); +} +__name(validateMaxOptionsLength, "validateMaxOptionsLength"); +function validateRequiredParameters3(name, description, options) { + validateName(name); + validateDescription(description); + validateMaxOptionsLength(options); +} +__name(validateRequiredParameters3, "validateRequiredParameters"); +var booleanPredicate = s5.boolean; +function validateDefaultPermission(value) { + booleanPredicate.parse(value); +} +__name(validateDefaultPermission, "validateDefaultPermission"); +function validateRequired(required) { + booleanPredicate.parse(required); +} +__name(validateRequired, "validateRequired"); +var choicesLengthPredicate = s5.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled); +function validateChoicesLength(amountAdding, choices) { + choicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding); +} +__name(validateChoicesLength, "validateChoicesLength"); +function assertReturnOfBuilder(input, ExpectedInstanceOf) { + s5.instance(ExpectedInstanceOf).parse(input); +} +__name(assertReturnOfBuilder, "assertReturnOfBuilder"); +var localizationMapPredicate = s5.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s5.string.nullish]))).strict.nullish.setValidationEnabled(isValidationEnabled); +function validateLocalizationMap(value) { + localizationMapPredicate.parse(value); +} +__name(validateLocalizationMap, "validateLocalizationMap"); +var dmPermissionPredicate = s5.boolean.nullish; +function validateDMPermission(value) { + dmPermissionPredicate.parse(value); +} +__name(validateDMPermission, "validateDMPermission"); +var memberPermissionPredicate = s5.union( + s5.bigint.transform((value) => value.toString()), + s5.number.safeInt.transform((value) => value.toString()), + s5.string.regex(/^\d+$/) +).nullish; +function validateDefaultMemberPermissions(permissions) { + return memberPermissionPredicate.parse(permissions); +} +__name(validateDefaultMemberPermissions, "validateDefaultMemberPermissions"); +function validateNSFW(value) { + booleanPredicate.parse(value); +} +__name(validateNSFW, "validateNSFW"); + +// src/interactions/slashCommands/SlashCommandBuilder.ts +import { mix as mix6 } from "ts-mixer"; + +// src/interactions/slashCommands/SlashCommandSubcommands.ts +import { + ApplicationCommandOptionType as ApplicationCommandOptionType11 +} from "discord-api-types/v10"; +import { mix as mix5 } from "ts-mixer"; + +// src/interactions/slashCommands/mixins/NameAndDescription.ts +var SharedNameAndDescription = class { + static { + __name(this, "SharedNameAndDescription"); + } + /** + * The name of this command. + */ + name; + /** + * The name localizations of this command. + */ + name_localizations; + /** + * The description of this command. + */ + description; + /** + * The description localizations of this command. + */ + description_localizations; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ + setName(name) { + validateName(name); + Reflect.set(this, "name", name); + return this; + } + /** + * Sets the description of this command. + * + * @param description - The description to use + */ + setDescription(description) { + validateDescription(description); + Reflect.set(this, "description", description); + return this; + } + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ + setNameLocalization(locale, localizedName) { + if (!this.name_localizations) { + Reflect.set(this, "name_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedName === null) { + this.name_localizations[parsedLocale] = null; + return this; + } + validateName(localizedName); + this.name_localizations[parsedLocale] = localizedName; + return this; + } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ + setNameLocalizations(localizedNames) { + if (localizedNames === null) { + Reflect.set(this, "name_localizations", null); + return this; + } + Reflect.set(this, "name_localizations", {}); + for (const args of Object.entries(localizedNames)) { + this.setNameLocalization(...args); + } + return this; + } + /** + * Sets a description localization for this command. + * + * @param locale - The locale to set + * @param localizedDescription - The localized description for the given locale + */ + setDescriptionLocalization(locale, localizedDescription) { + if (!this.description_localizations) { + Reflect.set(this, "description_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedDescription === null) { + this.description_localizations[parsedLocale] = null; + return this; + } + validateDescription(localizedDescription); + this.description_localizations[parsedLocale] = localizedDescription; + return this; + } + /** + * Sets the description localizations for this command. + * + * @param localizedDescriptions - The object of localized descriptions to set + */ + setDescriptionLocalizations(localizedDescriptions) { + if (localizedDescriptions === null) { + Reflect.set(this, "description_localizations", null); + return this; + } + Reflect.set(this, "description_localizations", {}); + for (const args of Object.entries(localizedDescriptions)) { + this.setDescriptionLocalization(...args); + } + return this; + } +}; + +// src/interactions/slashCommands/options/attachment.ts +import { ApplicationCommandOptionType } from "discord-api-types/v10"; + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts +var ApplicationCommandOptionBase = class extends SharedNameAndDescription { + static { + __name(this, "ApplicationCommandOptionBase"); + } + /** + * Whether this option is required. + * + * @defaultValue `false` + */ + required = false; + /** + * Sets whether this option is required. + * + * @param required - Whether this option should be required + */ + setRequired(required) { + validateRequired(required); + Reflect.set(this, "required", required); + return this; + } + /** + * This method runs required validators on this builder. + */ + runRequiredValidations() { + validateRequiredParameters3(this.name, this.description, []); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + validateRequired(this.required); + } +}; + +// src/interactions/slashCommands/options/attachment.ts +var SlashCommandAttachmentOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandAttachmentOption"); + } + /** + * The type of this option. + */ + type = ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/options/boolean.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType2 } from "discord-api-types/v10"; +var SlashCommandBooleanOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandBooleanOption"); + } + /** + * The type of this option. + */ + type = ApplicationCommandOptionType2.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/options/channel.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType3 } from "discord-api-types/v10"; +import { mix } from "ts-mixer"; + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts +import { s as s6 } from "@sapphire/shapeshift"; +import { ChannelType as ChannelType2 } from "discord-api-types/v10"; +var allowedChannelTypes = [ + ChannelType2.GuildText, + ChannelType2.GuildVoice, + ChannelType2.GuildCategory, + ChannelType2.GuildAnnouncement, + ChannelType2.AnnouncementThread, + ChannelType2.PublicThread, + ChannelType2.PrivateThread, + ChannelType2.GuildStageVoice, + ChannelType2.GuildForum, + ChannelType2.GuildMedia +]; +var channelTypesPredicate = s6.array(s6.union(...allowedChannelTypes.map((type) => s6.literal(type)))); +var ApplicationCommandOptionChannelTypesMixin = class { + static { + __name(this, "ApplicationCommandOptionChannelTypesMixin"); + } + /** + * The channel types of this option. + */ + channel_types; + /** + * Adds channel types to this option. + * + * @param channelTypes - The channel types + */ + addChannelTypes(...channelTypes) { + if (this.channel_types === void 0) { + Reflect.set(this, "channel_types", []); + } + this.channel_types.push(...channelTypesPredicate.parse(channelTypes)); + return this; + } +}; + +// src/interactions/slashCommands/options/channel.ts +var SlashCommandChannelOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + type = ApplicationCommandOptionType3.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; +__name(SlashCommandChannelOption, "SlashCommandChannelOption"); +SlashCommandChannelOption = __decorateClass([ + mix(ApplicationCommandOptionChannelTypesMixin) +], SlashCommandChannelOption); + +// src/interactions/slashCommands/options/integer.ts +import { s as s8 } from "@sapphire/shapeshift"; +import { ApplicationCommandOptionType as ApplicationCommandOptionType5 } from "discord-api-types/v10"; +import { mix as mix2 } from "ts-mixer"; + +// src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts +var ApplicationCommandNumericOptionMinMaxValueMixin = class { + static { + __name(this, "ApplicationCommandNumericOptionMinMaxValueMixin"); + } + /** + * The maximum value of this option. + */ + max_value; + /** + * The minimum value of this option. + */ + min_value; +}; + +// src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts +import { s as s7 } from "@sapphire/shapeshift"; +import { ApplicationCommandOptionType as ApplicationCommandOptionType4 } from "discord-api-types/v10"; +var stringPredicate = s7.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100); +var numberPredicate = s7.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY); +var choicesPredicate = s7.object({ + name: stringPredicate, + name_localizations: localizationMapPredicate, + value: s7.union(stringPredicate, numberPredicate) +}).array; +var booleanPredicate2 = s7.boolean; +var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { + static { + __name(this, "ApplicationCommandOptionWithChoicesAndAutocompleteMixin"); + } + /** + * The choices of this option. + */ + choices; + /** + * Whether this option utilizes autocomplete. + */ + autocomplete; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ + type; + /** + * Adds multiple choices to this option. + * + * @param choices - The choices to add + */ + addChoices(...choices) { + if (choices.length > 0 && this.autocomplete) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + choicesPredicate.parse(choices); + if (this.choices === void 0) { + Reflect.set(this, "choices", []); + } + validateChoicesLength(choices.length, this.choices); + for (const { name, name_localizations, value } of choices) { + if (this.type === ApplicationCommandOptionType4.String) { + stringPredicate.parse(value); + } else { + numberPredicate.parse(value); + } + this.choices.push({ name, name_localizations, value }); + } + return this; + } + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ + setChoices(...choices) { + if (choices.length > 0 && this.autocomplete) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + choicesPredicate.parse(choices); + Reflect.set(this, "choices", []); + this.addChoices(...choices); + return this; + } + /** + * Whether this option uses autocomplete. + * + * @param autocomplete - Whether this option should use autocomplete + */ + setAutocomplete(autocomplete) { + booleanPredicate2.parse(autocomplete); + if (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + Reflect.set(this, "autocomplete", autocomplete); + return this; + } +}; + +// src/interactions/slashCommands/options/integer.ts +var numberValidator = s8.number.int; +var SlashCommandIntegerOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + type = ApplicationCommandOptionType5.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max) { + numberValidator.parse(max); + Reflect.set(this, "max_value", max); + return this; + } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min) { + numberValidator.parse(min); + Reflect.set(this, "min_value", min); + return this; + } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { ...this }; + } +}; +__name(SlashCommandIntegerOption, "SlashCommandIntegerOption"); +SlashCommandIntegerOption = __decorateClass([ + mix2(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandIntegerOption); + +// src/interactions/slashCommands/options/mentionable.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType6 } from "discord-api-types/v10"; +var SlashCommandMentionableOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandMentionableOption"); + } + /** + * The type of this option. + */ + type = ApplicationCommandOptionType6.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/options/number.ts +import { s as s9 } from "@sapphire/shapeshift"; +import { ApplicationCommandOptionType as ApplicationCommandOptionType7 } from "discord-api-types/v10"; +import { mix as mix3 } from "ts-mixer"; +var numberValidator2 = s9.number; +var SlashCommandNumberOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + type = ApplicationCommandOptionType7.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ + setMaxValue(max) { + numberValidator2.parse(max); + Reflect.set(this, "max_value", max); + return this; + } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ + setMinValue(min) { + numberValidator2.parse(min); + Reflect.set(this, "min_value", min); + return this; + } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { ...this }; + } +}; +__name(SlashCommandNumberOption, "SlashCommandNumberOption"); +SlashCommandNumberOption = __decorateClass([ + mix3(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandNumberOption); + +// src/interactions/slashCommands/options/role.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType8 } from "discord-api-types/v10"; +var SlashCommandRoleOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandRoleOption"); + } + /** + * The type of this option. + */ + type = ApplicationCommandOptionType8.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/options/string.ts +import { s as s10 } from "@sapphire/shapeshift"; +import { ApplicationCommandOptionType as ApplicationCommandOptionType9 } from "discord-api-types/v10"; +import { mix as mix4 } from "ts-mixer"; +var minLengthValidator2 = s10.number.greaterThanOrEqual(0).lessThanOrEqual(6e3); +var maxLengthValidator2 = s10.number.greaterThanOrEqual(1).lessThanOrEqual(6e3); +var SlashCommandStringOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ + type = ApplicationCommandOptionType9.String; + /** + * The maximum length of this option. + */ + max_length; + /** + * The minimum length of this option. + */ + min_length; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ + setMaxLength(max) { + maxLengthValidator2.parse(max); + Reflect.set(this, "max_length", max); + return this; + } + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ + setMinLength(min) { + minLengthValidator2.parse(min); + Reflect.set(this, "min_length", min); + return this; + } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { + throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); + } + return { ...this }; + } +}; +__name(SlashCommandStringOption, "SlashCommandStringOption"); +SlashCommandStringOption = __decorateClass([ + mix4(ApplicationCommandOptionWithChoicesAndAutocompleteMixin) +], SlashCommandStringOption); + +// src/interactions/slashCommands/options/user.ts +import { ApplicationCommandOptionType as ApplicationCommandOptionType10 } from "discord-api-types/v10"; +var SlashCommandUserOption = class extends ApplicationCommandOptionBase { + static { + __name(this, "SlashCommandUserOption"); + } + /** + * The type of this option. + */ + type = ApplicationCommandOptionType10.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ + toJSON() { + this.runRequiredValidations(); + return { ...this }; + } +}; + +// src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts +var SharedSlashCommandOptions = class { + static { + __name(this, "SharedSlashCommandOptions"); + } + options; + /** + * Adds a boolean option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addBooleanOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandBooleanOption); + } + /** + * Adds a user option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addUserOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandUserOption); + } + /** + * Adds a channel option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addChannelOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandChannelOption); + } + /** + * Adds a role option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addRoleOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandRoleOption); + } + /** + * Adds an attachment option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addAttachmentOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandAttachmentOption); + } + /** + * Adds a mentionable option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addMentionableOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandMentionableOption); + } + /** + * Adds a string option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addStringOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandStringOption); + } + /** + * Adds an integer option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addIntegerOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandIntegerOption); + } + /** + * Adds a number option. + * + * @param input - A function that returns an option builder or an already built builder + */ + addNumberOption(input) { + return this._sharedAddOptionMethod(input, SlashCommandNumberOption); + } + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ + _sharedAddOptionMethod(input, Instance) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new Instance()) : input; + assertReturnOfBuilder(result, Instance); + options.push(result); + return this; + } +}; + +// src/interactions/slashCommands/SlashCommandSubcommands.ts +var SlashCommandSubcommandGroupBuilder = class { + /** + * The name of this subcommand group. + */ + name = void 0; + /** + * The description of this subcommand group. + */ + description = void 0; + /** + * The subcommands within this subcommand group. + */ + options = []; + /** + * Adds a new subcommand to this group. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ + addSubcommand(input) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new SlashCommandSubcommandBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandBuilder); + options.push(result); + return this; + } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + return { + type: ApplicationCommandOptionType11.SubcommandGroup, + name: this.name, + name_localizations: this.name_localizations, + description: this.description, + description_localizations: this.description_localizations, + options: this.options.map((option) => option.toJSON()) + }; + } +}; +__name(SlashCommandSubcommandGroupBuilder, "SlashCommandSubcommandGroupBuilder"); +SlashCommandSubcommandGroupBuilder = __decorateClass([ + mix5(SharedNameAndDescription) +], SlashCommandSubcommandGroupBuilder); +var SlashCommandSubcommandBuilder = class { + /** + * The name of this subcommand. + */ + name = void 0; + /** + * The description of this subcommand. + */ + description = void 0; + /** + * The options within this subcommand. + */ + options = []; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + return { + type: ApplicationCommandOptionType11.Subcommand, + name: this.name, + name_localizations: this.name_localizations, + description: this.description, + description_localizations: this.description_localizations, + options: this.options.map((option) => option.toJSON()) + }; + } +}; +__name(SlashCommandSubcommandBuilder, "SlashCommandSubcommandBuilder"); +SlashCommandSubcommandBuilder = __decorateClass([ + mix5(SharedNameAndDescription, SharedSlashCommandOptions) +], SlashCommandSubcommandBuilder); + +// src/interactions/slashCommands/SlashCommandBuilder.ts +var SlashCommandBuilder = class { + /** + * The name of this command. + */ + name = void 0; + /** + * The name localizations of this command. + */ + name_localizations; + /** + * The description of this command. + */ + description = void 0; + /** + * The description localizations of this command. + */ + description_localizations; + /** + * The options of this command. + */ + options = []; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ + default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + dm_permission = void 0; + /** + * Whether this command is NSFW. + */ + nsfw = void 0; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether or not to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. + */ + setDefaultPermission(value) { + validateDefaultPermission(value); + Reflect.set(this, "default_permission", value); + return this; + } + /** + * Sets the default permissions a member should have in order to run the command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDefaultMemberPermissions(permissions) { + const permissionValue = validateDefaultMemberPermissions(permissions); + Reflect.set(this, "default_member_permissions", permissionValue); + return this; + } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDMPermission(enabled) { + validateDMPermission(enabled); + Reflect.set(this, "dm_permission", enabled); + return this; + } + /** + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw = true) { + validateNSFW(nsfw); + Reflect.set(this, "nsfw", nsfw); + return this; + } + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder + */ + addSubcommandGroup(input) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new SlashCommandSubcommandGroupBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder); + options.push(result); + return this; + } + /** + * Adds a new subcommand to this command. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ + addSubcommand(input) { + const { options } = this; + validateMaxOptionsLength(options); + const result = typeof input === "function" ? input(new SlashCommandSubcommandBuilder()) : input; + assertReturnOfBuilder(result, SlashCommandSubcommandBuilder); + options.push(result); + return this; + } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + return { + ...this, + options: this.options.map((option) => option.toJSON()) + }; + } +}; +__name(SlashCommandBuilder, "SlashCommandBuilder"); +SlashCommandBuilder = __decorateClass([ + mix6(SharedSlashCommandOptions, SharedNameAndDescription) +], SlashCommandBuilder); + +// src/interactions/contextMenuCommands/Assertions.ts +var Assertions_exports6 = {}; +__export(Assertions_exports6, { + validateDMPermission: () => validateDMPermission2, + validateDefaultMemberPermissions: () => validateDefaultMemberPermissions2, + validateDefaultPermission: () => validateDefaultPermission2, + validateName: () => validateName2, + validateRequiredParameters: () => validateRequiredParameters4, + validateType: () => validateType +}); +import { s as s11 } from "@sapphire/shapeshift"; +import { ApplicationCommandType } from "discord-api-types/v10"; +var namePredicate2 = s11.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(32).regex(/^( *[\p{P}\p{L}\p{N}\p{sc=Devanagari}\p{sc=Thai}]+ *)+$/u).setValidationEnabled(isValidationEnabled); +var typePredicate = s11.union(s11.literal(ApplicationCommandType.User), s11.literal(ApplicationCommandType.Message)).setValidationEnabled(isValidationEnabled); +var booleanPredicate3 = s11.boolean; +function validateDefaultPermission2(value) { + booleanPredicate3.parse(value); +} +__name(validateDefaultPermission2, "validateDefaultPermission"); +function validateName2(name) { + namePredicate2.parse(name); +} +__name(validateName2, "validateName"); +function validateType(type) { + typePredicate.parse(type); +} +__name(validateType, "validateType"); +function validateRequiredParameters4(name, type) { + validateName2(name); + validateType(type); +} +__name(validateRequiredParameters4, "validateRequiredParameters"); +var dmPermissionPredicate2 = s11.boolean.nullish; +function validateDMPermission2(value) { + dmPermissionPredicate2.parse(value); +} +__name(validateDMPermission2, "validateDMPermission"); +var memberPermissionPredicate2 = s11.union( + s11.bigint.transform((value) => value.toString()), + s11.number.safeInt.transform((value) => value.toString()), + s11.string.regex(/^\d+$/) +).nullish; +function validateDefaultMemberPermissions2(permissions) { + return memberPermissionPredicate2.parse(permissions); +} +__name(validateDefaultMemberPermissions2, "validateDefaultMemberPermissions"); + +// src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts +var ContextMenuCommandBuilder = class { + static { + __name(this, "ContextMenuCommandBuilder"); + } + /** + * The name of this command. + */ + name = void 0; + /** + * The name localizations of this command. + */ + name_localizations; + /** + * The type of this command. + */ + type = void 0; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ + default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ + dm_permission = void 0; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ + setName(name) { + validateName2(name); + Reflect.set(this, "name", name); + return this; + } + /** + * Sets the type of this command. + * + * @param type - The type to use + */ + setType(type) { + validateType(type); + Reflect.set(this, "type", type); + return this; + } + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ + setDefaultPermission(value) { + validateDefaultPermission2(value); + Reflect.set(this, "default_permission", value); + return this; + } + /** + * Sets the default permissions a member should have in order to run this command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDefaultMemberPermissions(permissions) { + const permissionValue = validateDefaultMemberPermissions2(permissions); + Reflect.set(this, "default_member_permissions", permissionValue); + return this; + } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ + setDMPermission(enabled) { + validateDMPermission2(enabled); + Reflect.set(this, "dm_permission", enabled); + return this; + } + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ + setNameLocalization(locale, localizedName) { + if (!this.name_localizations) { + Reflect.set(this, "name_localizations", {}); + } + const parsedLocale = validateLocale(locale); + if (localizedName === null) { + this.name_localizations[parsedLocale] = null; + return this; + } + validateName2(localizedName); + this.name_localizations[parsedLocale] = localizedName; + return this; + } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ + setNameLocalizations(localizedNames) { + if (localizedNames === null) { + Reflect.set(this, "name_localizations", null); + return this; + } + Reflect.set(this, "name_localizations", {}); + for (const args of Object.entries(localizedNames)) + this.setNameLocalization(...args); + return this; + } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters4(this.name, this.type); + validateLocalizationMap(this.name_localizations); + return { ...this }; + } +}; + +// src/util/componentUtil.ts +function embedLength(data) { + return (data.title?.length ?? 0) + (data.description?.length ?? 0) + (data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) + (data.footer?.text.length ?? 0) + (data.author?.name.length ?? 0); +} +__name(embedLength, "embedLength"); + +// src/index.ts +var version = "1.7.0"; +export { + ActionRowBuilder, + ApplicationCommandNumericOptionMinMaxValueMixin, + ApplicationCommandOptionBase, + ApplicationCommandOptionChannelTypesMixin, + ApplicationCommandOptionWithChoicesAndAutocompleteMixin, + BaseSelectMenuBuilder, + ButtonBuilder, + ChannelSelectMenuBuilder, + Assertions_exports2 as ComponentAssertions, + ComponentBuilder, + Assertions_exports6 as ContextMenuCommandAssertions, + ContextMenuCommandBuilder, + Assertions_exports as EmbedAssertions, + EmbedBuilder, + MentionableSelectMenuBuilder, + Assertions_exports4 as ModalAssertions, + ModalBuilder, + RoleSelectMenuBuilder, + StringSelectMenuBuilder as SelectMenuBuilder, + StringSelectMenuOptionBuilder as SelectMenuOptionBuilder, + SharedNameAndDescription, + SharedSlashCommandOptions, + Assertions_exports5 as SlashCommandAssertions, + SlashCommandAttachmentOption, + SlashCommandBooleanOption, + SlashCommandBuilder, + SlashCommandChannelOption, + SlashCommandIntegerOption, + SlashCommandMentionableOption, + SlashCommandNumberOption, + SlashCommandRoleOption, + SlashCommandStringOption, + SlashCommandSubcommandBuilder, + SlashCommandSubcommandGroupBuilder, + SlashCommandUserOption, + StringSelectMenuBuilder, + StringSelectMenuOptionBuilder, + Assertions_exports3 as TextInputAssertions, + TextInputBuilder, + UserSelectMenuBuilder, + createComponentBuilder, + disableValidators, + embedLength, + enableValidators, + isValidationEnabled, + normalizeArray, + version +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.mjs.map b/node_modules/@discordjs/builders/dist/index.mjs.map new file mode 100644 index 0000000..41f5954 --- /dev/null +++ b/node_modules/@discordjs/builders/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/index.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts"],"sourcesContent":["import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\n/**\n * Enables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function enableValidators() {\n\treturn (validate = true);\n}\n\n/**\n * Disables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function disableValidators() {\n\treturn (validate = false);\n}\n\n/**\n * Checks whether validation is occurring.\n */\nexport function isValidationEnabled() {\n\treturn validate;\n}\n","/**\n * Normalizes data that is a rest parameter or an array into an array with a depth of 1.\n *\n * @typeParam ItemType - The data that must satisfy {@link RestOrArray}.\n * @param arr - The (possibly variadic) data to normalize\n */\nexport function normalizeArray(arr: RestOrArray): ItemType[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as ItemType[];\n}\n\n/**\n * Represents data that may be an array or came from a rest parameter.\n *\n * @remarks\n * This type is used throughout builders to ensure both an array and variadic arguments\n * may be used. It is normalized with {@link normalizeArray}.\n */\nexport type RestOrArray = Type[] | [Type[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\n/**\n * A tuple satisfying the RGB color model.\n *\n * @see {@link https://developer.mozilla.org/docs/Glossary/RGB}\n */\nexport type RGBTuple = [red: number, green: number, blue: number];\n\n/**\n * The base icon data typically used in payloads.\n */\nexport interface IconData {\n\t/**\n\t * The URL of the icon.\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon.\n\t */\n\tproxyIconURL?: string;\n}\n\n/**\n * Represents the author data of an embed.\n */\nexport type EmbedAuthorData = IconData & Omit;\n\n/**\n * Represents the author options of an embed.\n */\nexport type EmbedAuthorOptions = Omit;\n\n/**\n * Represents the footer data of an embed.\n */\nexport type EmbedFooterData = IconData & Omit;\n\n/**\n * Represents the footer options of an embed.\n */\nexport type EmbedFooterOptions = Omit;\n\n/**\n * Represents the image data of an embed.\n */\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image.\n\t */\n\tproxyURL?: string;\n}\n\n/**\n * A builder that creates API-compatible JSON data for embeds.\n */\nexport class EmbedBuilder {\n\t/**\n\t * The API data associated with this embed.\n\t */\n\tpublic readonly data: APIEmbed;\n\n\t/**\n\t * Creates a new embed from API data.\n\t *\n\t * @param data - The API data to create this embed with\n\t */\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed.\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array:\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic):\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\tconst normalizedFields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(normalizedFields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(normalizedFields);\n\n\t\tif (this.data.fields) this.data.fields.push(...normalizedFields);\n\t\telse this.data.fields = normalizedFields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields for this embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field:\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields:\n\t * ```ts\n\t * const n = 4;\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field:\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the fields for this embed.\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed.\n\t *\n\t * @param options - The options to use\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed.\n\t *\n\t * @param color - The color to use\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed.\n\t *\n\t * @param options - The footer to use\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed.\n\t *\n\t * @param url - The image URL to use\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed.\n\t *\n\t * @param url - The thumbnail URL to use\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed.\n\t *\n\t * @param timestamp - The timestamp or date to use\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title for this embed.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed.\n\t *\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\n// TODO: Consider removing this dep in the next major version\nexport * from '@discordjs/formatters';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version\n * that you are currently using.\n *\n * @privateRemarks This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild.\n */\nexport const version = '1.7.0' as string;\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menu options.\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data.\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah');\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label for this option.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this option.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description for this option.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default.\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display for this option.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * The builders that may be used for messages.\n */\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\n\n/**\n * The builders that may be used for modals.\n */\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\n\n/**\n * The builders that may be used within an action row for messages.\n */\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\n\n/**\n * The builders that may be used within an action row for modals.\n */\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\n\n/**\n * Any builder.\n */\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * A builder that creates API-compatible JSON data for action rows.\n *\n * @typeParam ComponentType - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row.\n\t */\n\tpublic readonly components: ComponentType[];\n\n\t/**\n\t * Creates a new action row from API data.\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as ComponentType[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this action row.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\n/**\n * Any action row component data represented as an object.\n */\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * The base component builder that contains common symbols for all sorts of components.\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\t/**\n\t * Constructs a new kind of component.\n\t *\n\t * @param data - The data to construct a component out of\n\t */\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * Components here are mapped to their respective builder.\n */\nexport interface MappedComponentTypes {\n\t/**\n\t * The action row component type is associated with an {@link ActionRowBuilder}.\n\t */\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t/**\n\t * The button component type is associated with an {@link ButtonBuilder}.\n\t */\n\t[ComponentType.Button]: ButtonBuilder;\n\t/**\n\t * The string select component type is associated with an {@link StringSelectMenuBuilder}.\n\t */\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t/**\n\t * The text inpiut component type is associated with an {@link TextInputBuilder}.\n\t */\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t/**\n\t * The user select component type is associated with an {@link UserSelectMenuBuilder}.\n\t */\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t/**\n\t * The role select component type is associated with an {@link RoleSelectMenuBuilder}.\n\t */\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t/**\n\t * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}.\n\t */\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t/**\n\t * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}.\n\t */\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam ComponentType - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-constituents\n\tdata: (APIModalComponent | APIMessageComponent) & { type: ComponentType },\n): MappedComponentTypes[ComponentType];\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam ComponentBuilder - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(\n\tdata: ComponentBuilder,\n): ComponentBuilder;\n\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * A builder that creates API-compatible JSON data for buttons.\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data.\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: '🙂' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button.\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`.\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button.\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled.\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import {\n\ttype APIChannelSelectComponent,\n\ttype ChannelType,\n\ttype Snowflake,\n\tComponentType,\n\tSelectMenuDefaultValueType,\n} from 'discord-api-types/v10';\nimport { type RestOrArray, normalizeArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator, optionsLengthValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for channel select menus.\n */\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\t/**\n\t * Adds channel types to this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets channel types for this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds default channels to this auto populated select menu.\n\t *\n\t * @param channels - The channels to add\n\t */\n\tpublic addDefaultChannels(...channels: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(channels);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.Channel as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets default channels to this auto populated select menu.\n\t *\n\t * @param channels - The channels to set\n\t */\n\tpublic setDefaultChannels(...channels: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(channels);\n\t\toptionsLengthValidator.parse(normalizedValues.length);\n\n\t\tthis.data.default_values = normalizedValues.map((id) => ({\n\t\t\tid,\n\t\t\ttype: SelectMenuDefaultValueType.Channel as const,\n\t\t}));\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * The base select menu builder that contains common symbols for select menu builders.\n *\n * @typeParam SelectMenuType - The type of select menu this would be instantiated for.\n */\nexport abstract class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu.\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu.\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled.\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import {\n\ttype APIMentionableSelectComponent,\n\ttype APISelectMenuDefaultValue,\n\ttype Snowflake,\n\tComponentType,\n\tSelectMenuDefaultValueType,\n} from 'discord-api-types/v10';\nimport { type RestOrArray, normalizeArray } from '../../util/normalizeArray.js';\nimport { optionsLengthValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for mentionable select menus.\n */\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n\n\t/**\n\t * Adds default roles to this auto populated select menu.\n\t *\n\t * @param roles - The roles to add\n\t */\n\tpublic addDefaultRoles(...roles: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(roles);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.Role as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds default users to this auto populated select menu.\n\t *\n\t * @param users - The users to add\n\t */\n\tpublic addDefaultUsers(...users: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(users);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.User as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds default values to this auto populated select menu.\n\t *\n\t * @param values - The values to add\n\t */\n\tpublic addDefaultValues(\n\t\t...values: RestOrArray<\n\t\t\t| APISelectMenuDefaultValue\n\t\t\t| APISelectMenuDefaultValue\n\t\t>\n\t) {\n\t\tconst normalizedValues = normalizeArray(values);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\t\tthis.data.default_values.push(...normalizedValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets default values to this auto populated select menu.\n\t *\n\t * @param values - The values to set\n\t */\n\tpublic setDefaultValues(\n\t\t...values: RestOrArray<\n\t\t\t| APISelectMenuDefaultValue\n\t\t\t| APISelectMenuDefaultValue\n\t\t>\n\t) {\n\t\tconst normalizedValues = normalizeArray(values);\n\t\toptionsLengthValidator.parse(normalizedValues.length);\n\t\tthis.data.default_values = normalizedValues.slice();\n\t\treturn this;\n\t}\n}\n","import {\n\ttype APIRoleSelectComponent,\n\ttype Snowflake,\n\tComponentType,\n\tSelectMenuDefaultValueType,\n} from 'discord-api-types/v10';\nimport { type RestOrArray, normalizeArray } from '../../util/normalizeArray.js';\nimport { optionsLengthValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for role select menus.\n */\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n\n\t/**\n\t * Adds default roles to this auto populated select menu.\n\t *\n\t * @param roles - The roles to add\n\t */\n\tpublic addDefaultRoles(...roles: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(roles);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.Role as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets default roles to this auto populated select menu.\n\t *\n\t * @param roles - The roles to set\n\t */\n\tpublic setDefaultRoles(...roles: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(roles);\n\t\toptionsLengthValidator.parse(normalizedValues.length);\n\n\t\tthis.data.default_values = normalizedValues.map((id) => ({\n\t\t\tid,\n\t\t\ttype: SelectMenuDefaultValueType.Role as const,\n\t\t}));\n\n\t\treturn this;\n\t}\n}\n","import { ComponentType } from 'discord-api-types/v10';\nimport type { APIStringSelectComponent, APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menus.\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu.\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu.\n\t *\n\t * @param options - The options to add\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + normalizedOptions.length);\n\t\tthis.options.push(\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options for this select menu.\n\t *\n\t * @param options - The options to set\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\treturn this.spliceOptions(0, this.options.length, ...options);\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts options for this select menu.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}.\n\t * It's useful for modifying and adjusting the order of existing options.\n\t * @example\n\t * Remove the first option:\n\t * ```ts\n\t * selectMenu.spliceOptions(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n option:\n\t * ```ts\n\t * const n = 4;\n\t * selectMenu.spliceOptions(0, n);\n\t * ```\n\t * @example\n\t * Remove the last option:\n\t * ```ts\n\t * selectMenu.spliceOptions(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of options to remove\n\t * @param options - The replacing option objects or builders\n\t */\n\tpublic spliceOptions(\n\t\tindex: number,\n\t\tdeleteCount: number,\n\t\t...options: RestOrArray\n\t) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\n\t\tconst clone = [...this.options];\n\n\t\tclone.splice(\n\t\t\tindex,\n\t\t\tdeleteCount,\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\n\t\toptionsLengthValidator.parse(clone.length);\n\t\tthis.options.splice(0, this.options.length, ...clone);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import {\n\ttype APIUserSelectComponent,\n\ttype Snowflake,\n\tComponentType,\n\tSelectMenuDefaultValueType,\n} from 'discord-api-types/v10';\nimport { type RestOrArray, normalizeArray } from '../../util/normalizeArray.js';\nimport { optionsLengthValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for user select menus.\n */\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n\n\t/**\n\t * Adds default users to this auto populated select menu.\n\t *\n\t * @param users - The users to add\n\t */\n\tpublic addDefaultUsers(...users: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(users);\n\t\toptionsLengthValidator.parse((this.data.default_values?.length ?? 0) + normalizedValues.length);\n\t\tthis.data.default_values ??= [];\n\n\t\tthis.data.default_values.push(\n\t\t\t...normalizedValues.map((id) => ({\n\t\t\t\tid,\n\t\t\t\ttype: SelectMenuDefaultValueType.User as const,\n\t\t\t})),\n\t\t);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets default users to this auto populated select menu.\n\t *\n\t * @param users - The users to set\n\t */\n\tpublic setDefaultUsers(...users: RestOrArray) {\n\t\tconst normalizedValues = normalizeArray(users);\n\t\toptionsLengthValidator.parse(normalizedValues.length);\n\n\t\tthis.data.default_values = normalizedValues.map((id) => ({\n\t\t\tid,\n\t\t\ttype: SelectMenuDefaultValueType.User as const,\n\t\t}));\n\n\t\treturn this;\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for text inputs.\n */\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data.\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input.\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input.\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder for this text input.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this text input.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required.\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for modals.\n */\nexport class ModalBuilder implements JSONEncodable {\n\t/**\n\t * The API data associated with this modal.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * The components within this modal.\n\t */\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\t/**\n\t * Creates a new modal from API data.\n\t *\n\t * @param data - The API data to create this modal with\n\t */\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of this modal.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of this modal.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this modal.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tReturnType extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => ReturnType): asserts input is ReturnType {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n\nexport function validateNSFW(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n\tvalidateNSFW,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * A builder that creates API-compatible JSON data for slash commands.\n */\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this command.\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Whether this command is NSFW.\n\t */\n\tpublic readonly nsfw: boolean | undefined = undefined;\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this command is NSFW.\n\t *\n\t * @param nsfw - Whether this command is NSFW\n\t */\n\tpublic setNSFW(nsfw = true) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateNSFW(nsfw);\n\t\tReflect.set(this, 'nsfw', nsfw);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command.\n\t *\n\t * @param input - A function that returns a subcommand group builder or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\n/**\n * An interface specifically for slash command subcommands.\n */\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\n/**\n * An interface specifically for slash command options.\n */\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\n/**\n * An interface that ensures the `toJSON()` call will return something\n * that can be serialized into API-compatible data.\n */\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands within this subcommand group.\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * A builder that creates API-compatible JSON data for slash command subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options within this subcommand.\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\n/**\n * This mixin holds name and description symbols for slash commands.\n */\nexport class SharedNameAndDescription {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name!: string;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description!: string;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this command.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations for this command.\n\t *\n\t * @param localizedDescriptions - The object of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command attachment option.\n */\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\n/**\n * The base application command option builder that contains common symbols for application command builders.\n */\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\t/**\n\t * Whether this option is required.\n\t *\n\t * @defaultValue `false`\n\t */\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Sets whether this option is required.\n\t *\n\t * @param required - Whether this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\t/**\n\t * This method runs required validators on this builder.\n\t */\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command boolean option.\n */\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n/**\n * A slash command channel option.\n */\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n/**\n * The allowed channel types used for a channel option in a slash command builder.\n *\n * @privateRemarks This can't be dynamic because const enums are erased at runtime.\n * @internal\n */\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n\tChannelType.GuildMedia,\n] as const;\n\n/**\n * The type of allowed channel types used for a channel option.\n */\nexport type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\n/**\n * This mixin holds channel type symbols used for options.\n */\nexport class ApplicationCommandOptionChannelTypesMixin {\n\t/**\n\t * The channel types of this option.\n\t */\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option.\n\t *\n\t * @param channelTypes - The channel types\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n/**\n * A slash command integer option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this } as APIApplicationCommandIntegerOption;\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","/**\n * This mixin holds minimum and maximum symbols used for options.\n */\nexport abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\t/**\n\t * The maximum value of this option.\n\t */\n\tpublic readonly max_value?: number;\n\n\t/**\n\t * The minimum value of this option.\n\t */\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option.\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option.\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\n/**\n * This mixin holds choices and autocomplete symbols used for options.\n */\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\t/**\n\t * The choices of this option.\n\t */\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\t/**\n\t * Whether this option utilizes autocomplete.\n\t */\n\tpublic readonly autocomplete?: boolean;\n\n\t/**\n\t * The type of this option.\n\t *\n\t * @privateRemarks Since this is present and this is a mixin, this is needed.\n\t */\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices to this option.\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets multiple choices for this option.\n\t *\n\t * @param choices - The choices to set\n\t */\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Whether this option uses autocomplete.\n\t *\n\t * @param autocomplete - Whether this option should use autocomplete\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command mentionable option.\n */\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n/**\n * A slash command number option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this } as APIApplicationCommandNumberOption;\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command role option.\n */\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n/**\n * A slash command string option.\n */\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\t/**\n\t * The maximum length of this option.\n\t */\n\tpublic readonly max_length?: number;\n\n\t/**\n\t * The minimum length of this option.\n\t */\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this } as APIApplicationCommandStringOption;\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command user option.\n */\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\n/**\n * This mixin holds symbols that can be shared in slash command options.\n *\n * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions.\n */\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\t/**\n\t * Where the actual adding magic happens. ✨\n\t *\n\t * @param input - The input. What else?\n\t * @param Instance - The instance of whatever is being added\n\t * @internal\n\t */\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| OptionBuilder\n\t\t\t| ((\n\t\t\t\t\tbuilder: OptionBuilder,\n\t\t\t ) => Omit | Omit | OptionBuilder),\n\t\tInstance: new () => OptionBuilder,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\n/**\n * The type a context menu command can be.\n */\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n\n/**\n * A builder that creates API-compatible JSON data for context menu commands.\n */\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this command.\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type of this command.\n\t *\n\t * @param type - The type to use\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run this command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIEmbed } from 'discord-api-types/v10';\n\n/**\n * Calculates the length of the embed.\n *\n * @param data - The embed data to check\n */\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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AAI;AAC5C,aAAO;AAAA,IACR;AAEA,YAAQ,IAAI,MAAM,sBAAsB,CAAC,CAAC;AAE1C,eAAW,QAAQ,OAAO,QAAQ,cAAc;AAC/C,WAAK,oBAAoB,GAAI,IAAsC;AACpE,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,SAA4D;AAClE,IAAAI,4BAA2B,KAAK,MAAM,KAAK,IAAI;AAE/C,4BAAwB,KAAK,kBAAkB;AAE/C,WAAO,EAAE,GAAG,KAAK;AAAA,EAClB;AACD;;;AC9LO,SAAS,YAAY,MAAgB;AAC3C,UACE,KAAK,OAAO,UAAU,MACtB,KAAK,aAAa,UAAU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;ArC6DT,IAAM,UAAU;","names":["Assertions_exports","s","s","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","SelectMenuDefaultValueType","ComponentType","SelectMenuDefaultValueType","ComponentType","SelectMenuDefaultValueType","ComponentType","SelectMenuDefaultValueType","ComponentType","ComponentType","ComponentType","SelectMenuDefaultValueType","ComponentType","SelectMenuDefaultValueType","ComponentType","Assertions_exports","placeholderValidator","s","s","placeholderValidator","ComponentType","placeholderValidator","ComponentType","ComponentType","Assertions_exports","validateRequiredParameters","s","s","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","s","s","descriptionPredicate","validateRequiredParameters","mix","ApplicationCommandOptionType","mix","validateRequiredParameters","ApplicationCommandOptionType","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ChannelType","ChannelType","s","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","s","ApplicationCommandOptionType","s","booleanPredicate","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","numberValidator","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","minLengthValidator","s","maxLengthValidator","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","validateRequiredParameters","ApplicationCommandOptionType","mix","validateRequiredParameters","mix","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","s","namePredicate","s","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/package.json b/node_modules/@discordjs/builders/package.json new file mode 100644 index 0000000..5084770 --- /dev/null +++ b/node_modules/@discordjs/builders/package.json @@ -0,0 +1,97 @@ +{ + "$schema": "https://json.schemastore.org/package.json", + "name": "@discordjs/builders", + "version": "1.7.0", + "description": "A set of builders that you can use when creating your bot", + "exports": { + ".": { + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + } + } + }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "directories": { + "lib": "src", + "test": "__tests__" + }, + "files": [ + "dist" + ], + "contributors": [ + "Vlad Frangu ", + "Crawl ", + "Amish Shah ", + "SpaceEEC ", + "Aura Román " + ], + "license": "Apache-2.0", + "keywords": [ + "discord", + "api", + "bot", + "client", + "node", + "discordapp", + "discordjs" + ], + "repository": { + "type": "git", + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/builders" + }, + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" + }, + "homepage": "https://discord.js.org", + "dependencies": { + "@sapphire/shapeshift": "^3.9.3", + "discord-api-types": "0.37.61", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.3", + "tslib": "^2.6.2", + "@discordjs/formatters": "^0.3.3", + "@discordjs/util": "^1.0.2" + }, + "devDependencies": { + "@favware/cliff-jumper": "^2.2.1", + "@types/node": "16.18.60", + "@vitest/coverage-v8": "^0.34.6", + "cross-env": "^7.0.3", + "downlevel-dts": "^0.11.0", + "esbuild-plugin-version-injector": "^1.2.1", + "eslint": "^8.53.0", + "eslint-config-neon": "^0.1.57", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^3.0.3", + "tsup": "^7.2.0", + "turbo": "^1.10.17-canary.0", + "typescript": "^5.2.2", + "vitest": "^0.34.6", + "@discordjs/api-extractor": "^7.38.1" + }, + "engines": { + "node": ">=16.11.0" + }, + "publishConfig": { + "access": "public" + }, + "scripts": { + "test": "vitest run", + "build": "tsc --noEmit && tsup", + "build:docs": "tsc -p tsconfig.docs.json && downlevel-dts ./dist-docs ./dist-docs", + "lint": "prettier --check . && cross-env TIMING=1 eslint --format=pretty src __tests__", + "format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src __tests__", + "fmt": "pnpm run format", + "docs": "pnpm run build:docs && api-extractor run --local", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/builders/*'", + "release": "cliff-jumper" + } +} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/CHANGELOG.md b/node_modules/@discordjs/collection/CHANGELOG.md new file mode 100644 index 0000000..2c43057 --- /dev/null +++ b/node_modules/@discordjs/collection/CHANGELOG.md @@ -0,0 +1,190 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@discordjs/collection@1.5.3](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.2...@discordjs/collection@1.5.3) - (2023-08-17) + +## Documentation + +- Update Node.js requirement to 16.11.0 (#9764) ([188877c](https://github.com/discordjs/discord.js/commit/188877c50af70f0d5cffb246620fa277435c6ce6)) + +# [@discordjs/collection@1.5.2](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.1...@discordjs/collection@1.5.2) - (2023-07-31) + +## Refactor + +- **collection:** Reduce `reduce`'s code (#9581) ([b85a3f2](https://github.com/discordjs/discord.js/commit/b85a3f2ddee8fc5974749b95fc07389a03093df2)) + +# [@discordjs/collection@1.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.0...@discordjs/collection@1.5.1) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +# [@discordjs/collection@1.5.2](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.1...@discordjs/collection@1.5.2) - (2023-07-31) + +## Refactor + +- **collection:** Reduce `reduce`'s code (#9581) ([b85a3f2](https://github.com/discordjs/discord.js/commit/b85a3f2ddee8fc5974749b95fc07389a03093df2)) + +# [@discordjs/collection@1.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.0...@discordjs/collection@1.5.1) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +# [@discordjs/collection@1.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.0...@discordjs/collection@1.5.1) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +# [@discordjs/collection@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.4.0...@discordjs/collection@1.5.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +## Refactor + +- **collection:** Fix/silence linter warnings (#9266) ([d6f4e60](https://github.com/discordjs/discord.js/commit/d6f4e60efd1a1796fc84dbbfbac4f9790e480a1c)) + +# [@discordjs/collection@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.3.0...@discordjs/collection@1.4.0) - (2023-03-12) + +## Documentation + +- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28)) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) + +## Refactor + +- Compare with `undefined` directly (#9191) ([869153c](https://github.com/discordjs/discord.js/commit/869153c3fdf155783e7c0ecebd3627b087c3a026)) + +# [@discordjs/collection@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.2.0...@discordjs/collection@1.3.0) - (2022-11-28) + +## Bug Fixes + +- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4)) + +## Features + +- Add `Collection#subtract()` (#8393) ([291f36c](https://github.com/discordjs/discord.js/commit/291f36cd736b5dea058145a1335bf7c78ec1d81d)) + +# [@discordjs/collection@1.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.1.0...@discordjs/collection@1.2.0) - (2022-10-08) + +## Bug Fixes + +- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9)) + +## Documentation + +- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0)) +- Remove xml tag from collection#find (#8550) ([4032457](https://github.com/discordjs/discord.js/commit/40324574ebea9894cadcc967e0db0e4e21d62768)) + +## Features + +- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2)) + +## Refactor + +- Website components (#8600) ([c334157](https://github.com/discordjs/discord.js/commit/c3341570d983aea9ecc419979d5a01de658c9d67)) +- Use `eslint-config-neon` for packages. (#8579) ([edadb9f](https://github.com/discordjs/discord.js/commit/edadb9fe5dfd9ff51a3cfc9b25cb242d3f9f5241)) + +## Typings + +- **Collection:** Make fn return type unknown (#8676) ([822b7f2](https://github.com/discordjs/discord.js/commit/822b7f234af053c8f917b0a998b82abfccd33801)) + +# [@discordjs/collection@1.1.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.0.1...@discordjs/collection@1.1.0) - (2022-08-22) + +## Bug Fixes + +- Use proper format for `@link` text (#8384) ([2655639](https://github.com/discordjs/discord.js/commit/26556390a3800e954974a00c1328ff47d3e67e9a)) + +## Documentation + +- Fence examples in codeblocks ([193b252](https://github.com/discordjs/discord.js/commit/193b252672440a860318d3c2968aedd9cb88e0ce)) +- Use link tags (#8382) ([5494791](https://github.com/discordjs/discord.js/commit/549479131318c659f86f0eb18578d597e22522d3)) + +## Features + +- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007)) +- **website:** Show descriptions for `@typeParam` blocks (#8523) ([e475b63](https://github.com/discordjs/discord.js/commit/e475b63f257f6261d73cb89fee9ecbcdd84e2a6b)) + +## Refactor + +- **website:** Adjust typography (#8503) ([0f83402](https://github.com/discordjs/discord.js/commit/0f834029850d2448981596cf082ff59917018d66)) +- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e)) + +# [@discordjs/collection@0.8.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.7.0...@discordjs/collection@0.8.0) - (2022-07-17) + +## Bug Fixes + +- **Collection:** Make error messages consistent (#8224) ([5bd6b28](https://github.com/discordjs/discord.js/commit/5bd6b28b3ebfced1cb9d23e83bd7c0def7a12404)) +- Check for function type (#8064) ([3bb9c0e](https://github.com/discordjs/discord.js/commit/3bb9c0e5c37311044ff41761b572ac4f91cda57c)) + +## Documentation + +- Add codecov coverage badge to readmes (#8226) ([f6db285](https://github.com/discordjs/discord.js/commit/f6db285c073898a749fe4591cbd4463d1896daf5)) + +## Features + +- Codecov (#8219) ([f10f4cd](https://github.com/discordjs/discord.js/commit/f10f4cdcd88ca6be7ec735ed3a415ba13da83db0)) +- **docgen:** Update typedoc ([b3346f4](https://github.com/discordjs/discord.js/commit/b3346f4b9b3d4f96443506643d4631dc1c6d7b21)) +- Website (#8043) ([127931d](https://github.com/discordjs/discord.js/commit/127931d1df7a2a5c27923c2f2151dbf3824e50cc)) +- **docgen:** Typescript support ([3279b40](https://github.com/discordjs/discord.js/commit/3279b40912e6aa61507bedb7db15a2b8668de44b)) +- Docgen package (#8029) ([8b979c0](https://github.com/discordjs/discord.js/commit/8b979c0245c42fd824d8e98745ee869f5360fc86)) +- Use vitest instead of jest for more speed ([8d8e6c0](https://github.com/discordjs/discord.js/commit/8d8e6c03decd7352a2aa180f6e5bc1a13602539b)) +- Add scripts package for locally used scripts ([f2ae1f9](https://github.com/discordjs/discord.js/commit/f2ae1f9348bfd893332a9060f71a8a5f272a1b8b)) + +## Refactor + +- **collection:** Remove `default` property (#8055) ([c8f1690](https://github.com/discordjs/discord.js/commit/c8f1690896f55f06e05a83704262783cfc2bb91d)) +- **collection:** Remove default export (#8053) ([16810f3](https://github.com/discordjs/discord.js/commit/16810f3e410bf35ed7e6e7412d517ea74c792c5d)) +- Move all the config files to root (#8033) ([769ea0b](https://github.com/discordjs/discord.js/commit/769ea0bfe78c4f1d413c6b397c604ffe91e39c6a)) + +## Testing + +- **collection:** Improve coverage (#8222) ([a51f721](https://github.com/discordjs/discord.js/commit/a51f7215eca67a0f46fba8b2d706f7ec6f6dc228)) + +# [@discordjs/collection@0.7.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.6.0...@discordjs/collection@0.7.0) - (2022-06-04) + +## Styling + +- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629)) + +# [@discordjs/collection@0.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.5.0...@discordjs/collection@0.6.0) - (2022-04-17) + +## Features + +- Add support for module: NodeNext in TS and ESM (#7598) ([8f1986a](https://github.com/discordjs/discord.js/commit/8f1986a6aa98365e09b00e84ad5f9f354ab61f3d)) +- **builders:** Add attachment command option type (#7203) ([ae0f35f](https://github.com/discordjs/discord.js/commit/ae0f35f51d68dfa5a7dc43d161ef9365171debdb)) +- **Collection:** Add merging functions (#7299) ([e4bd07b](https://github.com/discordjs/discord.js/commit/e4bd07b2394f227ea06b72eb6999de9ab3127b25)) + +# [@discordjs/collection@0.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@0.4.0...@discordjs/collection@0.5.0) - (2022-01-24) + +## Refactor + +- Make `intersect` perform a true intersection (#7211) ([d8efba2](https://github.com/discordjs/discord.js/commit/d8efba24e09aa2a8dbf028fc57a561a56e7833fd)) + +## Typings + +- Add `ReadonlyCollection` (#7245) ([db25f52](https://github.com/discordjs/discord.js/commit/db25f529b26d7c819c1c42ad3e26c2263ea2da0e)) +- **Collection:** Union types on `intersect` and `difference` (#7196) ([1f9b922](https://github.com/discordjs/discord.js/commit/1f9b9225f2066e9cc66c3355417139fd25cc403c)) diff --git a/node_modules/@discordjs/collection/LICENSE b/node_modules/@discordjs/collection/LICENSE new file mode 100644 index 0000000..d21f37a --- /dev/null +++ b/node_modules/@discordjs/collection/LICENSE @@ -0,0 +1,191 @@ + 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 + + Copyright 2021 Noel Buechler + Copyright 2015 Amish Shah + + 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/@discordjs/collection/README.md b/node_modules/@discordjs/collection/README.md new file mode 100644 index 0000000..4ddde14 --- /dev/null +++ b/node_modules/@discordjs/collection/README.md @@ -0,0 +1,67 @@ +
+
+

+ discord.js +

+
+

+ Discord server + npm version + npm downloads + Build status + Code coverage +

+

+ Vercel + Cloudflare Workers +

+
+ +## About + +`@discordjs/collection` is a powerful utility data structure used in discord.js. + +## Installation + +**Node.js 16.11.0 or newer is required.** + +```sh +npm install @discordjs/collection +yarn add @discordjs/collection +pnpm add @discordjs/collection +``` + +## Links + +- [Website][website] ([source][website-source]) +- [Documentation][documentation] +- [Guide][guide] ([source][guide-source]) + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. +- [discord.js Discord server][discord] +- [Discord API Discord server][discord-api] +- [GitHub][source] +- [npm][npm] +- [Related libraries][related-libs] + +## Contributing + +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. + +## Help + +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. + +[website]: https://discord.js.org +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/docs/packages/collection/stable +[guide]: https://discordjs.guide/ +[guide-source]: https://github.com/discordjs/guide +[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html +[discord]: https://discord.gg/djs +[discord-api]: https://discord.gg/discord-api +[source]: https://github.com/discordjs/discord.js/tree/main/packages/collection +[npm]: https://www.npmjs.com/package/@discordjs/collection +[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries +[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md diff --git a/node_modules/@discordjs/collection/dist/index.d.mts b/node_modules/@discordjs/collection/dist/index.d.mts new file mode 100644 index 0000000..5990c61 --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.d.mts @@ -0,0 +1,457 @@ +/** + * @internal + */ +interface CollectionConstructor { + new (): Collection; + new (entries?: readonly (readonly [K, V])[] | null): Collection; + new (iterable: Iterable): Collection; + readonly prototype: Collection; + readonly [Symbol.species]: CollectionConstructor; +} +/** + * Represents an immutable version of a collection + */ +type ReadonlyCollection = Omit, 'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'> & ReadonlyMap; +/** + * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself + * + * @internal + */ +interface Collection extends Map { + constructor: CollectionConstructor; +} +/** + * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has + * an ID, for significantly improved performance and ease-of-use. + * + * @typeParam K - The key type this collection holds + * @typeParam V - The value type this collection holds + */ +declare class Collection extends Map { + /** + * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator. + * + * @param key - The key to get if it exists, or set otherwise + * @param defaultValueGenerator - A function that generates the default value + * @example + * ```ts + * collection.ensure(guildId, () => defaultGuildConfig); + * ``` + */ + ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V; + /** + * Checks if all of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if all of the elements exist, `false` if at least one does not exist. + */ + hasAll(...keys: K[]): boolean; + /** + * Checks if any of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if any of the elements exist, `false` if none exist. + */ + hasAny(...keys: K[]): boolean; + /** + * Obtains the first value(s) in this collection. + * + * @param amount - Amount of values to obtain from the beginning + * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative + */ + first(): V | undefined; + first(amount: number): V[]; + /** + * Obtains the first key(s) in this collection. + * + * @param amount - Amount of keys to obtain from the beginning + * @returns A single key if no amount is provided or an array of keys, starting from the end if + * amount is negative + */ + firstKey(): K | undefined; + firstKey(amount: number): K[]; + /** + * Obtains the last value(s) in this collection. + * + * @param amount - Amount of values to obtain from the end + * @returns A single value if no amount is provided or an array of values, starting from the start if + * amount is negative + */ + last(): V | undefined; + last(amount: number): V[]; + /** + * Obtains the last key(s) in this collection. + * + * @param amount - Amount of keys to obtain from the end + * @returns A single key if no amount is provided or an array of keys, starting from the start if + * amount is negative + */ + lastKey(): K | undefined; + lastKey(amount: number): K[]; + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the item at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the element to obtain + */ + at(index: number): V | undefined; + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the key at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the key to obtain + */ + keyAt(index: number): K | undefined; + /** + * Obtains unique random value(s) from this collection. + * + * @param amount - Amount of values to obtain randomly + * @returns A single value if no amount is provided or an array of values + */ + random(): V | undefined; + random(amount: number): V[]; + /** + * Obtains unique random key(s) from this collection. + * + * @param amount - Amount of keys to obtain randomly + * @returns A single key if no amount is provided or an array + */ + randomKey(): K | undefined; + randomKey(amount: number): K[]; + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()} + * but returns a Collection instead of an Array. + */ + reverse(): this; + /** + * Searches for a single item where the given function returns a truthy value. This behaves like + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}. + * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you + * should use the `get` method. See + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.find(user => user.username === 'Bob'); + * ``` + */ + find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined; + find(fn: (value: V, key: K, collection: this) => unknown): V | undefined; + find(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): V2 | undefined; + find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined; + /** + * Searches for the key of a single item where the given function returns a truthy value. This behaves like + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()}, + * but returns the key rather than the positional index. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.findKey(user => user.username === 'Bob'); + * ``` + */ + findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined; + findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined; + findKey(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): K2 | undefined; + findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined; + /** + * Removes items that satisfy the provided filter function. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @returns The number of removed entries + */ + sweep(fn: (value: V, key: K, collection: this) => unknown): number; + sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number; + /** + * Identical to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()}, + * but returns a Collection instead of an Array. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.filter(user => user.username === 'Bob'); + * ``` + */ + filter(fn: (value: V, key: K, collection: this) => key is K2): Collection; + filter(fn: (value: V, key: K, collection: this) => value is V2): Collection; + filter(fn: (value: V, key: K, collection: this) => unknown): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection; + /** + * Partitions the collection into two collections where the first collection + * contains the items that passed and the second contains the items that failed. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * const [big, small] = collection.partition(guild => guild.memberCount > 250); + * ``` + */ + partition(fn: (value: V, key: K, collection: this) => key is K2): [Collection, Collection, V>]; + partition(fn: (value: V, key: K, collection: this) => value is V2): [Collection, Collection>]; + partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection]; + partition(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): [Collection, Collection, V>]; + partition(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): [Collection, Collection>]; + partition(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): [Collection, Collection]; + /** + * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}. + * + * @param fn - Function that produces a new Collection + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.flatMap(guild => guild.members.cache); + * ``` + */ + flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection; + flatMap(fn: (this: This, value: V, key: K, collection: this) => Collection, thisArg: This): Collection; + /** + * Maps each item to another value into an array. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}. + * + * @param fn - Function that produces an element of the new array, taking three arguments + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.map(user => user.tag); + * ``` + */ + map(fn: (value: V, key: K, collection: this) => T): T[]; + map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[]; + /** + * Maps each item to another value into a collection. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}. + * + * @param fn - Function that produces an element of the new collection, taking three arguments + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.mapValues(user => user.tag); + * ``` + */ + mapValues(fn: (value: V, key: K, collection: this) => T): Collection; + mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection; + /** + * Checks if there exists an item that passes a test. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.some(user => user.discriminator === '0000'); + * ``` + */ + some(fn: (value: V, key: K, collection: this) => unknown): boolean; + some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean; + /** + * Checks if all items passes a test. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.every(user => !user.bot); + * ``` + */ + every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection; + every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection; + every(fn: (value: V, key: K, collection: this) => unknown): boolean; + every(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): this is Collection; + every(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): this is Collection; + every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean; + /** + * Applies a function to produce a single value. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}. + * + * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param initialValue - Starting value for the accumulator + * @example + * ```ts + * collection.reduce((acc, guild) => acc + guild.memberCount, 0); + * ``` + */ + reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T; + /** + * Identical to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()}, + * but returns the collection instead of undefined. + * + * @param fn - Function to execute for each element + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection + * .each(user => console.log(user.username)) + * .filter(user => user.bot) + * .each(user => console.log(user.username)); + * ``` + */ + each(fn: (value: V, key: K, collection: this) => void): this; + each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this; + /** + * Runs a function on the collection and returns the collection. + * + * @param fn - Function to execute + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection + * .tap(coll => console.log(coll.size)) + * .filter(user => user.bot) + * .tap(coll => console.log(coll.size)) + * ``` + */ + tap(fn: (collection: this) => void): this; + tap(fn: (this: T, collection: this) => void, thisArg: T): this; + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ + clone(): Collection; + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * + * @param collections - Collections to merge + * @example + * ```ts + * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + * ``` + */ + concat(...collections: ReadonlyCollection[]): Collection; + /** + * Checks if this collection shares identical items with another. + * This is different to checking for equality using equal-signs, because + * the collections may be different objects, but contain the same data. + * + * @param collection - Collection to compare with + * @returns Whether the collections have identical contents + */ + equals(collection: ReadonlyCollection): boolean; + /** + * The sort method sorts the items of a collection in place and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @example + * ```ts + * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ + sort(compareFunction?: Comparator): this; + /** + * The intersect method returns a new structure containing items where the keys and values are present in both original structures. + * + * @param other - The other Collection to filter against + */ + intersect(other: ReadonlyCollection): Collection; + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ + subtract(other: ReadonlyCollection): Collection; + /** + * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. + * + * @param other - The other Collection to filter against + */ + difference(other: ReadonlyCollection): Collection; + /** + * Merges two Collections together into a new Collection. + * + * @param other - The other Collection to merge with + * @param whenInSelf - Function getting the result if the entry only exists in this Collection + * @param whenInOther - Function getting the result if the entry only exists in the other Collection + * @param whenInBoth - Function getting the result if the entry exists in both Collections + * @example + * ```ts + * // Sums up the entries in two collections. + * coll.merge( + * other, + * x => ({ keep: true, value: x }), + * y => ({ keep: true, value: y }), + * (x, y) => ({ keep: true, value: x + y }), + * ); + * ``` + * @example + * ```ts + * // Intersects two collections in a left-biased manner. + * coll.merge( + * other, + * x => ({ keep: false }), + * y => ({ keep: false }), + * (x, _) => ({ keep: true, value: x }), + * ); + * ``` + */ + merge(other: ReadonlyCollection, whenInSelf: (value: V, key: K) => Keep, whenInOther: (valueOther: T, key: K) => Keep, whenInBoth: (value: V, valueOther: T, key: K) => Keep): Collection; + /** + * The sorted method sorts the items of a collection and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, + * according to the string conversion of each element. + * @example + * ```ts + * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ + sorted(compareFunction?: Comparator): Collection; + toJSON(): V[]; + private static defaultSort; + /** + * Creates a Collection from a list of entries. + * + * @param entries - The list of entries + * @param combine - Function to combine an existing entry with a new one + * @example + * ```ts + * Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y); + * // returns Collection { "a" => 3, "b" => 2 } + * ``` + */ + static combineEntries(entries: Iterable<[K, V]>, combine: (firstValue: V, secondValue: V, key: K) => V): Collection; +} +/** + * @internal + */ +type Keep = { + keep: false; +} | { + keep: true; + value: V; +}; +/** + * @internal + */ +type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number; + +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version + * that you are currently using. + */ +declare const version: string; + +export { Collection, CollectionConstructor, Comparator, Keep, ReadonlyCollection, version }; diff --git a/node_modules/@discordjs/collection/dist/index.d.ts b/node_modules/@discordjs/collection/dist/index.d.ts new file mode 100644 index 0000000..5990c61 --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.d.ts @@ -0,0 +1,457 @@ +/** + * @internal + */ +interface CollectionConstructor { + new (): Collection; + new (entries?: readonly (readonly [K, V])[] | null): Collection; + new (iterable: Iterable): Collection; + readonly prototype: Collection; + readonly [Symbol.species]: CollectionConstructor; +} +/** + * Represents an immutable version of a collection + */ +type ReadonlyCollection = Omit, 'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'> & ReadonlyMap; +/** + * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself + * + * @internal + */ +interface Collection extends Map { + constructor: CollectionConstructor; +} +/** + * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has + * an ID, for significantly improved performance and ease-of-use. + * + * @typeParam K - The key type this collection holds + * @typeParam V - The value type this collection holds + */ +declare class Collection extends Map { + /** + * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator. + * + * @param key - The key to get if it exists, or set otherwise + * @param defaultValueGenerator - A function that generates the default value + * @example + * ```ts + * collection.ensure(guildId, () => defaultGuildConfig); + * ``` + */ + ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V; + /** + * Checks if all of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if all of the elements exist, `false` if at least one does not exist. + */ + hasAll(...keys: K[]): boolean; + /** + * Checks if any of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if any of the elements exist, `false` if none exist. + */ + hasAny(...keys: K[]): boolean; + /** + * Obtains the first value(s) in this collection. + * + * @param amount - Amount of values to obtain from the beginning + * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative + */ + first(): V | undefined; + first(amount: number): V[]; + /** + * Obtains the first key(s) in this collection. + * + * @param amount - Amount of keys to obtain from the beginning + * @returns A single key if no amount is provided or an array of keys, starting from the end if + * amount is negative + */ + firstKey(): K | undefined; + firstKey(amount: number): K[]; + /** + * Obtains the last value(s) in this collection. + * + * @param amount - Amount of values to obtain from the end + * @returns A single value if no amount is provided or an array of values, starting from the start if + * amount is negative + */ + last(): V | undefined; + last(amount: number): V[]; + /** + * Obtains the last key(s) in this collection. + * + * @param amount - Amount of keys to obtain from the end + * @returns A single key if no amount is provided or an array of keys, starting from the start if + * amount is negative + */ + lastKey(): K | undefined; + lastKey(amount: number): K[]; + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the item at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the element to obtain + */ + at(index: number): V | undefined; + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the key at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the key to obtain + */ + keyAt(index: number): K | undefined; + /** + * Obtains unique random value(s) from this collection. + * + * @param amount - Amount of values to obtain randomly + * @returns A single value if no amount is provided or an array of values + */ + random(): V | undefined; + random(amount: number): V[]; + /** + * Obtains unique random key(s) from this collection. + * + * @param amount - Amount of keys to obtain randomly + * @returns A single key if no amount is provided or an array + */ + randomKey(): K | undefined; + randomKey(amount: number): K[]; + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()} + * but returns a Collection instead of an Array. + */ + reverse(): this; + /** + * Searches for a single item where the given function returns a truthy value. This behaves like + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}. + * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you + * should use the `get` method. See + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.find(user => user.username === 'Bob'); + * ``` + */ + find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined; + find(fn: (value: V, key: K, collection: this) => unknown): V | undefined; + find(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): V2 | undefined; + find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined; + /** + * Searches for the key of a single item where the given function returns a truthy value. This behaves like + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()}, + * but returns the key rather than the positional index. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.findKey(user => user.username === 'Bob'); + * ``` + */ + findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined; + findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined; + findKey(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): K2 | undefined; + findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined; + /** + * Removes items that satisfy the provided filter function. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @returns The number of removed entries + */ + sweep(fn: (value: V, key: K, collection: this) => unknown): number; + sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number; + /** + * Identical to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()}, + * but returns a Collection instead of an Array. + * + * @param fn - The function to test with (should return boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.filter(user => user.username === 'Bob'); + * ``` + */ + filter(fn: (value: V, key: K, collection: this) => key is K2): Collection; + filter(fn: (value: V, key: K, collection: this) => value is V2): Collection; + filter(fn: (value: V, key: K, collection: this) => unknown): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): Collection; + filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection; + /** + * Partitions the collection into two collections where the first collection + * contains the items that passed and the second contains the items that failed. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * const [big, small] = collection.partition(guild => guild.memberCount > 250); + * ``` + */ + partition(fn: (value: V, key: K, collection: this) => key is K2): [Collection, Collection, V>]; + partition(fn: (value: V, key: K, collection: this) => value is V2): [Collection, Collection>]; + partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection]; + partition(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): [Collection, Collection, V>]; + partition(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): [Collection, Collection>]; + partition(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): [Collection, Collection]; + /** + * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}. + * + * @param fn - Function that produces a new Collection + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.flatMap(guild => guild.members.cache); + * ``` + */ + flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection; + flatMap(fn: (this: This, value: V, key: K, collection: this) => Collection, thisArg: This): Collection; + /** + * Maps each item to another value into an array. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}. + * + * @param fn - Function that produces an element of the new array, taking three arguments + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.map(user => user.tag); + * ``` + */ + map(fn: (value: V, key: K, collection: this) => T): T[]; + map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[]; + /** + * Maps each item to another value into a collection. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}. + * + * @param fn - Function that produces an element of the new collection, taking three arguments + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.mapValues(user => user.tag); + * ``` + */ + mapValues(fn: (value: V, key: K, collection: this) => T): Collection; + mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection; + /** + * Checks if there exists an item that passes a test. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.some(user => user.discriminator === '0000'); + * ``` + */ + some(fn: (value: V, key: K, collection: this) => unknown): boolean; + some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean; + /** + * Checks if all items passes a test. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}. + * + * @param fn - Function used to test (should return a boolean) + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection.every(user => !user.bot); + * ``` + */ + every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection; + every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection; + every(fn: (value: V, key: K, collection: this) => unknown): boolean; + every(fn: (this: This, value: V, key: K, collection: this) => key is K2, thisArg: This): this is Collection; + every(fn: (this: This, value: V, key: K, collection: this) => value is V2, thisArg: This): this is Collection; + every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean; + /** + * Applies a function to produce a single value. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}. + * + * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param initialValue - Starting value for the accumulator + * @example + * ```ts + * collection.reduce((acc, guild) => acc + guild.memberCount, 0); + * ``` + */ + reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T; + /** + * Identical to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()}, + * but returns the collection instead of undefined. + * + * @param fn - Function to execute for each element + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection + * .each(user => console.log(user.username)) + * .filter(user => user.bot) + * .each(user => console.log(user.username)); + * ``` + */ + each(fn: (value: V, key: K, collection: this) => void): this; + each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this; + /** + * Runs a function on the collection and returns the collection. + * + * @param fn - Function to execute + * @param thisArg - Value to use as `this` when executing function + * @example + * ```ts + * collection + * .tap(coll => console.log(coll.size)) + * .filter(user => user.bot) + * .tap(coll => console.log(coll.size)) + * ``` + */ + tap(fn: (collection: this) => void): this; + tap(fn: (this: T, collection: this) => void, thisArg: T): this; + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ + clone(): Collection; + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * + * @param collections - Collections to merge + * @example + * ```ts + * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + * ``` + */ + concat(...collections: ReadonlyCollection[]): Collection; + /** + * Checks if this collection shares identical items with another. + * This is different to checking for equality using equal-signs, because + * the collections may be different objects, but contain the same data. + * + * @param collection - Collection to compare with + * @returns Whether the collections have identical contents + */ + equals(collection: ReadonlyCollection): boolean; + /** + * The sort method sorts the items of a collection in place and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @example + * ```ts + * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ + sort(compareFunction?: Comparator): this; + /** + * The intersect method returns a new structure containing items where the keys and values are present in both original structures. + * + * @param other - The other Collection to filter against + */ + intersect(other: ReadonlyCollection): Collection; + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ + subtract(other: ReadonlyCollection): Collection; + /** + * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. + * + * @param other - The other Collection to filter against + */ + difference(other: ReadonlyCollection): Collection; + /** + * Merges two Collections together into a new Collection. + * + * @param other - The other Collection to merge with + * @param whenInSelf - Function getting the result if the entry only exists in this Collection + * @param whenInOther - Function getting the result if the entry only exists in the other Collection + * @param whenInBoth - Function getting the result if the entry exists in both Collections + * @example + * ```ts + * // Sums up the entries in two collections. + * coll.merge( + * other, + * x => ({ keep: true, value: x }), + * y => ({ keep: true, value: y }), + * (x, y) => ({ keep: true, value: x + y }), + * ); + * ``` + * @example + * ```ts + * // Intersects two collections in a left-biased manner. + * coll.merge( + * other, + * x => ({ keep: false }), + * y => ({ keep: false }), + * (x, _) => ({ keep: true, value: x }), + * ); + * ``` + */ + merge(other: ReadonlyCollection, whenInSelf: (value: V, key: K) => Keep, whenInOther: (valueOther: T, key: K) => Keep, whenInBoth: (value: V, valueOther: T, key: K) => Keep): Collection; + /** + * The sorted method sorts the items of a collection and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, + * according to the string conversion of each element. + * @example + * ```ts + * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ + sorted(compareFunction?: Comparator): Collection; + toJSON(): V[]; + private static defaultSort; + /** + * Creates a Collection from a list of entries. + * + * @param entries - The list of entries + * @param combine - Function to combine an existing entry with a new one + * @example + * ```ts + * Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y); + * // returns Collection { "a" => 3, "b" => 2 } + * ``` + */ + static combineEntries(entries: Iterable<[K, V]>, combine: (firstValue: V, secondValue: V, key: K) => V): Collection; +} +/** + * @internal + */ +type Keep = { + keep: false; +} | { + keep: true; + value: V; +}; +/** + * @internal + */ +type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number; + +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version + * that you are currently using. + */ +declare const version: string; + +export { Collection, CollectionConstructor, Comparator, Keep, ReadonlyCollection, version }; diff --git a/node_modules/@discordjs/collection/dist/index.js b/node_modules/@discordjs/collection/dist/index.js new file mode 100644 index 0000000..d9379ea --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.js @@ -0,0 +1,543 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +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/index.ts +var src_exports = {}; +__export(src_exports, { + Collection: () => Collection, + version: () => version +}); +module.exports = __toCommonJS(src_exports); + +// src/collection.ts +var Collection = class _Collection extends Map { + static { + __name(this, "Collection"); + } + /** + * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator. + * + * @param key - The key to get if it exists, or set otherwise + * @param defaultValueGenerator - A function that generates the default value + * @example + * ```ts + * collection.ensure(guildId, () => defaultGuildConfig); + * ``` + */ + ensure(key, defaultValueGenerator) { + if (this.has(key)) + return this.get(key); + if (typeof defaultValueGenerator !== "function") + throw new TypeError(`${defaultValueGenerator} is not a function`); + const defaultValue = defaultValueGenerator(key, this); + this.set(key, defaultValue); + return defaultValue; + } + /** + * Checks if all of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if all of the elements exist, `false` if at least one does not exist. + */ + hasAll(...keys) { + return keys.every((key) => super.has(key)); + } + /** + * Checks if any of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if any of the elements exist, `false` if none exist. + */ + hasAny(...keys) { + return keys.some((key) => super.has(key)); + } + first(amount) { + if (amount === void 0) + return this.values().next().value; + if (amount < 0) + return this.last(amount * -1); + amount = Math.min(this.size, amount); + const iter = this.values(); + return Array.from({ length: amount }, () => iter.next().value); + } + firstKey(amount) { + if (amount === void 0) + return this.keys().next().value; + if (amount < 0) + return this.lastKey(amount * -1); + amount = Math.min(this.size, amount); + const iter = this.keys(); + return Array.from({ length: amount }, () => iter.next().value); + } + last(amount) { + const arr = [...this.values()]; + if (amount === void 0) + return arr[arr.length - 1]; + if (amount < 0) + return this.first(amount * -1); + if (!amount) + return []; + return arr.slice(-amount); + } + lastKey(amount) { + const arr = [...this.keys()]; + if (amount === void 0) + return arr[arr.length - 1]; + if (amount < 0) + return this.firstKey(amount * -1); + if (!amount) + return []; + return arr.slice(-amount); + } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the item at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the element to obtain + */ + at(index) { + index = Math.floor(index); + const arr = [...this.values()]; + return arr.at(index); + } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the key at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the key to obtain + */ + keyAt(index) { + index = Math.floor(index); + const arr = [...this.keys()]; + return arr.at(index); + } + random(amount) { + const arr = [...this.values()]; + if (amount === void 0) + return arr[Math.floor(Math.random() * arr.length)]; + if (!arr.length || !amount) + return []; + return Array.from( + { length: Math.min(amount, arr.length) }, + () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0] + ); + } + randomKey(amount) { + const arr = [...this.keys()]; + if (amount === void 0) + return arr[Math.floor(Math.random() * arr.length)]; + if (!arr.length || !amount) + return []; + return Array.from( + { length: Math.min(amount, arr.length) }, + () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0] + ); + } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()} + * but returns a Collection instead of an Array. + */ + reverse() { + const entries = [...this.entries()].reverse(); + this.clear(); + for (const [key, value] of entries) + this.set(key, value); + return this; + } + find(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return val; + } + return void 0; + } + findKey(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return key; + } + return void 0; + } + sweep(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const previousSize = this.size; + for (const [key, val] of this) { + if (fn(val, key, this)) + this.delete(key); + } + return previousSize - this.size; + } + filter(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const results = new this.constructor[Symbol.species](); + for (const [key, val] of this) { + if (fn(val, key, this)) + results.set(key, val); + } + return results; + } + partition(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const results = [ + new this.constructor[Symbol.species](), + new this.constructor[Symbol.species]() + ]; + for (const [key, val] of this) { + if (fn(val, key, this)) { + results[0].set(key, val); + } else { + results[1].set(key, val); + } + } + return results; + } + flatMap(fn, thisArg) { + const collections = this.map(fn, thisArg); + return new this.constructor[Symbol.species]().concat(...collections); + } + map(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const iter = this.entries(); + return Array.from({ length: this.size }, () => { + const [key, value] = iter.next().value; + return fn(value, key, this); + }); + } + mapValues(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const coll = new this.constructor[Symbol.species](); + for (const [key, val] of this) + coll.set(key, fn(val, key, this)); + return coll; + } + some(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return true; + } + return false; + } + every(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (!fn(val, key, this)) + return false; + } + return true; + } + /** + * Applies a function to produce a single value. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}. + * + * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param initialValue - Starting value for the accumulator + * @example + * ```ts + * collection.reduce((acc, guild) => acc + guild.memberCount, 0); + * ``` + */ + reduce(fn, initialValue) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + let accumulator; + const iterator = this.entries(); + if (initialValue === void 0) { + if (this.size === 0) + throw new TypeError("Reduce of empty collection with no initial value"); + accumulator = iterator.next().value[1]; + } else { + accumulator = initialValue; + } + for (const [key, value] of iterator) { + accumulator = fn(accumulator, value, key, this); + } + return accumulator; + } + each(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, value] of this) { + fn(value, key, this); + } + return this; + } + tap(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + fn(this); + return this; + } + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ + clone() { + return new this.constructor[Symbol.species](this); + } + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * + * @param collections - Collections to merge + * @example + * ```ts + * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + * ``` + */ + concat(...collections) { + const newColl = this.clone(); + for (const coll of collections) { + for (const [key, val] of coll) + newColl.set(key, val); + } + return newColl; + } + /** + * Checks if this collection shares identical items with another. + * This is different to checking for equality using equal-signs, because + * the collections may be different objects, but contain the same data. + * + * @param collection - Collection to compare with + * @returns Whether the collections have identical contents + */ + equals(collection) { + if (!collection) + return false; + if (this === collection) + return true; + if (this.size !== collection.size) + return false; + for (const [key, value] of this) { + if (!collection.has(key) || value !== collection.get(key)) { + return false; + } + } + return true; + } + /** + * The sort method sorts the items of a collection in place and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @example + * ```ts + * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ + sort(compareFunction = _Collection.defaultSort) { + const entries = [...this.entries()]; + entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0])); + super.clear(); + for (const [key, value] of entries) { + super.set(key, value); + } + return this; + } + /** + * The intersect method returns a new structure containing items where the keys and values are present in both original structures. + * + * @param other - The other Collection to filter against + */ + intersect(other) { + const coll = new this.constructor[Symbol.species](); + for (const [key, value] of other) { + if (this.has(key) && Object.is(value, this.get(key))) { + coll.set(key, value); + } + } + return coll; + } + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ + subtract(other) { + const coll = new this.constructor[Symbol.species](); + for (const [key, value] of this) { + if (!other.has(key) || !Object.is(value, other.get(key))) { + coll.set(key, value); + } + } + return coll; + } + /** + * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. + * + * @param other - The other Collection to filter against + */ + difference(other) { + const coll = new this.constructor[Symbol.species](); + for (const [key, value] of other) { + if (!this.has(key)) + coll.set(key, value); + } + for (const [key, value] of this) { + if (!other.has(key)) + coll.set(key, value); + } + return coll; + } + /** + * Merges two Collections together into a new Collection. + * + * @param other - The other Collection to merge with + * @param whenInSelf - Function getting the result if the entry only exists in this Collection + * @param whenInOther - Function getting the result if the entry only exists in the other Collection + * @param whenInBoth - Function getting the result if the entry exists in both Collections + * @example + * ```ts + * // Sums up the entries in two collections. + * coll.merge( + * other, + * x => ({ keep: true, value: x }), + * y => ({ keep: true, value: y }), + * (x, y) => ({ keep: true, value: x + y }), + * ); + * ``` + * @example + * ```ts + * // Intersects two collections in a left-biased manner. + * coll.merge( + * other, + * x => ({ keep: false }), + * y => ({ keep: false }), + * (x, _) => ({ keep: true, value: x }), + * ); + * ``` + */ + merge(other, whenInSelf, whenInOther, whenInBoth) { + const coll = new this.constructor[Symbol.species](); + const keys = /* @__PURE__ */ new Set([...this.keys(), ...other.keys()]); + for (const key of keys) { + const hasInSelf = this.has(key); + const hasInOther = other.has(key); + if (hasInSelf && hasInOther) { + const result = whenInBoth(this.get(key), other.get(key), key); + if (result.keep) + coll.set(key, result.value); + } else if (hasInSelf) { + const result = whenInSelf(this.get(key), key); + if (result.keep) + coll.set(key, result.value); + } else if (hasInOther) { + const result = whenInOther(other.get(key), key); + if (result.keep) + coll.set(key, result.value); + } + } + return coll; + } + /** + * The sorted method sorts the items of a collection and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, + * according to the string conversion of each element. + * @example + * ```ts + * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ + sorted(compareFunction = _Collection.defaultSort) { + return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk)); + } + toJSON() { + return [...this.values()]; + } + static defaultSort(firstValue, secondValue) { + return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1; + } + /** + * Creates a Collection from a list of entries. + * + * @param entries - The list of entries + * @param combine - Function to combine an existing entry with a new one + * @example + * ```ts + * Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y); + * // returns Collection { "a" => 3, "b" => 2 } + * ``` + */ + static combineEntries(entries, combine) { + const coll = new _Collection(); + for (const [key, value] of entries) { + if (coll.has(key)) { + coll.set(key, combine(coll.get(key), value, key)); + } else { + coll.set(key, value); + } + } + return coll; + } +}; + +// src/index.ts +var version = "1.5.3"; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Collection, + version +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/collection/dist/index.js.map b/node_modules/@discordjs/collection/dist/index.js.map new file mode 100644 index 0000000..247240c --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/collection.ts"],"sourcesContent":["export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.5.3' as string;\n","/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((key) => super.has(key));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((key) => super.has(key));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (amount === undefined) return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (amount === undefined) return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tconst iterator = this.entries();\n\t\tif (initialValue === undefined) {\n\t\t\tif (this.size === 0) throw new TypeError('Reduce of empty collection with no initial value');\n\t\t\taccumulator = iterator.next().value[1];\n\t\t} else {\n\t\t\taccumulator = initialValue;\n\t\t}\n\n\t\tfor (const [key, value] of iterator) {\n\t\t\taccumulator = fn(accumulator, value, key, this);\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\n\t\tfor (const [key, value] of this) {\n\t\t\tfn(value, key, this);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [key, value] of entries) {\n\t\t\tsuper.set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (this.has(key) && Object.is(value, this.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key) || !Object.is(value, other.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (!this.has(key)) coll.set(key, value);\n\t\t}\n\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key)) coll.set(key, value);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\n\t\tfor (const key of keys) {\n\t\t\tconst hasInSelf = this.has(key);\n\t\t\tconst hasInOther = other.has(key);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst result = whenInBoth(this.get(key)!, other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst result = whenInSelf(this.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst result = whenInOther(other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (coll.has(key)) {\n\t\t\t\tcoll.set(key, combine(coll.get(key)!, value, key));\n\t\t\t} else {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqCO,IAAM,aAAN,MAAM,oBAAyB,IAAU;AAAA,EArChD,OAqCgD;AAAA;AAAA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AAI,OAAO,GAAG,CAAC;AAAA,MAClD,OAAO;AACN,aAAK,IAAI,KAAK,KAAK;AAAA,MACpB;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;;;AD9yBO,IAAM,UAAU;","names":[]} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/dist/index.mjs b/node_modules/@discordjs/collection/dist/index.mjs new file mode 100644 index 0000000..c31c9ee --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.mjs @@ -0,0 +1,517 @@ +var __defProp = Object.defineProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + +// src/collection.ts +var Collection = class _Collection extends Map { + static { + __name(this, "Collection"); + } + /** + * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator. + * + * @param key - The key to get if it exists, or set otherwise + * @param defaultValueGenerator - A function that generates the default value + * @example + * ```ts + * collection.ensure(guildId, () => defaultGuildConfig); + * ``` + */ + ensure(key, defaultValueGenerator) { + if (this.has(key)) + return this.get(key); + if (typeof defaultValueGenerator !== "function") + throw new TypeError(`${defaultValueGenerator} is not a function`); + const defaultValue = defaultValueGenerator(key, this); + this.set(key, defaultValue); + return defaultValue; + } + /** + * Checks if all of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if all of the elements exist, `false` if at least one does not exist. + */ + hasAll(...keys) { + return keys.every((key) => super.has(key)); + } + /** + * Checks if any of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if any of the elements exist, `false` if none exist. + */ + hasAny(...keys) { + return keys.some((key) => super.has(key)); + } + first(amount) { + if (amount === void 0) + return this.values().next().value; + if (amount < 0) + return this.last(amount * -1); + amount = Math.min(this.size, amount); + const iter = this.values(); + return Array.from({ length: amount }, () => iter.next().value); + } + firstKey(amount) { + if (amount === void 0) + return this.keys().next().value; + if (amount < 0) + return this.lastKey(amount * -1); + amount = Math.min(this.size, amount); + const iter = this.keys(); + return Array.from({ length: amount }, () => iter.next().value); + } + last(amount) { + const arr = [...this.values()]; + if (amount === void 0) + return arr[arr.length - 1]; + if (amount < 0) + return this.first(amount * -1); + if (!amount) + return []; + return arr.slice(-amount); + } + lastKey(amount) { + const arr = [...this.keys()]; + if (amount === void 0) + return arr[arr.length - 1]; + if (amount < 0) + return this.firstKey(amount * -1); + if (!amount) + return []; + return arr.slice(-amount); + } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the item at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the element to obtain + */ + at(index) { + index = Math.floor(index); + const arr = [...this.values()]; + return arr.at(index); + } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the key at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the key to obtain + */ + keyAt(index) { + index = Math.floor(index); + const arr = [...this.keys()]; + return arr.at(index); + } + random(amount) { + const arr = [...this.values()]; + if (amount === void 0) + return arr[Math.floor(Math.random() * arr.length)]; + if (!arr.length || !amount) + return []; + return Array.from( + { length: Math.min(amount, arr.length) }, + () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0] + ); + } + randomKey(amount) { + const arr = [...this.keys()]; + if (amount === void 0) + return arr[Math.floor(Math.random() * arr.length)]; + if (!arr.length || !amount) + return []; + return Array.from( + { length: Math.min(amount, arr.length) }, + () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0] + ); + } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()} + * but returns a Collection instead of an Array. + */ + reverse() { + const entries = [...this.entries()].reverse(); + this.clear(); + for (const [key, value] of entries) + this.set(key, value); + return this; + } + find(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return val; + } + return void 0; + } + findKey(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return key; + } + return void 0; + } + sweep(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const previousSize = this.size; + for (const [key, val] of this) { + if (fn(val, key, this)) + this.delete(key); + } + return previousSize - this.size; + } + filter(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const results = new this.constructor[Symbol.species](); + for (const [key, val] of this) { + if (fn(val, key, this)) + results.set(key, val); + } + return results; + } + partition(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const results = [ + new this.constructor[Symbol.species](), + new this.constructor[Symbol.species]() + ]; + for (const [key, val] of this) { + if (fn(val, key, this)) { + results[0].set(key, val); + } else { + results[1].set(key, val); + } + } + return results; + } + flatMap(fn, thisArg) { + const collections = this.map(fn, thisArg); + return new this.constructor[Symbol.species]().concat(...collections); + } + map(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const iter = this.entries(); + return Array.from({ length: this.size }, () => { + const [key, value] = iter.next().value; + return fn(value, key, this); + }); + } + mapValues(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + const coll = new this.constructor[Symbol.species](); + for (const [key, val] of this) + coll.set(key, fn(val, key, this)); + return coll; + } + some(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (fn(val, key, this)) + return true; + } + return false; + } + every(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, val] of this) { + if (!fn(val, key, this)) + return false; + } + return true; + } + /** + * Applies a function to produce a single value. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}. + * + * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param initialValue - Starting value for the accumulator + * @example + * ```ts + * collection.reduce((acc, guild) => acc + guild.memberCount, 0); + * ``` + */ + reduce(fn, initialValue) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + let accumulator; + const iterator = this.entries(); + if (initialValue === void 0) { + if (this.size === 0) + throw new TypeError("Reduce of empty collection with no initial value"); + accumulator = iterator.next().value[1]; + } else { + accumulator = initialValue; + } + for (const [key, value] of iterator) { + accumulator = fn(accumulator, value, key, this); + } + return accumulator; + } + each(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, value] of this) { + fn(value, key, this); + } + return this; + } + tap(fn, thisArg) { + if (typeof fn !== "function") + throw new TypeError(`${fn} is not a function`); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + fn(this); + return this; + } + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ + clone() { + return new this.constructor[Symbol.species](this); + } + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * + * @param collections - Collections to merge + * @example + * ```ts + * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + * ``` + */ + concat(...collections) { + const newColl = this.clone(); + for (const coll of collections) { + for (const [key, val] of coll) + newColl.set(key, val); + } + return newColl; + } + /** + * Checks if this collection shares identical items with another. + * This is different to checking for equality using equal-signs, because + * the collections may be different objects, but contain the same data. + * + * @param collection - Collection to compare with + * @returns Whether the collections have identical contents + */ + equals(collection) { + if (!collection) + return false; + if (this === collection) + return true; + if (this.size !== collection.size) + return false; + for (const [key, value] of this) { + if (!collection.has(key) || value !== collection.get(key)) { + return false; + } + } + return true; + } + /** + * The sort method sorts the items of a collection in place and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @example + * ```ts + * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ + sort(compareFunction = _Collection.defaultSort) { + const entries = [...this.entries()]; + entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0])); + super.clear(); + for (const [key, value] of entries) { + super.set(key, value); + } + return this; + } + /** + * The intersect method returns a new structure containing items where the keys and values are present in both original structures. + * + * @param other - The other Collection to filter against + */ + intersect(other) { + const coll = new this.constructor[Symbol.species](); + for (const [key, value] of other) { + if (this.has(key) && Object.is(value, this.get(key))) { + coll.set(key, value); + } + } + return coll; + } + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ + subtract(other) { + const coll = new this.constructor[Symbol.species](); + for (const [key, value] of this) { + if (!other.has(key) || !Object.is(value, other.get(key))) { + coll.set(key, value); + } + } + return coll; + } + /** + * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. + * + * @param other - The other Collection to filter against + */ + difference(other) { + const coll = new this.constructor[Symbol.species](); + for (const [key, value] of other) { + if (!this.has(key)) + coll.set(key, value); + } + for (const [key, value] of this) { + if (!other.has(key)) + coll.set(key, value); + } + return coll; + } + /** + * Merges two Collections together into a new Collection. + * + * @param other - The other Collection to merge with + * @param whenInSelf - Function getting the result if the entry only exists in this Collection + * @param whenInOther - Function getting the result if the entry only exists in the other Collection + * @param whenInBoth - Function getting the result if the entry exists in both Collections + * @example + * ```ts + * // Sums up the entries in two collections. + * coll.merge( + * other, + * x => ({ keep: true, value: x }), + * y => ({ keep: true, value: y }), + * (x, y) => ({ keep: true, value: x + y }), + * ); + * ``` + * @example + * ```ts + * // Intersects two collections in a left-biased manner. + * coll.merge( + * other, + * x => ({ keep: false }), + * y => ({ keep: false }), + * (x, _) => ({ keep: true, value: x }), + * ); + * ``` + */ + merge(other, whenInSelf, whenInOther, whenInBoth) { + const coll = new this.constructor[Symbol.species](); + const keys = /* @__PURE__ */ new Set([...this.keys(), ...other.keys()]); + for (const key of keys) { + const hasInSelf = this.has(key); + const hasInOther = other.has(key); + if (hasInSelf && hasInOther) { + const result = whenInBoth(this.get(key), other.get(key), key); + if (result.keep) + coll.set(key, result.value); + } else if (hasInSelf) { + const result = whenInSelf(this.get(key), key); + if (result.keep) + coll.set(key, result.value); + } else if (hasInOther) { + const result = whenInOther(other.get(key), key); + if (result.keep) + coll.set(key, result.value); + } + } + return coll; + } + /** + * The sorted method sorts the items of a collection and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, + * according to the string conversion of each element. + * @example + * ```ts + * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ + sorted(compareFunction = _Collection.defaultSort) { + return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk)); + } + toJSON() { + return [...this.values()]; + } + static defaultSort(firstValue, secondValue) { + return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1; + } + /** + * Creates a Collection from a list of entries. + * + * @param entries - The list of entries + * @param combine - Function to combine an existing entry with a new one + * @example + * ```ts + * Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y); + * // returns Collection { "a" => 3, "b" => 2 } + * ``` + */ + static combineEntries(entries, combine) { + const coll = new _Collection(); + for (const [key, value] of entries) { + if (coll.has(key)) { + coll.set(key, combine(coll.get(key), value, key)); + } else { + coll.set(key, value); + } + } + return coll; + } +}; + +// src/index.ts +var version = "1.5.3"; +export { + Collection, + version +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/collection/dist/index.mjs.map b/node_modules/@discordjs/collection/dist/index.mjs.map new file mode 100644 index 0000000..fcf72ab --- /dev/null +++ b/node_modules/@discordjs/collection/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/collection.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((key) => super.has(key));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((key) => super.has(key));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (amount === undefined) return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (amount === undefined) return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tconst iterator = this.entries();\n\t\tif (initialValue === undefined) {\n\t\t\tif (this.size === 0) throw new TypeError('Reduce of empty collection with no initial value');\n\t\t\taccumulator = iterator.next().value[1];\n\t\t} else {\n\t\t\taccumulator = initialValue;\n\t\t}\n\n\t\tfor (const [key, value] of iterator) {\n\t\t\taccumulator = fn(accumulator, value, key, this);\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\n\t\tfor (const [key, value] of this) {\n\t\t\tfn(value, key, this);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [key, value] of entries) {\n\t\t\tsuper.set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (this.has(key) && Object.is(value, this.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key) || !Object.is(value, other.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (!this.has(key)) coll.set(key, value);\n\t\t}\n\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key)) coll.set(key, value);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\n\t\tfor (const key of keys) {\n\t\t\tconst hasInSelf = this.has(key);\n\t\t\tconst hasInOther = other.has(key);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst result = whenInBoth(this.get(key)!, other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst result = whenInSelf(this.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst result = whenInOther(other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (coll.has(key)) {\n\t\t\t\tcoll.set(key, combine(coll.get(key)!, value, key));\n\t\t\t} else {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n","export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.5.3' as string;\n"],"mappings":";;;;AAqCO,IAAM,aAAN,MAAM,oBAAyB,IAAU;AAAA,EArChD,OAqCgD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWxC,OAAO,KAAQ,uBAA2D;AAChF,QAAI,KAAK,IAAI,GAAG;AAAG,aAAO,KAAK,IAAI,GAAG;AACtC,QAAI,OAAO,0BAA0B;AAAY,YAAM,IAAI,UAAU,GAAG,qBAAqB,oBAAoB;AACjH,UAAM,eAAe,sBAAsB,KAAK,IAAI;AACpD,SAAK,IAAI,KAAK,YAAY;AAC1B,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,MAAM,CAAC,QAAQ,MAAM,IAAI,GAAG,CAAC;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,KAAK,CAAC,QAAQ,MAAM,IAAI,GAAG,CAAC;AAAA,EACzC;AAAA,EAUO,MAAM,QAAsC;AAClD,QAAI,WAAW;AAAW,aAAO,KAAK,OAAO,EAAE,KAAK,EAAE;AACtD,QAAI,SAAS;AAAG,aAAO,KAAK,KAAK,SAAS,EAAE;AAC5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,gBAAgB,IAAI,IAAI,IAAI,EAAE,CAAC;AAAA,EAC3G;AAAA,EAEO,SAAS;AAEf,WAAO,CAAC,GAAG,KAAK,OAAO,CAAC;AAAA,EACzB;AAAA,EAEA,OAAe,YAAe,YAAe,aAAwB;AACpE,WAAO,OAAO,aAAa,WAAW,KAAK,OAAO,eAAe,WAAW,IAAI;AAAA,EACjF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,OAAc,eACb,SACA,SACmB;AACnB,UAAM,OAAO,IAAI,YAAiB;AAClC,eAAW,CAAC,KAAK,KAAK,KAAK,SAAS;AACnC,UAAI,KAAK,IAAI,GAAG,GAAG;AAClB,aAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,GAAG,GAAI,OAAO,GAAG,CAAC;AAAA,MAClD,OAAO;AACN,aAAK,IAAI,KAAK,KAAK;AAAA,MACpB;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;;;AC9yBO,IAAM,UAAU;","names":[]} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/package.json b/node_modules/@discordjs/collection/package.json new file mode 100644 index 0000000..81e2418 --- /dev/null +++ b/node_modules/@discordjs/collection/package.json @@ -0,0 +1,76 @@ +{ + "name": "@discordjs/collection", + "version": "1.5.3", + "description": "Utility data structure used in discord.js", + "scripts": { + "test": "vitest run", + "build": "tsup", + "build:docs": "tsc -p tsconfig.docs.json", + "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", + "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", + "fmt": "yarn format", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", + "prepack": "yarn lint && yarn test && yarn build", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/collection/*'", + "release": "cliff-jumper" + }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "directories": { + "lib": "src", + "test": "__tests__" + }, + "files": [ + "dist" + ], + "contributors": [ + "Crawl ", + "Amish Shah ", + "SpaceEEC ", + "Vlad Frangu ", + "Aura Román " + ], + "license": "Apache-2.0", + "keywords": [ + "map", + "collection", + "utility" + ], + "repository": { + "type": "git", + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/collection" + }, + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" + }, + "homepage": "https://discord.js.org", + "devDependencies": { + "@favware/cliff-jumper": "^2.1.1", + "@microsoft/api-extractor": "^7.36.4", + "@types/node": "16.18.40", + "@vitest/coverage-v8": "^0.34.2", + "cross-env": "^7.0.3", + "esbuild-plugin-version-injector": "^1.2.0", + "eslint": "^8.47.0", + "eslint-config-neon": "^0.1.47", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsup": "^7.2.0", + "turbo": "^1.10.12", + "typescript": "^5.1.6", + "vitest": "^0.34.2" + }, + "engines": { + "node": ">=16.11.0" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/node_modules/@discordjs/formatters/LICENSE b/node_modules/@discordjs/formatters/LICENSE new file mode 100644 index 0000000..e2baac1 --- /dev/null +++ b/node_modules/@discordjs/formatters/LICENSE @@ -0,0 +1,191 @@ + 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 + + Copyright 2021 Noel Buechler + Copyright 2021 Vlad Frangu + + 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/@discordjs/formatters/README.md b/node_modules/@discordjs/formatters/README.md new file mode 100644 index 0000000..65ad4b0 --- /dev/null +++ b/node_modules/@discordjs/formatters/README.md @@ -0,0 +1,82 @@ +
+
+

+ discord.js +

+
+

+ Discord server + npm version + npm downloads + Build status + Code coverage +

+

+ Vercel + Cloudflare Workers +

+
+ +## About + +`@discordjs/formatters` is a collection of functions for formatting strings to be used on Discord. + +## Installation + +**Node.js 16.11.0 or newer is required.** + +```sh +npm install @discordjs/formatters +yarn add @discordjs/formatters +pnpm add @discordjs/formatters +bun add @discordjs/formatters +``` + +## Example usage + +````ts +import { codeBlock } from '@discordjs/formatters'; + +const formattedCode = codeBlock('hello world!'); +console.log(formattedCode); + +// Prints: +// ``` +// hello world! +// ``` +```` + +## Links + +- [Website][website] ([source][website-source]) +- [Documentation][documentation] +- [Guide][guide] ([source][guide-source]) + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. +- [discord.js Discord server][discord] +- [Discord API Discord server][discord-api] +- [GitHub][source] +- [npm][npm] +- [Related libraries][related-libs] + +## Contributing + +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. + +## Help + +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. + +[website]: https://discord.js.org +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/docs/packages/formatters/stable +[guide]: https://discordjs.guide/ +[guide-source]: https://github.com/discordjs/guide +[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html +[discord]: https://discord.gg/djs +[discord-api]: https://discord.gg/discord-api +[source]: https://github.com/discordjs/discord.js/tree/main/packages/formatters +[npm]: https://www.npmjs.com/package/@discordjs/formatters +[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries +[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md diff --git a/node_modules/@discordjs/formatters/dist/index.d.mts b/node_modules/@discordjs/formatters/dist/index.d.mts new file mode 100644 index 0000000..0240f6b --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.d.mts @@ -0,0 +1,586 @@ +import { URL } from 'node:url'; +import { Snowflake } from 'discord-api-types/globals'; + +/** + * The options that affect what will be escaped. + */ +interface EscapeMarkdownOptions { + /** + * Whether to escape bold text. + * + * @defaultValue `true` + */ + bold?: boolean; + /** + * Whether to escape bulleted lists. + * + * @defaultValue `false` + */ + bulletedList?: boolean; + /** + * Whether to escape code blocks. + * + * @defaultValue `true` + */ + codeBlock?: boolean; + /** + * Whether to escape text inside code blocks. + * + * @defaultValue `true` + */ + codeBlockContent?: boolean; + /** + * Whether to escape `\`. + * + * @defaultValue `true` + */ + escape?: boolean; + /** + * Whether to escape headings. + * + * @defaultValue `false` + */ + heading?: boolean; + /** + * Whether to escape inline code. + * + * @defaultValue `true` + */ + inlineCode?: boolean; + /** + * Whether to escape text inside inline code. + * + * @defaultValue `true` + */ + inlineCodeContent?: boolean; + /** + * Whether to escape italics. + * + * @defaultValue `true` + */ + italic?: boolean; + /** + * Whether to escape masked links. + * + * @defaultValue `false` + */ + maskedLink?: boolean; + /** + * Whether to escape numbered lists. + * + * @defaultValue `false` + */ + numberedList?: boolean; + /** + * Whether to escape spoilers. + * + * @defaultValue `true` + */ + spoiler?: boolean; + /** + * Whether to escape strikethroughs. + * + * @defaultValue `true` + */ + strikethrough?: boolean; + /** + * Whether to escape underlines. + * + * @defaultValue `true` + */ + underline?: boolean; +} +/** + * Escapes any Discord-flavored markdown in a string. + * + * @param text - Content to escape + * @param options - Options for escaping the markdown + */ +declare function escapeMarkdown(text: string, options?: EscapeMarkdownOptions): string; +/** + * Escapes code block markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeCodeBlock(text: string): string; +/** + * Escapes inline code markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeInlineCode(text: string): string; +/** + * Escapes italic markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeItalic(text: string): string; +/** + * Escapes bold markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeBold(text: string): string; +/** + * Escapes underline markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeUnderline(text: string): string; +/** + * Escapes strikethrough markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeStrikethrough(text: string): string; +/** + * Escapes spoiler markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeSpoiler(text: string): string; +/** + * Escapes escape characters in a string. + * + * @param text - Content to escape + */ +declare function escapeEscape(text: string): string; +/** + * Escapes heading characters in a string. + * + * @param text - Content to escape + */ +declare function escapeHeading(text: string): string; +/** + * Escapes bulleted list characters in a string. + * + * @param text - Content to escape + */ +declare function escapeBulletedList(text: string): string; +/** + * Escapes numbered list characters in a string. + * + * @param text - Content to escape + */ +declare function escapeNumberedList(text: string): string; +/** + * Escapes masked link characters in a string. + * + * @param text - Content to escape + */ +declare function escapeMaskedLink(text: string): string; + +/** + * Wraps the content inside a code block with no language. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function codeBlock(content: Content): `\`\`\`\n${Content}\n\`\`\``; +/** + * Wraps the content inside a code block with the specified language. + * + * @typeParam Language - This is inferred by the supplied language + * @typeParam Content - This is inferred by the supplied content + * @param language - The language for the code block + * @param content - The content to wrap + */ +declare function codeBlock(language: Language, content: Content): `\`\`\`${Language}\n${Content}\n\`\`\``; +/** + * Wraps the content inside \`backticks\` which formats it as inline code. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function inlineCode(content: Content): `\`${Content}\``; +/** + * Formats the content into italic text. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function italic(content: Content): `_${Content}_`; +/** + * Formats the content into bold text. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function bold(content: Content): `**${Content}**`; +/** + * Formats the content into underscored text. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function underscore(content: Content): `__${Content}__`; +/** + * Formats the content into strike-through text. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function strikethrough(content: Content): `~~${Content}~~`; +/** + * Formats the content into a quote. + * + * @remarks This needs to be at the start of the line for Discord to format it. + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function quote(content: Content): `> ${Content}`; +/** + * Formats the content into a block quote. + * + * @remarks This needs to be at the start of the line for Discord to format it. + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function blockQuote(content: Content): `>>> ${Content}`; +/** + * Wraps the URL into `<>` which stops it from embedding. + * + * @typeParam Content - This is inferred by the supplied content + * @param url - The URL to wrap + */ +declare function hideLinkEmbed(url: Content): `<${Content}>`; +/** + * Wraps the URL into `<>` which stops it from embedding. + * + * @param url - The URL to wrap + */ +declare function hideLinkEmbed(url: URL): `<${string}>`; +/** + * Formats the content and the URL into a masked URL. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to display + * @param url - The URL the content links to + */ +declare function hyperlink(content: Content, url: URL): `[${Content}](${string})`; +/** + * Formats the content and the URL into a masked URL. + * + * @typeParam Content - This is inferred by the supplied content + * @typeParam Url - This is inferred by the supplied URL + * @param content - The content to display + * @param url - The URL the content links to + */ +declare function hyperlink(content: Content, url: Url): `[${Content}](${Url})`; +/** + * Formats the content and the URL into a masked URL with a custom tooltip. + * + * @typeParam Content - This is inferred by the supplied content + * @typeParam Title - This is inferred by the supplied title + * @param content - The content to display + * @param url - The URL the content links to + * @param title - The title shown when hovering on the masked link + */ +declare function hyperlink(content: Content, url: URL, title: Title): `[${Content}](${string} "${Title}")`; +/** + * Formats the content and the URL into a masked URL with a custom tooltip. + * + * @typeParam Content - This is inferred by the supplied content + * @typeParam Url - This is inferred by the supplied URL + * @typeParam Title - This is inferred by the supplied title + * @param content - The content to display + * @param url - The URL the content links to + * @param title - The title shown when hovering on the masked link + */ +declare function hyperlink(content: Content, url: Url, title: Title): `[${Content}](${Url} "${Title}")`; +/** + * Formats the content into a spoiler. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function spoiler(content: Content): `||${Content}||`; +/** + * Formats a user id into a user mention. + * + * @typeParam UserId - This is inferred by the supplied user id + * @param userId - The user id to format + */ +declare function userMention(userId: UserId): `<@${UserId}>`; +/** + * Formats a channel id into a channel mention. + * + * @typeParam ChannelId - This is inferred by the supplied channel id + * @param channelId - The channel id to format + */ +declare function channelMention(channelId: ChannelId): `<#${ChannelId}>`; +/** + * Formats a role id into a role mention. + * + * @typeParam RoleId - This is inferred by the supplied role id + * @param roleId - The role id to format + */ +declare function roleMention(roleId: RoleId): `<@&${RoleId}>`; +/** + * Formats an application command name, subcommand group name, subcommand name, and id into an application command mention. + * + * @typeParam CommandName - This is inferred by the supplied command name + * @typeParam SubcommandGroupName - This is inferred by the supplied subcommand group name + * @typeParam SubcommandName - This is inferred by the supplied subcommand name + * @typeParam CommandId - This is inferred by the supplied command id + * @param commandName - The application command name to format + * @param subcommandGroupName - The subcommand group name to format + * @param subcommandName - The subcommand name to format + * @param commandId - The application command id to format + */ +declare function chatInputApplicationCommandMention(commandName: CommandName, subcommandGroupName: SubcommandGroupName, subcommandName: SubcommandName, commandId: CommandId): ``; +/** + * Formats an application command name, subcommand name, and id into an application command mention. + * + * @typeParam CommandName - This is inferred by the supplied command name + * @typeParam SubcommandName - This is inferred by the supplied subcommand name + * @typeParam CommandId - This is inferred by the supplied command id + * @param commandName - The application command name to format + * @param subcommandName - The subcommand name to format + * @param commandId - The application command id to format + */ +declare function chatInputApplicationCommandMention(commandName: CommandName, subcommandName: SubcommandName, commandId: CommandId): ``; +/** + * Formats an application command name and id into an application command mention. + * + * @typeParam CommandName - This is inferred by the supplied command name + * @typeParam CommandId - This is inferred by the supplied command id + * @param commandName - The application command name to format + * @param commandId - The application command id to format + */ +declare function chatInputApplicationCommandMention(commandName: CommandName, commandId: CommandId): ``; +/** + * Formats a non-animated emoji id into a fully qualified emoji identifier. + * + * @typeParam EmojiId - This is inferred by the supplied emoji id + * @param emojiId - The emoji id to format + */ +declare function formatEmoji(emojiId: EmojiId, animated?: false): `<:_:${EmojiId}>`; +/** + * Formats an animated emoji id into a fully qualified emoji identifier. + * + * @typeParam EmojiId - This is inferred by the supplied emoji id + * @param emojiId - The emoji id to format + * @param animated - Whether the emoji is animated + */ +declare function formatEmoji(emojiId: EmojiId, animated?: true): ``; +/** + * Formats an emoji id into a fully qualified emoji identifier. + * + * @typeParam EmojiId - This is inferred by the supplied emoji id + * @param emojiId - The emoji id to format + * @param animated - Whether the emoji is animated + */ +declare function formatEmoji(emojiId: EmojiId, animated?: boolean): `<:_:${EmojiId}>` | ``; +/** + * Formats a channel link for a direct message channel. + * + * @typeParam ChannelId - This is inferred by the supplied channel id + * @param channelId - The channel's id + */ +declare function channelLink(channelId: ChannelId): `https://discord.com/channels/@me/${ChannelId}`; +/** + * Formats a channel link for a guild channel. + * + * @typeParam ChannelId - This is inferred by the supplied channel id + * @typeParam GuildId - This is inferred by the supplied guild id + * @param channelId - The channel's id + * @param guildId - The guild's id + */ +declare function channelLink(channelId: ChannelId, guildId: GuildId): `https://discord.com/channels/${GuildId}/${ChannelId}`; +/** + * Formats a message link for a direct message channel. + * + * @typeParam ChannelId - This is inferred by the supplied channel id + * @typeParam MessageId - This is inferred by the supplied message id + * @param channelId - The channel's id + * @param messageId - The message's id + */ +declare function messageLink(channelId: ChannelId, messageId: MessageId): `https://discord.com/channels/@me/${ChannelId}/${MessageId}`; +/** + * Formats a message link for a guild channel. + * + * @typeParam ChannelId - This is inferred by the supplied channel id + * @typeParam MessageId - This is inferred by the supplied message id + * @typeParam GuildId - This is inferred by the supplied guild id + * @param channelId - The channel's id + * @param messageId - The message's id + * @param guildId - The guild's id + */ +declare function messageLink(channelId: ChannelId, messageId: MessageId, guildId: GuildId): `https://discord.com/channels/${GuildId}/${ChannelId}/${MessageId}`; +/** + * The heading levels for expanded markdown. + */ +declare enum HeadingLevel { + /** + * The first heading level. + */ + One = 1, + /** + * The second heading level. + */ + Two = 2, + /** + * The third heading level. + */ + Three = 3 +} +/** + * Formats the content into a heading level. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + * @param level - The heading level + */ +declare function heading(content: Content, level?: HeadingLevel.One): `# ${Content}`; +/** + * Formats the content into a heading level. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + * @param level - The heading level + */ +declare function heading(content: Content, level: HeadingLevel.Two): `## ${Content}`; +/** + * Formats the content into a heading level. + * + * @typeParam Content - This is inferred by the supplied content + * @param content - The content to wrap + * @param level - The heading level + */ +declare function heading(content: Content, level: HeadingLevel.Three): `### ${Content}`; +/** + * A type that recursively traverses into arrays. + */ +type RecursiveArray = readonly (ItemType | RecursiveArray)[]; +/** + * Formats the elements in the array to an ordered list. + * + * @param list - The array of elements to list + * @param startNumber - The starting number for the list + */ +declare function orderedList(list: RecursiveArray, startNumber?: number): string; +/** + * Formats the elements in the array to an unordered list. + * + * @param list - The array of elements to list + */ +declare function unorderedList(list: RecursiveArray): string; +/** + * Formats a date into a short date-time string. + * + * @param date - The date to format. Defaults to the current time + */ +declare function time(date?: Date): ``; +/** + * Formats a date given a format style. + * + * @typeParam Style - This is inferred by the supplied {@link TimestampStylesString} + * @param date - The date to format + * @param style - The style to use + */ +declare function time + + diff --git a/node_modules/md5/dist/md5.min.js b/node_modules/md5/dist/md5.min.js new file mode 100644 index 0000000..250ab73 --- /dev/null +++ b/node_modules/md5/dist/md5.min.js @@ -0,0 +1,7 @@ +var MD5=function(r){function n(o){if(t[o])return t[o].exports;var e=t[o]={i:o,l:!1,exports:{}};return r[o].call(e.exports,e,e.exports,n),e.l=!0,e.exports}var t={};return n.m=r,n.c=t,n.i=function(r){return r},n.d=function(r,t,o){n.o(r,t)||Object.defineProperty(r,t,{configurable:!1,enumerable:!0,get:o})},n.n=function(r){var t=r&&r.__esModule?function(){return r.default}:function(){return r};return n.d(t,"a",t),t},n.o=function(r,n){return Object.prototype.hasOwnProperty.call(r,n)},n.p="",n(n.s=4)}([function(r,n){var t={utf8:{stringToBytes:function(r){return t.bin.stringToBytes(unescape(encodeURIComponent(r)))},bytesToString:function(r){return decodeURIComponent(escape(t.bin.bytesToString(r)))}},bin:{stringToBytes:function(r){for(var n=[],t=0;t>>24)|4278255360&(f[h]<<24|f[h]>>>8);f[s>>>5]|=128<>>9<<4)]=s;for(var p=i._ff,y=i._gg,v=i._hh,d=i._ii,h=0;h>>0,a=a+T>>>0,l=l+x>>>0,g=g+B>>>0}return n.endian([c,a,l,g])};i._ff=function(r,n,t,o,e,u,i){var f=r+(n&t|~n&o)+(e>>>0)+i;return(f<>>32-u)+n},i._gg=function(r,n,t,o,e,u,i){var f=r+(n&o|t&~o)+(e>>>0)+i;return(f<>>32-u)+n},i._hh=function(r,n,t,o,e,u,i){var f=r+(n^t^o)+(e>>>0)+i;return(f<>>32-u)+n},i._ii=function(r,n,t,o,e,u,i){var f=r+(t^(n|~o))+(e>>>0)+i;return(f<>>32-u)+n},i._blocksize=16,i._digestsize=16,r.exports=function(r,t){if(void 0===r||null===r)throw new Error("Illegal argument "+r);var o=n.wordsToBytes(i(r,t));return t&&t.asBytes?o:t&&t.asString?u.bytesToString(o):n.bytesToHex(o)}}()},function(r,n){!function(){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t={rotl:function(r,n){return r<>>32-n},rotr:function(r,n){return r<<32-n|r>>>n},endian:function(r){if(r.constructor==Number)return 16711935&t.rotl(r,8)|4278255360&t.rotl(r,24);for(var n=0;n0;r--)n.push(Math.floor(256*Math.random()));return n},bytesToWords:function(r){for(var n=[],t=0,o=0;t>>5]|=r[t]<<24-o%32;return n},wordsToBytes:function(r){for(var n=[],t=0;t<32*r.length;t+=8)n.push(r[t>>>5]>>>24-t%32&255);return n},bytesToHex:function(r){for(var n=[],t=0;t>>4).toString(16)),n.push((15&r[t]).toString(16));return n.join("")},hexToBytes:function(r){for(var n=[],t=0;t>>6*(3-u)&63)):t.push("=");return t.join("")},base64ToBytes:function(r){r=r.replace(/[^A-Z0-9+\/]/gi,"");for(var t=[],o=0,e=0;o>>6-2*e);return t}};r.exports=t}()},function(r,n){function t(r){return!!r.constructor&&"function"==typeof r.constructor.isBuffer&&r.constructor.isBuffer(r)}function o(r){return"function"==typeof r.readFloatLE&&"function"==typeof r.slice&&t(r.slice(0,0))}/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ +r.exports=function(r){return null!=r&&(t(r)||o(r)||!!r._isBuffer)}},function(r,n,t){r.exports=t(1)}]); \ No newline at end of file diff --git a/node_modules/md5/md5.js b/node_modules/md5/md5.js new file mode 100644 index 0000000..64f0be2 --- /dev/null +++ b/node_modules/md5/md5.js @@ -0,0 +1,160 @@ +(function(){ + var crypt = require('crypt'), + utf8 = require('charenc').utf8, + isBuffer = require('is-buffer'), + bin = require('charenc').bin, + + // The core + md5 = function (message, options) { + // Convert to byte array + if (message.constructor == String) + if (options && options.encoding === 'binary') + message = bin.stringToBytes(message); + else + message = utf8.stringToBytes(message); + else if (isBuffer(message)) + message = Array.prototype.slice.call(message, 0); + else if (!Array.isArray(message) && message.constructor !== Uint8Array) + message = message.toString(); + // else, assume byte array already + + var m = crypt.bytesToWords(message), + l = message.length * 8, + a = 1732584193, + b = -271733879, + c = -1732584194, + d = 271733878; + + // Swap endian + for (var i = 0; i < m.length; i++) { + m[i] = ((m[i] << 8) | (m[i] >>> 24)) & 0x00FF00FF | + ((m[i] << 24) | (m[i] >>> 8)) & 0xFF00FF00; + } + + // Padding + m[l >>> 5] |= 0x80 << (l % 32); + m[(((l + 64) >>> 9) << 4) + 14] = l; + + // Method shortcuts + var FF = md5._ff, + GG = md5._gg, + HH = md5._hh, + II = md5._ii; + + for (var i = 0; i < m.length; i += 16) { + + var aa = a, + bb = b, + cc = c, + dd = d; + + a = FF(a, b, c, d, m[i+ 0], 7, -680876936); + d = FF(d, a, b, c, m[i+ 1], 12, -389564586); + c = FF(c, d, a, b, m[i+ 2], 17, 606105819); + b = FF(b, c, d, a, m[i+ 3], 22, -1044525330); + a = FF(a, b, c, d, m[i+ 4], 7, -176418897); + d = FF(d, a, b, c, m[i+ 5], 12, 1200080426); + c = FF(c, d, a, b, m[i+ 6], 17, -1473231341); + b = FF(b, c, d, a, m[i+ 7], 22, -45705983); + a = FF(a, b, c, d, m[i+ 8], 7, 1770035416); + d = FF(d, a, b, c, m[i+ 9], 12, -1958414417); + c = FF(c, d, a, b, m[i+10], 17, -42063); + b = FF(b, c, d, a, m[i+11], 22, -1990404162); + a = FF(a, b, c, d, m[i+12], 7, 1804603682); + d = FF(d, a, b, c, m[i+13], 12, -40341101); + c = FF(c, d, a, b, m[i+14], 17, -1502002290); + b = FF(b, c, d, a, m[i+15], 22, 1236535329); + + a = GG(a, b, c, d, m[i+ 1], 5, -165796510); + d = GG(d, a, b, c, m[i+ 6], 9, -1069501632); + c = GG(c, d, a, b, m[i+11], 14, 643717713); + b = GG(b, c, d, a, m[i+ 0], 20, -373897302); + a = GG(a, b, c, d, m[i+ 5], 5, -701558691); + d = GG(d, a, b, c, m[i+10], 9, 38016083); + c = GG(c, d, a, b, m[i+15], 14, -660478335); + b = GG(b, c, d, a, m[i+ 4], 20, -405537848); + a = GG(a, b, c, d, m[i+ 9], 5, 568446438); + d = GG(d, a, b, c, m[i+14], 9, -1019803690); + c = GG(c, d, a, b, m[i+ 3], 14, -187363961); + b = GG(b, c, d, a, m[i+ 8], 20, 1163531501); + a = GG(a, b, c, d, m[i+13], 5, -1444681467); + d = GG(d, a, b, c, m[i+ 2], 9, -51403784); + c = GG(c, d, a, b, m[i+ 7], 14, 1735328473); + b = GG(b, c, d, a, m[i+12], 20, -1926607734); + + a = HH(a, b, c, d, m[i+ 5], 4, -378558); + d = HH(d, a, b, c, m[i+ 8], 11, -2022574463); + c = HH(c, d, a, b, m[i+11], 16, 1839030562); + b = HH(b, c, d, a, m[i+14], 23, -35309556); + a = HH(a, b, c, d, m[i+ 1], 4, -1530992060); + d = HH(d, a, b, c, m[i+ 4], 11, 1272893353); + c = HH(c, d, a, b, m[i+ 7], 16, -155497632); + b = HH(b, c, d, a, m[i+10], 23, -1094730640); + a = HH(a, b, c, d, m[i+13], 4, 681279174); + d = HH(d, a, b, c, m[i+ 0], 11, -358537222); + c = HH(c, d, a, b, m[i+ 3], 16, -722521979); + b = HH(b, c, d, a, m[i+ 6], 23, 76029189); + a = HH(a, b, c, d, m[i+ 9], 4, -640364487); + d = HH(d, a, b, c, m[i+12], 11, -421815835); + c = HH(c, d, a, b, m[i+15], 16, 530742520); + b = HH(b, c, d, a, m[i+ 2], 23, -995338651); + + a = II(a, b, c, d, m[i+ 0], 6, -198630844); + d = II(d, a, b, c, m[i+ 7], 10, 1126891415); + c = II(c, d, a, b, m[i+14], 15, -1416354905); + b = II(b, c, d, a, m[i+ 5], 21, -57434055); + a = II(a, b, c, d, m[i+12], 6, 1700485571); + d = II(d, a, b, c, m[i+ 3], 10, -1894986606); + c = II(c, d, a, b, m[i+10], 15, -1051523); + b = II(b, c, d, a, m[i+ 1], 21, -2054922799); + a = II(a, b, c, d, m[i+ 8], 6, 1873313359); + d = II(d, a, b, c, m[i+15], 10, -30611744); + c = II(c, d, a, b, m[i+ 6], 15, -1560198380); + b = II(b, c, d, a, m[i+13], 21, 1309151649); + a = II(a, b, c, d, m[i+ 4], 6, -145523070); + d = II(d, a, b, c, m[i+11], 10, -1120210379); + c = II(c, d, a, b, m[i+ 2], 15, 718787259); + b = II(b, c, d, a, m[i+ 9], 21, -343485551); + + a = (a + aa) >>> 0; + b = (b + bb) >>> 0; + c = (c + cc) >>> 0; + d = (d + dd) >>> 0; + } + + return crypt.endian([a, b, c, d]); + }; + + // Auxiliary functions + md5._ff = function (a, b, c, d, x, s, t) { + var n = a + (b & c | ~b & d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._gg = function (a, b, c, d, x, s, t) { + var n = a + (b & d | c & ~d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._hh = function (a, b, c, d, x, s, t) { + var n = a + (b ^ c ^ d) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + md5._ii = function (a, b, c, d, x, s, t) { + var n = a + (c ^ (b | ~d)) + (x >>> 0) + t; + return ((n << s) | (n >>> (32 - s))) + b; + }; + + // Package private blocksize + md5._blocksize = 16; + md5._digestsize = 16; + + module.exports = function (message, options) { + if (message === undefined || message === null) + throw new Error('Illegal argument ' + message); + + var digestbytes = crypt.wordsToBytes(md5(message, options)); + return options && options.asBytes ? digestbytes : + options && options.asString ? bin.bytesToString(digestbytes) : + crypt.bytesToHex(digestbytes); + }; + +})(); diff --git a/node_modules/md5/package.json b/node_modules/md5/package.json new file mode 100644 index 0000000..7618a07 --- /dev/null +++ b/node_modules/md5/package.json @@ -0,0 +1,38 @@ +{ + "name": "md5", + "description": "js function for hashing messages with MD5", + "version": "2.3.0", + "author": "Paul Vorbach (http://paul.vorba.ch)", + "contributors": [ + "salba" + ], + "tags": [ + "md5", + "hash", + "encryption", + "message digest" + ], + "repository": { + "type": "git", + "url": "git://github.com/pvorb/node-md5.git" + }, + "bugs": { + "url": "https://github.com/pvorb/node-md5/issues" + }, + "main": "md5.js", + "scripts": { + "test": "mocha", + "webpack": "webpack -p" + }, + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + }, + "devDependencies": { + "mocha": "~2.3.4", + "webpack": "~2.4.1" + }, + "optionalDependencies": {}, + "license": "BSD-3-Clause" +} diff --git a/node_modules/md5/test.js b/node_modules/md5/test.js new file mode 100644 index 0000000..db78c25 --- /dev/null +++ b/node_modules/md5/test.js @@ -0,0 +1,75 @@ +var md5 = require('./md5.js'); +var assert = require('assert'); + +describe('md5', function () { + + it('should throw an error for an undefined value', function() { + assert.throws(function() { + md5(undefined); + }); + }); + + it('should allow the hashing of the string `undefined`', function() { + assert.equal('5e543256c480ac577d30f76f9120eb74', md5('undefined')); + }); + + it('should throw an error for `null`', function() { + assert.throws(function() { + md5(null); + }); + }); + + it('should return the expected MD5 hash for "message"', function() { + assert.equal('78e731027d8fd50ed642340b7c9a63b3', md5('message')); + }); + + it('should not return the same hash for random numbers twice', function() { + var msg1 = Math.floor((Math.random() * 100000) + 1) + (new Date).getTime(); + var msg2 = Math.floor((Math.random() * 100000) + 1) + (new Date).getTime(); + + if (msg1 !== msg2) { + assert.notEqual(md5(msg1), md5(msg2)); + } else { + assert.equal(md5(msg1), md5(msg1)); + } + }); + + it('should support Node.js Buffers', function() { + var buffer = new Buffer('message áßäöü', 'utf8'); + + assert.equal(md5(buffer), md5('message áßäöü')); + }) + + it('should be able to use a binary encoded string', function() { + var hash1 = md5('abc', { asString: true }); + var hash2 = md5(hash1 + 'a', { asString: true, encoding : 'binary' }); + var hash3 = md5(hash1 + 'a', { encoding : 'binary' }); + assert.equal(hash3, '131f0ac52813044f5110e4aec638c169'); + }); + + it('should support Uint8Array', function() { + // Polyfills + if (!Array.from) { + Array.from = function(src, fn) { + var result = new Array(src.length); + for (var i = 0; i < src.length; ++i) + result[i] = fn(src[i]); + return result; + }; + } + if (!Uint8Array.from) { + Uint8Array.from = function(src) { + var result = new Uint8Array(src.length); + for (var i = 0; i < src.length; ++i) + result[i] = src[i]; + return result; + }; + } + + var message = 'foobarbaz'; + var u8arr = Uint8Array.from( + Array.from(message, function(c) { return c.charCodeAt(0); })); + var u8aHash = md5(u8arr); + assert.equal(u8aHash, md5(message)); + }); +}); diff --git a/node_modules/md5/webpack.config.js b/node_modules/md5/webpack.config.js new file mode 100644 index 0000000..310eb37 --- /dev/null +++ b/node_modules/md5/webpack.config.js @@ -0,0 +1,13 @@ +const {resolve} = require('path'); + +module.exports = { + entry: [ + './md5.js' + ], + output: { + path: resolve('./dist'), + filename: 'md5.min.js', + libraryTarget: "var", + library: "MD5" + } +}; \ No newline at end of file diff --git a/node_modules/mime-db/HISTORY.md b/node_modules/mime-db/HISTORY.md new file mode 100644 index 0000000..7436f64 --- /dev/null +++ b/node_modules/mime-db/HISTORY.md @@ -0,0 +1,507 @@ +1.52.0 / 2022-02-21 +=================== + + * Add extensions from IANA for more `image/*` types + * Add extension `.asc` to `application/pgp-keys` + * Add extensions to various XML types + * Add new upstream MIME types + +1.51.0 / 2021-11-08 +=================== + + * Add new upstream MIME types + * Mark `image/vnd.microsoft.icon` as compressible + * Mark `image/vnd.ms-dds` as compressible + +1.50.0 / 2021-09-15 +=================== + + * Add deprecated iWorks mime types and extensions + * Add new upstream MIME types + +1.49.0 / 2021-07-26 +=================== + + * Add extension `.trig` to `application/trig` + * Add new upstream MIME types + +1.48.0 / 2021-05-30 +=================== + + * Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + * Add new upstream MIME types + * Mark `text/yaml` as compressible + +1.47.0 / 2021-04-01 +=================== + + * Add new upstream MIME types + * Remove ambigious extensions from IANA for `application/*+xml` types + * Update primary extension to `.es` for `application/ecmascript` + +1.46.0 / 2021-02-13 +=================== + + * Add extension `.amr` to `audio/amr` + * Add extension `.m4s` to `video/iso.segment` + * Add extension `.opus` to `audio/ogg` + * Add new upstream MIME types + +1.45.0 / 2020-09-22 +=================== + + * Add `application/ubjson` with extension `.ubj` + * Add `image/avif` with extension `.avif` + * Add `image/ktx2` with extension `.ktx2` + * Add extension `.dbf` to `application/vnd.dbf` + * Add extension `.rar` to `application/vnd.rar` + * Add extension `.td` to `application/urc-targetdesc+xml` + * Add new upstream MIME types + * Fix extension of `application/vnd.apple.keynote` to be `.key` + +1.44.0 / 2020-04-22 +=================== + + * Add charsets from IANA + * Add extension `.cjs` to `application/node` + * Add new upstream MIME types + +1.43.0 / 2020-01-05 +=================== + + * Add `application/x-keepass2` with extension `.kdbx` + * Add extension `.mxmf` to `audio/mobile-xmf` + * Add extensions from IANA for `application/*+xml` types + * Add new upstream MIME types + +1.42.0 / 2019-09-25 +=================== + + * Add `image/vnd.ms-dds` with extension `.dds` + * Add new upstream MIME types + * Remove compressible from `multipart/mixed` + +1.41.0 / 2019-08-30 +=================== + + * Add new upstream MIME types + * Add `application/toml` with extension `.toml` + * Mark `font/ttf` as compressible + +1.40.0 / 2019-04-20 +=================== + + * Add extensions from IANA for `model/*` types + * Add `text/mdx` with extension `.mdx` + +1.39.0 / 2019-04-04 +=================== + + * Add extensions `.siv` and `.sieve` to `application/sieve` + * Add new upstream MIME types + +1.38.0 / 2019-02-04 +=================== + + * Add extension `.nq` to `application/n-quads` + * Add extension `.nt` to `application/n-triples` + * Add new upstream MIME types + * Mark `text/less` as compressible + +1.37.0 / 2018-10-19 +=================== + + * Add extensions to HEIC image types + * Add new upstream MIME types + +1.36.0 / 2018-08-20 +=================== + + * Add Apple file extensions from IANA + * Add extensions from IANA for `image/*` types + * Add new upstream MIME types + +1.35.0 / 2018-07-15 +=================== + + * Add extension `.owl` to `application/rdf+xml` + * Add new upstream MIME types + - Removes extension `.woff` from `application/font-woff` + +1.34.0 / 2018-06-03 +=================== + + * Add extension `.csl` to `application/vnd.citationstyles.style+xml` + * Add extension `.es` to `application/ecmascript` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/turtle` + * Mark all XML-derived types as compressible + +1.33.0 / 2018-02-15 +=================== + + * Add extensions from IANA for `message/*` types + * Add new upstream MIME types + * Fix some incorrect OOXML types + * Remove `application/font-woff2` + +1.32.0 / 2017-11-29 +=================== + + * Add new upstream MIME types + * Update `text/hjson` to registered `application/hjson` + * Add `text/shex` with extension `.shex` + +1.31.0 / 2017-10-25 +=================== + + * Add `application/raml+yaml` with extension `.raml` + * Add `application/wasm` with extension `.wasm` + * Add new `font` type from IANA + * Add new upstream font extensions + * Add new upstream MIME types + * Add extensions for JPEG-2000 images + +1.30.0 / 2017-08-27 +=================== + + * Add `application/vnd.ms-outlook` + * Add `application/x-arj` + * Add extension `.mjs` to `application/javascript` + * Add glTF types and extensions + * Add new upstream MIME types + * Add `text/x-org` + * Add VirtualBox MIME types + * Fix `source` records for `video/*` types that are IANA + * Update `font/opentype` to registered `font/otf` + +1.29.0 / 2017-07-10 +=================== + + * Add `application/fido.trusted-apps+json` + * Add extension `.wadl` to `application/vnd.sun.wadl+xml` + * Add new upstream MIME types + * Add `UTF-8` as default charset for `text/css` + +1.28.0 / 2017-05-14 +=================== + + * Add new upstream MIME types + * Add extension `.gz` to `application/gzip` + * Update extensions `.md` and `.markdown` to be `text/markdown` + +1.27.0 / 2017-03-16 +=================== + + * Add new upstream MIME types + * Add `image/apng` with extension `.apng` + +1.26.0 / 2017-01-14 +=================== + + * Add new upstream MIME types + * Add extension `.geojson` to `application/geo+json` + +1.25.0 / 2016-11-11 +=================== + + * Add new upstream MIME types + +1.24.0 / 2016-09-18 +=================== + + * Add `audio/mp3` + * Add new upstream MIME types + +1.23.0 / 2016-05-01 +=================== + + * Add new upstream MIME types + * Add extension `.3gpp` to `audio/3gpp` + +1.22.0 / 2016-02-15 +=================== + + * Add `text/slim` + * Add extension `.rng` to `application/xml` + * Add new upstream MIME types + * Fix extension of `application/dash+xml` to be `.mpd` + * Update primary extension to `.m4a` for `audio/mp4` + +1.21.0 / 2016-01-06 +=================== + + * Add Google document types + * Add new upstream MIME types + +1.20.0 / 2015-11-10 +=================== + + * Add `text/x-suse-ymp` + * Add new upstream MIME types + +1.19.0 / 2015-09-17 +=================== + + * Add `application/vnd.apple.pkpass` + * Add new upstream MIME types + +1.18.0 / 2015-09-03 +=================== + + * Add new upstream MIME types + +1.17.0 / 2015-08-13 +=================== + + * Add `application/x-msdos-program` + * Add `audio/g711-0` + * Add `image/vnd.mozilla.apng` + * Add extension `.exe` to `application/x-msdos-program` + +1.16.0 / 2015-07-29 +=================== + + * Add `application/vnd.uri-map` + +1.15.0 / 2015-07-13 +=================== + + * Add `application/x-httpd-php` + +1.14.0 / 2015-06-25 +=================== + + * Add `application/scim+json` + * Add `application/vnd.3gpp.ussd+xml` + * Add `application/vnd.biopax.rdf+xml` + * Add `text/x-processing` + +1.13.0 / 2015-06-07 +=================== + + * Add nginx as a source + * Add `application/x-cocoa` + * Add `application/x-java-archive-diff` + * Add `application/x-makeself` + * Add `application/x-perl` + * Add `application/x-pilot` + * Add `application/x-redhat-package-manager` + * Add `application/x-sea` + * Add `audio/x-m4a` + * Add `audio/x-realaudio` + * Add `image/x-jng` + * Add `text/mathml` + +1.12.0 / 2015-06-05 +=================== + + * Add `application/bdoc` + * Add `application/vnd.hyperdrive+json` + * Add `application/x-bdoc` + * Add extension `.rtf` to `text/rtf` + +1.11.0 / 2015-05-31 +=================== + + * Add `audio/wav` + * Add `audio/wave` + * Add extension `.litcoffee` to `text/coffeescript` + * Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data` + * Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install` + +1.10.0 / 2015-05-19 +=================== + + * Add `application/vnd.balsamiq.bmpr` + * Add `application/vnd.microsoft.portable-executable` + * Add `application/x-ns-proxy-autoconfig` + +1.9.1 / 2015-04-19 +================== + + * Remove `.json` extension from `application/manifest+json` + - This is causing bugs downstream + +1.9.0 / 2015-04-19 +================== + + * Add `application/manifest+json` + * Add `application/vnd.micro+json` + * Add `image/vnd.zbrush.pcx` + * Add `image/x-ms-bmp` + +1.8.0 / 2015-03-13 +================== + + * Add `application/vnd.citationstyles.style+xml` + * Add `application/vnd.fastcopy-disk-image` + * Add `application/vnd.gov.sk.xmldatacontainer+xml` + * Add extension `.jsonld` to `application/ld+json` + +1.7.0 / 2015-02-08 +================== + + * Add `application/vnd.gerber` + * Add `application/vnd.msa-disk-image` + +1.6.1 / 2015-02-05 +================== + + * Community extensions ownership transferred from `node-mime` + +1.6.0 / 2015-01-29 +================== + + * Add `application/jose` + * Add `application/jose+json` + * Add `application/json-seq` + * Add `application/jwk+json` + * Add `application/jwk-set+json` + * Add `application/jwt` + * Add `application/rdap+json` + * Add `application/vnd.gov.sk.e-form+xml` + * Add `application/vnd.ims.imsccv1p3` + +1.5.0 / 2014-12-30 +================== + + * Add `application/vnd.oracle.resource+json` + * Fix various invalid MIME type entries + - `application/mbox+xml` + - `application/oscp-response` + - `application/vwg-multiplexed` + - `audio/g721` + +1.4.0 / 2014-12-21 +================== + + * Add `application/vnd.ims.imsccv1p2` + * Fix various invalid MIME type entries + - `application/vnd-acucobol` + - `application/vnd-curl` + - `application/vnd-dart` + - `application/vnd-dxr` + - `application/vnd-fdf` + - `application/vnd-mif` + - `application/vnd-sema` + - `application/vnd-wap-wmlc` + - `application/vnd.adobe.flash-movie` + - `application/vnd.dece-zip` + - `application/vnd.dvb_service` + - `application/vnd.micrografx-igx` + - `application/vnd.sealed-doc` + - `application/vnd.sealed-eml` + - `application/vnd.sealed-mht` + - `application/vnd.sealed-ppt` + - `application/vnd.sealed-tiff` + - `application/vnd.sealed-xls` + - `application/vnd.sealedmedia.softseal-html` + - `application/vnd.sealedmedia.softseal-pdf` + - `application/vnd.wap-slc` + - `application/vnd.wap-wbxml` + - `audio/vnd.sealedmedia.softseal-mpeg` + - `image/vnd-djvu` + - `image/vnd-svf` + - `image/vnd-wap-wbmp` + - `image/vnd.sealed-png` + - `image/vnd.sealedmedia.softseal-gif` + - `image/vnd.sealedmedia.softseal-jpg` + - `model/vnd-dwf` + - `model/vnd.parasolid.transmit-binary` + - `model/vnd.parasolid.transmit-text` + - `text/vnd-a` + - `text/vnd-curl` + - `text/vnd.wap-wml` + * Remove example template MIME types + - `application/example` + - `audio/example` + - `image/example` + - `message/example` + - `model/example` + - `multipart/example` + - `text/example` + - `video/example` + +1.3.1 / 2014-12-16 +================== + + * Fix missing extensions + - `application/json5` + - `text/hjson` + +1.3.0 / 2014-12-07 +================== + + * Add `application/a2l` + * Add `application/aml` + * Add `application/atfx` + * Add `application/atxml` + * Add `application/cdfx+xml` + * Add `application/dii` + * Add `application/json5` + * Add `application/lxf` + * Add `application/mf4` + * Add `application/vnd.apache.thrift.compact` + * Add `application/vnd.apache.thrift.json` + * Add `application/vnd.coffeescript` + * Add `application/vnd.enphase.envoy` + * Add `application/vnd.ims.imsccv1p1` + * Add `text/csv-schema` + * Add `text/hjson` + * Add `text/markdown` + * Add `text/yaml` + +1.2.0 / 2014-11-09 +================== + + * Add `application/cea` + * Add `application/dit` + * Add `application/vnd.gov.sk.e-form+zip` + * Add `application/vnd.tmd.mediaflex.api+xml` + * Type `application/epub+zip` is now IANA-registered + +1.1.2 / 2014-10-23 +================== + + * Rebuild database for `application/x-www-form-urlencoded` change + +1.1.1 / 2014-10-20 +================== + + * Mark `application/x-www-form-urlencoded` as compressible. + +1.1.0 / 2014-09-28 +================== + + * Add `application/font-woff2` + +1.0.3 / 2014-09-25 +================== + + * Fix engine requirement in package + +1.0.2 / 2014-09-25 +================== + + * Add `application/coap-group+json` + * Add `application/dcd` + * Add `application/vnd.apache.thrift.binary` + * Add `image/vnd.tencent.tap` + * Mark all JSON-derived types as compressible + * Update `text/vtt` data + +1.0.1 / 2014-08-30 +================== + + * Fix extension ordering + +1.0.0 / 2014-08-30 +================== + + * Add `application/atf` + * Add `application/merge-patch+json` + * Add `multipart/x-mixed-replace` + * Add `source: 'apache'` metadata + * Add `source: 'iana'` metadata + * Remove badly-assumed charset data diff --git a/node_modules/mime-db/LICENSE b/node_modules/mime-db/LICENSE new file mode 100644 index 0000000..0751cb1 --- /dev/null +++ b/node_modules/mime-db/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015-2022 Douglas Christopher Wilson + +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/mime-db/README.md b/node_modules/mime-db/README.md new file mode 100644 index 0000000..5a8fcfe --- /dev/null +++ b/node_modules/mime-db/README.md @@ -0,0 +1,100 @@ +# mime-db + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-image]][node-url] +[![Build Status][ci-image]][ci-url] +[![Coverage Status][coveralls-image]][coveralls-url] + +This is a large database of mime types and information about them. +It consists of a single, public JSON file and does not include any logic, +allowing it to remain as un-opinionated as possible with an API. +It aggregates data from the following sources: + +- http://www.iana.org/assignments/media-types/media-types.xhtml +- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types +- http://hg.nginx.org/nginx/raw-file/default/conf/mime.types + +## Installation + +```bash +npm install mime-db +``` + +### Database Download + +If you're crazy enough to use this in the browser, you can just grab the +JSON file using [jsDelivr](https://www.jsdelivr.com/). It is recommended to +replace `master` with [a release tag](https://github.com/jshttp/mime-db/tags) +as the JSON format may change in the future. + +``` +https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json +``` + +## Usage + +```js +var db = require('mime-db') + +// grab data on .js files +var data = db['application/javascript'] +``` + +## Data Structure + +The JSON file is a map lookup for lowercased mime types. +Each mime type has the following properties: + +- `.source` - where the mime type is defined. + If not set, it's probably a custom media type. + - `apache` - [Apache common media types](http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types) + - `iana` - [IANA-defined media types](http://www.iana.org/assignments/media-types/media-types.xhtml) + - `nginx` - [nginx media types](http://hg.nginx.org/nginx/raw-file/default/conf/mime.types) +- `.extensions[]` - known extensions associated with this mime type. +- `.compressible` - whether a file of this type can be gzipped. +- `.charset` - the default charset associated with this type, if any. + +If unknown, every property could be `undefined`. + +## Contributing + +To edit the database, only make PRs against `src/custom-types.json` or +`src/custom-suffix.json`. + +The `src/custom-types.json` file is a JSON object with the MIME type as the +keys and the values being an object with the following keys: + +- `compressible` - leave out if you don't know, otherwise `true`/`false` to + indicate whether the data represented by the type is typically compressible. +- `extensions` - include an array of file extensions that are associated with + the type. +- `notes` - human-readable notes about the type, typically what the type is. +- `sources` - include an array of URLs of where the MIME type and the associated + extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source); + links to type aggregating sites and Wikipedia are _not acceptable_. + +To update the build, run `npm run build`. + +### Adding Custom Media Types + +The best way to get new media types included in this library is to register +them with the IANA. The community registration procedure is outlined in +[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types +registered with the IANA are automatically pulled into this library. + +If that is not possible / feasible, they can be added directly here as a +"custom" type. To do this, it is required to have a primary source that +definitively lists the media type. If an extension is going to be listed as +associateed with this media type, the source must definitively link the +media type and extension as well. + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci +[ci-url]: https://github.com/jshttp/mime-db/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master +[node-image]: https://badgen.net/npm/node/mime-db +[node-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-db +[npm-url]: https://npmjs.org/package/mime-db +[npm-version-image]: https://badgen.net/npm/v/mime-db diff --git a/node_modules/mime-db/db.json b/node_modules/mime-db/db.json new file mode 100644 index 0000000..eb9c42c --- /dev/null +++ b/node_modules/mime-db/db.json @@ -0,0 +1,8519 @@ +{ + "application/1d-interleaved-parityfec": { + "source": "iana" + }, + "application/3gpdash-qoe-report+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/3gpp-ims+xml": { + "source": "iana", + "compressible": true + }, + "application/3gpphal+json": { + "source": "iana", + "compressible": true + }, + "application/3gpphalforms+json": { + "source": "iana", + "compressible": true + }, + "application/a2l": { + "source": "iana" + }, + "application/ace+cbor": { + "source": "iana" + }, + "application/activemessage": { + "source": "iana" + }, + "application/activity+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-costmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-directory+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcost+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointcostparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointprop+json": { + "source": "iana", + "compressible": true + }, + "application/alto-endpointpropparams+json": { + "source": "iana", + "compressible": true + }, + "application/alto-error+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmap+json": { + "source": "iana", + "compressible": true + }, + "application/alto-networkmapfilter+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamcontrol+json": { + "source": "iana", + "compressible": true + }, + "application/alto-updatestreamparams+json": { + "source": "iana", + "compressible": true + }, + "application/aml": { + "source": "iana" + }, + "application/andrew-inset": { + "source": "iana", + "extensions": ["ez"] + }, + "application/applefile": { + "source": "iana" + }, + "application/applixware": { + "source": "apache", + "extensions": ["aw"] + }, + "application/at+jwt": { + "source": "iana" + }, + "application/atf": { + "source": "iana" + }, + "application/atfx": { + "source": "iana" + }, + "application/atom+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atom"] + }, + "application/atomcat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomcat"] + }, + "application/atomdeleted+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomdeleted"] + }, + "application/atomicmail": { + "source": "iana" + }, + "application/atomsvc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["atomsvc"] + }, + "application/atsc-dwd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dwd"] + }, + "application/atsc-dynamic-event-message": { + "source": "iana" + }, + "application/atsc-held+xml": { + "source": "iana", + "compressible": true, + "extensions": ["held"] + }, + "application/atsc-rdt+json": { + "source": "iana", + "compressible": true + }, + "application/atsc-rsat+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsat"] + }, + "application/atxml": { + "source": "iana" + }, + "application/auth-policy+xml": { + "source": "iana", + "compressible": true + }, + "application/bacnet-xdd+zip": { + "source": "iana", + "compressible": false + }, + "application/batch-smtp": { + "source": "iana" + }, + "application/bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/beep+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/calendar+json": { + "source": "iana", + "compressible": true + }, + "application/calendar+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xcs"] + }, + "application/call-completion": { + "source": "iana" + }, + "application/cals-1840": { + "source": "iana" + }, + "application/captive+json": { + "source": "iana", + "compressible": true + }, + "application/cbor": { + "source": "iana" + }, + "application/cbor-seq": { + "source": "iana" + }, + "application/cccex": { + "source": "iana" + }, + "application/ccmp+xml": { + "source": "iana", + "compressible": true + }, + "application/ccxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ccxml"] + }, + "application/cdfx+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdfx"] + }, + "application/cdmi-capability": { + "source": "iana", + "extensions": ["cdmia"] + }, + "application/cdmi-container": { + "source": "iana", + "extensions": ["cdmic"] + }, + "application/cdmi-domain": { + "source": "iana", + "extensions": ["cdmid"] + }, + "application/cdmi-object": { + "source": "iana", + "extensions": ["cdmio"] + }, + "application/cdmi-queue": { + "source": "iana", + "extensions": ["cdmiq"] + }, + "application/cdni": { + "source": "iana" + }, + "application/cea": { + "source": "iana" + }, + "application/cea-2018+xml": { + "source": "iana", + "compressible": true + }, + "application/cellml+xml": { + "source": "iana", + "compressible": true + }, + "application/cfw": { + "source": "iana" + }, + "application/city+json": { + "source": "iana", + "compressible": true + }, + "application/clr": { + "source": "iana" + }, + "application/clue+xml": { + "source": "iana", + "compressible": true + }, + "application/clue_info+xml": { + "source": "iana", + "compressible": true + }, + "application/cms": { + "source": "iana" + }, + "application/cnrp+xml": { + "source": "iana", + "compressible": true + }, + "application/coap-group+json": { + "source": "iana", + "compressible": true + }, + "application/coap-payload": { + "source": "iana" + }, + "application/commonground": { + "source": "iana" + }, + "application/conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/cose": { + "source": "iana" + }, + "application/cose-key": { + "source": "iana" + }, + "application/cose-key-set": { + "source": "iana" + }, + "application/cpl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cpl"] + }, + "application/csrattrs": { + "source": "iana" + }, + "application/csta+xml": { + "source": "iana", + "compressible": true + }, + "application/cstadata+xml": { + "source": "iana", + "compressible": true + }, + "application/csvm+json": { + "source": "iana", + "compressible": true + }, + "application/cu-seeme": { + "source": "apache", + "extensions": ["cu"] + }, + "application/cwt": { + "source": "iana" + }, + "application/cybercash": { + "source": "iana" + }, + "application/dart": { + "compressible": true + }, + "application/dash+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpd"] + }, + "application/dash-patch+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpp"] + }, + "application/dashdelta": { + "source": "iana" + }, + "application/davmount+xml": { + "source": "iana", + "compressible": true, + "extensions": ["davmount"] + }, + "application/dca-rft": { + "source": "iana" + }, + "application/dcd": { + "source": "iana" + }, + "application/dec-dx": { + "source": "iana" + }, + "application/dialog-info+xml": { + "source": "iana", + "compressible": true + }, + "application/dicom": { + "source": "iana" + }, + "application/dicom+json": { + "source": "iana", + "compressible": true + }, + "application/dicom+xml": { + "source": "iana", + "compressible": true + }, + "application/dii": { + "source": "iana" + }, + "application/dit": { + "source": "iana" + }, + "application/dns": { + "source": "iana" + }, + "application/dns+json": { + "source": "iana", + "compressible": true + }, + "application/dns-message": { + "source": "iana" + }, + "application/docbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dbk"] + }, + "application/dots+cbor": { + "source": "iana" + }, + "application/dskpp+xml": { + "source": "iana", + "compressible": true + }, + "application/dssc+der": { + "source": "iana", + "extensions": ["dssc"] + }, + "application/dssc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdssc"] + }, + "application/dvcs": { + "source": "iana" + }, + "application/ecmascript": { + "source": "iana", + "compressible": true, + "extensions": ["es","ecma"] + }, + "application/edi-consent": { + "source": "iana" + }, + "application/edi-x12": { + "source": "iana", + "compressible": false + }, + "application/edifact": { + "source": "iana", + "compressible": false + }, + "application/efi": { + "source": "iana" + }, + "application/elm+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/elm+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.cap+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/emergencycalldata.comment+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.control+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.deviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.ecall.msd": { + "source": "iana" + }, + "application/emergencycalldata.providerinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.serviceinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.subscriberinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/emergencycalldata.veds+xml": { + "source": "iana", + "compressible": true + }, + "application/emma+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emma"] + }, + "application/emotionml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["emotionml"] + }, + "application/encaprtp": { + "source": "iana" + }, + "application/epp+xml": { + "source": "iana", + "compressible": true + }, + "application/epub+zip": { + "source": "iana", + "compressible": false, + "extensions": ["epub"] + }, + "application/eshop": { + "source": "iana" + }, + "application/exi": { + "source": "iana", + "extensions": ["exi"] + }, + "application/expect-ct-report+json": { + "source": "iana", + "compressible": true + }, + "application/express": { + "source": "iana", + "extensions": ["exp"] + }, + "application/fastinfoset": { + "source": "iana" + }, + "application/fastsoap": { + "source": "iana" + }, + "application/fdt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fdt"] + }, + "application/fhir+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fhir+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/fido.trusted-apps+json": { + "compressible": true + }, + "application/fits": { + "source": "iana" + }, + "application/flexfec": { + "source": "iana" + }, + "application/font-sfnt": { + "source": "iana" + }, + "application/font-tdpfr": { + "source": "iana", + "extensions": ["pfr"] + }, + "application/font-woff": { + "source": "iana", + "compressible": false + }, + "application/framework-attributes+xml": { + "source": "iana", + "compressible": true + }, + "application/geo+json": { + "source": "iana", + "compressible": true, + "extensions": ["geojson"] + }, + "application/geo+json-seq": { + "source": "iana" + }, + "application/geopackage+sqlite3": { + "source": "iana" + }, + "application/geoxacml+xml": { + "source": "iana", + "compressible": true + }, + "application/gltf-buffer": { + "source": "iana" + }, + "application/gml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["gml"] + }, + "application/gpx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["gpx"] + }, + "application/gxf": { + "source": "apache", + "extensions": ["gxf"] + }, + "application/gzip": { + "source": "iana", + "compressible": false, + "extensions": ["gz"] + }, + "application/h224": { + "source": "iana" + }, + "application/held+xml": { + "source": "iana", + "compressible": true + }, + "application/hjson": { + "extensions": ["hjson"] + }, + "application/http": { + "source": "iana" + }, + "application/hyperstudio": { + "source": "iana", + "extensions": ["stk"] + }, + "application/ibe-key-request+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pkg-reply+xml": { + "source": "iana", + "compressible": true + }, + "application/ibe-pp-data": { + "source": "iana" + }, + "application/iges": { + "source": "iana" + }, + "application/im-iscomposing+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/index": { + "source": "iana" + }, + "application/index.cmd": { + "source": "iana" + }, + "application/index.obj": { + "source": "iana" + }, + "application/index.response": { + "source": "iana" + }, + "application/index.vnd": { + "source": "iana" + }, + "application/inkml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ink","inkml"] + }, + "application/iotp": { + "source": "iana" + }, + "application/ipfix": { + "source": "iana", + "extensions": ["ipfix"] + }, + "application/ipp": { + "source": "iana" + }, + "application/isup": { + "source": "iana" + }, + "application/its+xml": { + "source": "iana", + "compressible": true, + "extensions": ["its"] + }, + "application/java-archive": { + "source": "apache", + "compressible": false, + "extensions": ["jar","war","ear"] + }, + "application/java-serialized-object": { + "source": "apache", + "compressible": false, + "extensions": ["ser"] + }, + "application/java-vm": { + "source": "apache", + "compressible": false, + "extensions": ["class"] + }, + "application/javascript": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["js","mjs"] + }, + "application/jf2feed+json": { + "source": "iana", + "compressible": true + }, + "application/jose": { + "source": "iana" + }, + "application/jose+json": { + "source": "iana", + "compressible": true + }, + "application/jrd+json": { + "source": "iana", + "compressible": true + }, + "application/jscalendar+json": { + "source": "iana", + "compressible": true + }, + "application/json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["json","map"] + }, + "application/json-patch+json": { + "source": "iana", + "compressible": true + }, + "application/json-seq": { + "source": "iana" + }, + "application/json5": { + "extensions": ["json5"] + }, + "application/jsonml+json": { + "source": "apache", + "compressible": true, + "extensions": ["jsonml"] + }, + "application/jwk+json": { + "source": "iana", + "compressible": true + }, + "application/jwk-set+json": { + "source": "iana", + "compressible": true + }, + "application/jwt": { + "source": "iana" + }, + "application/kpml-request+xml": { + "source": "iana", + "compressible": true + }, + "application/kpml-response+xml": { + "source": "iana", + "compressible": true + }, + "application/ld+json": { + "source": "iana", + "compressible": true, + "extensions": ["jsonld"] + }, + "application/lgr+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lgr"] + }, + "application/link-format": { + "source": "iana" + }, + "application/load-control+xml": { + "source": "iana", + "compressible": true + }, + "application/lost+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lostxml"] + }, + "application/lostsync+xml": { + "source": "iana", + "compressible": true + }, + "application/lpf+zip": { + "source": "iana", + "compressible": false + }, + "application/lxf": { + "source": "iana" + }, + "application/mac-binhex40": { + "source": "iana", + "extensions": ["hqx"] + }, + "application/mac-compactpro": { + "source": "apache", + "extensions": ["cpt"] + }, + "application/macwriteii": { + "source": "iana" + }, + "application/mads+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mads"] + }, + "application/manifest+json": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["webmanifest"] + }, + "application/marc": { + "source": "iana", + "extensions": ["mrc"] + }, + "application/marcxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mrcx"] + }, + "application/mathematica": { + "source": "iana", + "extensions": ["ma","nb","mb"] + }, + "application/mathml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mathml"] + }, + "application/mathml-content+xml": { + "source": "iana", + "compressible": true + }, + "application/mathml-presentation+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-associated-procedure-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-deregister+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-envelope+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-msk-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-protection-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-reception-report+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-register-response+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-schedule+xml": { + "source": "iana", + "compressible": true + }, + "application/mbms-user-service-description+xml": { + "source": "iana", + "compressible": true + }, + "application/mbox": { + "source": "iana", + "extensions": ["mbox"] + }, + "application/media-policy-dataset+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpf"] + }, + "application/media_control+xml": { + "source": "iana", + "compressible": true + }, + "application/mediaservercontrol+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mscml"] + }, + "application/merge-patch+json": { + "source": "iana", + "compressible": true + }, + "application/metalink+xml": { + "source": "apache", + "compressible": true, + "extensions": ["metalink"] + }, + "application/metalink4+xml": { + "source": "iana", + "compressible": true, + "extensions": ["meta4"] + }, + "application/mets+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mets"] + }, + "application/mf4": { + "source": "iana" + }, + "application/mikey": { + "source": "iana" + }, + "application/mipc": { + "source": "iana" + }, + "application/missing-blocks+cbor-seq": { + "source": "iana" + }, + "application/mmt-aei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["maei"] + }, + "application/mmt-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musd"] + }, + "application/mods+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mods"] + }, + "application/moss-keys": { + "source": "iana" + }, + "application/moss-signature": { + "source": "iana" + }, + "application/mosskey-data": { + "source": "iana" + }, + "application/mosskey-request": { + "source": "iana" + }, + "application/mp21": { + "source": "iana", + "extensions": ["m21","mp21"] + }, + "application/mp4": { + "source": "iana", + "extensions": ["mp4s","m4p"] + }, + "application/mpeg4-generic": { + "source": "iana" + }, + "application/mpeg4-iod": { + "source": "iana" + }, + "application/mpeg4-iod-xmt": { + "source": "iana" + }, + "application/mrb-consumer+xml": { + "source": "iana", + "compressible": true + }, + "application/mrb-publish+xml": { + "source": "iana", + "compressible": true + }, + "application/msc-ivr+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msc-mixer+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/msword": { + "source": "iana", + "compressible": false, + "extensions": ["doc","dot"] + }, + "application/mud+json": { + "source": "iana", + "compressible": true + }, + "application/multipart-core": { + "source": "iana" + }, + "application/mxf": { + "source": "iana", + "extensions": ["mxf"] + }, + "application/n-quads": { + "source": "iana", + "extensions": ["nq"] + }, + "application/n-triples": { + "source": "iana", + "extensions": ["nt"] + }, + "application/nasdata": { + "source": "iana" + }, + "application/news-checkgroups": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-groupinfo": { + "source": "iana", + "charset": "US-ASCII" + }, + "application/news-transmission": { + "source": "iana" + }, + "application/nlsml+xml": { + "source": "iana", + "compressible": true + }, + "application/node": { + "source": "iana", + "extensions": ["cjs"] + }, + "application/nss": { + "source": "iana" + }, + "application/oauth-authz-req+jwt": { + "source": "iana" + }, + "application/oblivious-dns-message": { + "source": "iana" + }, + "application/ocsp-request": { + "source": "iana" + }, + "application/ocsp-response": { + "source": "iana" + }, + "application/octet-stream": { + "source": "iana", + "compressible": false, + "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"] + }, + "application/oda": { + "source": "iana", + "extensions": ["oda"] + }, + "application/odm+xml": { + "source": "iana", + "compressible": true + }, + "application/odx": { + "source": "iana" + }, + "application/oebps-package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["opf"] + }, + "application/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogx"] + }, + "application/omdoc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["omdoc"] + }, + "application/onenote": { + "source": "apache", + "extensions": ["onetoc","onetoc2","onetmp","onepkg"] + }, + "application/opc-nodeset+xml": { + "source": "iana", + "compressible": true + }, + "application/oscore": { + "source": "iana" + }, + "application/oxps": { + "source": "iana", + "extensions": ["oxps"] + }, + "application/p21": { + "source": "iana" + }, + "application/p21+zip": { + "source": "iana", + "compressible": false + }, + "application/p2p-overlay+xml": { + "source": "iana", + "compressible": true, + "extensions": ["relo"] + }, + "application/parityfec": { + "source": "iana" + }, + "application/passport": { + "source": "iana" + }, + "application/patch-ops-error+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xer"] + }, + "application/pdf": { + "source": "iana", + "compressible": false, + "extensions": ["pdf"] + }, + "application/pdx": { + "source": "iana" + }, + "application/pem-certificate-chain": { + "source": "iana" + }, + "application/pgp-encrypted": { + "source": "iana", + "compressible": false, + "extensions": ["pgp"] + }, + "application/pgp-keys": { + "source": "iana", + "extensions": ["asc"] + }, + "application/pgp-signature": { + "source": "iana", + "extensions": ["asc","sig"] + }, + "application/pics-rules": { + "source": "apache", + "extensions": ["prf"] + }, + "application/pidf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pidf-diff+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/pkcs10": { + "source": "iana", + "extensions": ["p10"] + }, + "application/pkcs12": { + "source": "iana" + }, + "application/pkcs7-mime": { + "source": "iana", + "extensions": ["p7m","p7c"] + }, + "application/pkcs7-signature": { + "source": "iana", + "extensions": ["p7s"] + }, + "application/pkcs8": { + "source": "iana", + "extensions": ["p8"] + }, + "application/pkcs8-encrypted": { + "source": "iana" + }, + "application/pkix-attr-cert": { + "source": "iana", + "extensions": ["ac"] + }, + "application/pkix-cert": { + "source": "iana", + "extensions": ["cer"] + }, + "application/pkix-crl": { + "source": "iana", + "extensions": ["crl"] + }, + "application/pkix-pkipath": { + "source": "iana", + "extensions": ["pkipath"] + }, + "application/pkixcmp": { + "source": "iana", + "extensions": ["pki"] + }, + "application/pls+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pls"] + }, + "application/poc-settings+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/postscript": { + "source": "iana", + "compressible": true, + "extensions": ["ai","eps","ps"] + }, + "application/ppsp-tracker+json": { + "source": "iana", + "compressible": true + }, + "application/problem+json": { + "source": "iana", + "compressible": true + }, + "application/problem+xml": { + "source": "iana", + "compressible": true + }, + "application/provenance+xml": { + "source": "iana", + "compressible": true, + "extensions": ["provx"] + }, + "application/prs.alvestrand.titrax-sheet": { + "source": "iana" + }, + "application/prs.cww": { + "source": "iana", + "extensions": ["cww"] + }, + "application/prs.cyn": { + "source": "iana", + "charset": "7-BIT" + }, + "application/prs.hpub+zip": { + "source": "iana", + "compressible": false + }, + "application/prs.nprend": { + "source": "iana" + }, + "application/prs.plucker": { + "source": "iana" + }, + "application/prs.rdf-xml-crypt": { + "source": "iana" + }, + "application/prs.xsf+xml": { + "source": "iana", + "compressible": true + }, + "application/pskc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["pskcxml"] + }, + "application/pvd+json": { + "source": "iana", + "compressible": true + }, + "application/qsig": { + "source": "iana" + }, + "application/raml+yaml": { + "compressible": true, + "extensions": ["raml"] + }, + "application/raptorfec": { + "source": "iana" + }, + "application/rdap+json": { + "source": "iana", + "compressible": true + }, + "application/rdf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rdf","owl"] + }, + "application/reginfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rif"] + }, + "application/relax-ng-compact-syntax": { + "source": "iana", + "extensions": ["rnc"] + }, + "application/remote-printing": { + "source": "iana" + }, + "application/reputon+json": { + "source": "iana", + "compressible": true + }, + "application/resource-lists+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rl"] + }, + "application/resource-lists-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rld"] + }, + "application/rfc+xml": { + "source": "iana", + "compressible": true + }, + "application/riscos": { + "source": "iana" + }, + "application/rlmi+xml": { + "source": "iana", + "compressible": true + }, + "application/rls-services+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rs"] + }, + "application/route-apd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rapd"] + }, + "application/route-s-tsid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sls"] + }, + "application/route-usd+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rusd"] + }, + "application/rpki-ghostbusters": { + "source": "iana", + "extensions": ["gbr"] + }, + "application/rpki-manifest": { + "source": "iana", + "extensions": ["mft"] + }, + "application/rpki-publication": { + "source": "iana" + }, + "application/rpki-roa": { + "source": "iana", + "extensions": ["roa"] + }, + "application/rpki-updown": { + "source": "iana" + }, + "application/rsd+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rsd"] + }, + "application/rss+xml": { + "source": "apache", + "compressible": true, + "extensions": ["rss"] + }, + "application/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "application/rtploopback": { + "source": "iana" + }, + "application/rtx": { + "source": "iana" + }, + "application/samlassertion+xml": { + "source": "iana", + "compressible": true + }, + "application/samlmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/sarif+json": { + "source": "iana", + "compressible": true + }, + "application/sarif-external-properties+json": { + "source": "iana", + "compressible": true + }, + "application/sbe": { + "source": "iana" + }, + "application/sbml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sbml"] + }, + "application/scaip+xml": { + "source": "iana", + "compressible": true + }, + "application/scim+json": { + "source": "iana", + "compressible": true + }, + "application/scvp-cv-request": { + "source": "iana", + "extensions": ["scq"] + }, + "application/scvp-cv-response": { + "source": "iana", + "extensions": ["scs"] + }, + "application/scvp-vp-request": { + "source": "iana", + "extensions": ["spq"] + }, + "application/scvp-vp-response": { + "source": "iana", + "extensions": ["spp"] + }, + "application/sdp": { + "source": "iana", + "extensions": ["sdp"] + }, + "application/secevent+jwt": { + "source": "iana" + }, + "application/senml+cbor": { + "source": "iana" + }, + "application/senml+json": { + "source": "iana", + "compressible": true + }, + "application/senml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["senmlx"] + }, + "application/senml-etch+cbor": { + "source": "iana" + }, + "application/senml-etch+json": { + "source": "iana", + "compressible": true + }, + "application/senml-exi": { + "source": "iana" + }, + "application/sensml+cbor": { + "source": "iana" + }, + "application/sensml+json": { + "source": "iana", + "compressible": true + }, + "application/sensml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sensmlx"] + }, + "application/sensml-exi": { + "source": "iana" + }, + "application/sep+xml": { + "source": "iana", + "compressible": true + }, + "application/sep-exi": { + "source": "iana" + }, + "application/session-info": { + "source": "iana" + }, + "application/set-payment": { + "source": "iana" + }, + "application/set-payment-initiation": { + "source": "iana", + "extensions": ["setpay"] + }, + "application/set-registration": { + "source": "iana" + }, + "application/set-registration-initiation": { + "source": "iana", + "extensions": ["setreg"] + }, + "application/sgml": { + "source": "iana" + }, + "application/sgml-open-catalog": { + "source": "iana" + }, + "application/shf+xml": { + "source": "iana", + "compressible": true, + "extensions": ["shf"] + }, + "application/sieve": { + "source": "iana", + "extensions": ["siv","sieve"] + }, + "application/simple-filter+xml": { + "source": "iana", + "compressible": true + }, + "application/simple-message-summary": { + "source": "iana" + }, + "application/simplesymbolcontainer": { + "source": "iana" + }, + "application/sipc": { + "source": "iana" + }, + "application/slate": { + "source": "iana" + }, + "application/smil": { + "source": "iana" + }, + "application/smil+xml": { + "source": "iana", + "compressible": true, + "extensions": ["smi","smil"] + }, + "application/smpte336m": { + "source": "iana" + }, + "application/soap+fastinfoset": { + "source": "iana" + }, + "application/soap+xml": { + "source": "iana", + "compressible": true + }, + "application/sparql-query": { + "source": "iana", + "extensions": ["rq"] + }, + "application/sparql-results+xml": { + "source": "iana", + "compressible": true, + "extensions": ["srx"] + }, + "application/spdx+json": { + "source": "iana", + "compressible": true + }, + "application/spirits-event+xml": { + "source": "iana", + "compressible": true + }, + "application/sql": { + "source": "iana" + }, + "application/srgs": { + "source": "iana", + "extensions": ["gram"] + }, + "application/srgs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["grxml"] + }, + "application/sru+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sru"] + }, + "application/ssdl+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ssdl"] + }, + "application/ssml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ssml"] + }, + "application/stix+json": { + "source": "iana", + "compressible": true + }, + "application/swid+xml": { + "source": "iana", + "compressible": true, + "extensions": ["swidtag"] + }, + "application/tamp-apex-update": { + "source": "iana" + }, + "application/tamp-apex-update-confirm": { + "source": "iana" + }, + "application/tamp-community-update": { + "source": "iana" + }, + "application/tamp-community-update-confirm": { + "source": "iana" + }, + "application/tamp-error": { + "source": "iana" + }, + "application/tamp-sequence-adjust": { + "source": "iana" + }, + "application/tamp-sequence-adjust-confirm": { + "source": "iana" + }, + "application/tamp-status-query": { + "source": "iana" + }, + "application/tamp-status-response": { + "source": "iana" + }, + "application/tamp-update": { + "source": "iana" + }, + "application/tamp-update-confirm": { + "source": "iana" + }, + "application/tar": { + "compressible": true + }, + "application/taxii+json": { + "source": "iana", + "compressible": true + }, + "application/td+json": { + "source": "iana", + "compressible": true + }, + "application/tei+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tei","teicorpus"] + }, + "application/tetra_isi": { + "source": "iana" + }, + "application/thraud+xml": { + "source": "iana", + "compressible": true, + "extensions": ["tfi"] + }, + "application/timestamp-query": { + "source": "iana" + }, + "application/timestamp-reply": { + "source": "iana" + }, + "application/timestamped-data": { + "source": "iana", + "extensions": ["tsd"] + }, + "application/tlsrpt+gzip": { + "source": "iana" + }, + "application/tlsrpt+json": { + "source": "iana", + "compressible": true + }, + "application/tnauthlist": { + "source": "iana" + }, + "application/token-introspection+jwt": { + "source": "iana" + }, + "application/toml": { + "compressible": true, + "extensions": ["toml"] + }, + "application/trickle-ice-sdpfrag": { + "source": "iana" + }, + "application/trig": { + "source": "iana", + "extensions": ["trig"] + }, + "application/ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ttml"] + }, + "application/tve-trigger": { + "source": "iana" + }, + "application/tzif": { + "source": "iana" + }, + "application/tzif-leap": { + "source": "iana" + }, + "application/ubjson": { + "compressible": false, + "extensions": ["ubj"] + }, + "application/ulpfec": { + "source": "iana" + }, + "application/urc-grpsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/urc-ressheet+xml": { + "source": "iana", + "compressible": true, + "extensions": ["rsheet"] + }, + "application/urc-targetdesc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["td"] + }, + "application/urc-uisocketdesc+xml": { + "source": "iana", + "compressible": true + }, + "application/vcard+json": { + "source": "iana", + "compressible": true + }, + "application/vcard+xml": { + "source": "iana", + "compressible": true + }, + "application/vemmi": { + "source": "iana" + }, + "application/vividence.scriptfile": { + "source": "apache" + }, + "application/vnd.1000minds.decision-model+xml": { + "source": "iana", + "compressible": true, + "extensions": ["1km"] + }, + "application/vnd.3gpp-prose+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-prose-pc3ch+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp-v2x-local-service-information": { + "source": "iana" + }, + "application/vnd.3gpp.5gnas": { + "source": "iana" + }, + "application/vnd.3gpp.access-transfer-events+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.bsf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gmop+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.gtpc": { + "source": "iana" + }, + "application/vnd.3gpp.interworking-data": { + "source": "iana" + }, + "application/vnd.3gpp.lpp": { + "source": "iana" + }, + "application/vnd.3gpp.mc-signalling-ear": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-payload": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-signalling": { + "source": "iana" + }, + "application/vnd.3gpp.mcdata-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcdata-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-floor-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-signed+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-ue-init-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcptt-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-command+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-affiliation-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-location-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-service-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-transmission-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-ue-config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mcvideo-user-profile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.mid-call+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ngap": { + "source": "iana" + }, + "application/vnd.3gpp.pfcp": { + "source": "iana" + }, + "application/vnd.3gpp.pic-bw-large": { + "source": "iana", + "extensions": ["plb"] + }, + "application/vnd.3gpp.pic-bw-small": { + "source": "iana", + "extensions": ["psb"] + }, + "application/vnd.3gpp.pic-bw-var": { + "source": "iana", + "extensions": ["pvb"] + }, + "application/vnd.3gpp.s1ap": { + "source": "iana" + }, + "application/vnd.3gpp.sms": { + "source": "iana" + }, + "application/vnd.3gpp.sms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-ext+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.srvcc-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.state-and-event-info+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp.ussd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.bcmcsinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.3gpp2.sms": { + "source": "iana" + }, + "application/vnd.3gpp2.tcap": { + "source": "iana", + "extensions": ["tcap"] + }, + "application/vnd.3lightssoftware.imagescal": { + "source": "iana" + }, + "application/vnd.3m.post-it-notes": { + "source": "iana", + "extensions": ["pwn"] + }, + "application/vnd.accpac.simply.aso": { + "source": "iana", + "extensions": ["aso"] + }, + "application/vnd.accpac.simply.imp": { + "source": "iana", + "extensions": ["imp"] + }, + "application/vnd.acucobol": { + "source": "iana", + "extensions": ["acu"] + }, + "application/vnd.acucorp": { + "source": "iana", + "extensions": ["atc","acutc"] + }, + "application/vnd.adobe.air-application-installer-package+zip": { + "source": "apache", + "compressible": false, + "extensions": ["air"] + }, + "application/vnd.adobe.flash.movie": { + "source": "iana" + }, + "application/vnd.adobe.formscentral.fcdt": { + "source": "iana", + "extensions": ["fcdt"] + }, + "application/vnd.adobe.fxp": { + "source": "iana", + "extensions": ["fxp","fxpl"] + }, + "application/vnd.adobe.partial-upload": { + "source": "iana" + }, + "application/vnd.adobe.xdp+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdp"] + }, + "application/vnd.adobe.xfdf": { + "source": "iana", + "extensions": ["xfdf"] + }, + "application/vnd.aether.imp": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata": { + "source": "iana" + }, + "application/vnd.afpc.afplinedata-pagedef": { + "source": "iana" + }, + "application/vnd.afpc.cmoca-cmresource": { + "source": "iana" + }, + "application/vnd.afpc.foca-charset": { + "source": "iana" + }, + "application/vnd.afpc.foca-codedfont": { + "source": "iana" + }, + "application/vnd.afpc.foca-codepage": { + "source": "iana" + }, + "application/vnd.afpc.modca": { + "source": "iana" + }, + "application/vnd.afpc.modca-cmtable": { + "source": "iana" + }, + "application/vnd.afpc.modca-formdef": { + "source": "iana" + }, + "application/vnd.afpc.modca-mediummap": { + "source": "iana" + }, + "application/vnd.afpc.modca-objectcontainer": { + "source": "iana" + }, + "application/vnd.afpc.modca-overlay": { + "source": "iana" + }, + "application/vnd.afpc.modca-pagesegment": { + "source": "iana" + }, + "application/vnd.age": { + "source": "iana", + "extensions": ["age"] + }, + "application/vnd.ah-barcode": { + "source": "iana" + }, + "application/vnd.ahead.space": { + "source": "iana", + "extensions": ["ahead"] + }, + "application/vnd.airzip.filesecure.azf": { + "source": "iana", + "extensions": ["azf"] + }, + "application/vnd.airzip.filesecure.azs": { + "source": "iana", + "extensions": ["azs"] + }, + "application/vnd.amadeus+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.amazon.ebook": { + "source": "apache", + "extensions": ["azw"] + }, + "application/vnd.amazon.mobi8-ebook": { + "source": "iana" + }, + "application/vnd.americandynamics.acc": { + "source": "iana", + "extensions": ["acc"] + }, + "application/vnd.amiga.ami": { + "source": "iana", + "extensions": ["ami"] + }, + "application/vnd.amundsen.maze+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.android.ota": { + "source": "iana" + }, + "application/vnd.android.package-archive": { + "source": "apache", + "compressible": false, + "extensions": ["apk"] + }, + "application/vnd.anki": { + "source": "iana" + }, + "application/vnd.anser-web-certificate-issue-initiation": { + "source": "iana", + "extensions": ["cii"] + }, + "application/vnd.anser-web-funds-transfer-initiation": { + "source": "apache", + "extensions": ["fti"] + }, + "application/vnd.antix.game-component": { + "source": "iana", + "extensions": ["atx"] + }, + "application/vnd.apache.arrow.file": { + "source": "iana" + }, + "application/vnd.apache.arrow.stream": { + "source": "iana" + }, + "application/vnd.apache.thrift.binary": { + "source": "iana" + }, + "application/vnd.apache.thrift.compact": { + "source": "iana" + }, + "application/vnd.apache.thrift.json": { + "source": "iana" + }, + "application/vnd.api+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.aplextor.warrp+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apothekende.reservation+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.apple.installer+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mpkg"] + }, + "application/vnd.apple.keynote": { + "source": "iana", + "extensions": ["key"] + }, + "application/vnd.apple.mpegurl": { + "source": "iana", + "extensions": ["m3u8"] + }, + "application/vnd.apple.numbers": { + "source": "iana", + "extensions": ["numbers"] + }, + "application/vnd.apple.pages": { + "source": "iana", + "extensions": ["pages"] + }, + "application/vnd.apple.pkpass": { + "compressible": false, + "extensions": ["pkpass"] + }, + "application/vnd.arastra.swi": { + "source": "iana" + }, + "application/vnd.aristanetworks.swi": { + "source": "iana", + "extensions": ["swi"] + }, + "application/vnd.artisan+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.artsquare": { + "source": "iana" + }, + "application/vnd.astraea-software.iota": { + "source": "iana", + "extensions": ["iota"] + }, + "application/vnd.audiograph": { + "source": "iana", + "extensions": ["aep"] + }, + "application/vnd.autopackage": { + "source": "iana" + }, + "application/vnd.avalon+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.avistar+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.balsamiq.bmml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["bmml"] + }, + "application/vnd.balsamiq.bmpr": { + "source": "iana" + }, + "application/vnd.banana-accounting": { + "source": "iana" + }, + "application/vnd.bbf.usp.error": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg": { + "source": "iana" + }, + "application/vnd.bbf.usp.msg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bekitzur-stech+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.bint.med-content": { + "source": "iana" + }, + "application/vnd.biopax.rdf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.blink-idb-value-wrapper": { + "source": "iana" + }, + "application/vnd.blueice.multipass": { + "source": "iana", + "extensions": ["mpm"] + }, + "application/vnd.bluetooth.ep.oob": { + "source": "iana" + }, + "application/vnd.bluetooth.le.oob": { + "source": "iana" + }, + "application/vnd.bmi": { + "source": "iana", + "extensions": ["bmi"] + }, + "application/vnd.bpf": { + "source": "iana" + }, + "application/vnd.bpf3": { + "source": "iana" + }, + "application/vnd.businessobjects": { + "source": "iana", + "extensions": ["rep"] + }, + "application/vnd.byu.uapi+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cab-jscript": { + "source": "iana" + }, + "application/vnd.canon-cpdl": { + "source": "iana" + }, + "application/vnd.canon-lips": { + "source": "iana" + }, + "application/vnd.capasystems-pg+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cendio.thinlinc.clientconf": { + "source": "iana" + }, + "application/vnd.century-systems.tcp_stream": { + "source": "iana" + }, + "application/vnd.chemdraw+xml": { + "source": "iana", + "compressible": true, + "extensions": ["cdxml"] + }, + "application/vnd.chess-pgn": { + "source": "iana" + }, + "application/vnd.chipnuts.karaoke-mmd": { + "source": "iana", + "extensions": ["mmd"] + }, + "application/vnd.ciedi": { + "source": "iana" + }, + "application/vnd.cinderella": { + "source": "iana", + "extensions": ["cdy"] + }, + "application/vnd.cirpack.isdn-ext": { + "source": "iana" + }, + "application/vnd.citationstyles.style+xml": { + "source": "iana", + "compressible": true, + "extensions": ["csl"] + }, + "application/vnd.claymore": { + "source": "iana", + "extensions": ["cla"] + }, + "application/vnd.cloanto.rp9": { + "source": "iana", + "extensions": ["rp9"] + }, + "application/vnd.clonk.c4group": { + "source": "iana", + "extensions": ["c4g","c4d","c4f","c4p","c4u"] + }, + "application/vnd.cluetrust.cartomobile-config": { + "source": "iana", + "extensions": ["c11amc"] + }, + "application/vnd.cluetrust.cartomobile-config-pkg": { + "source": "iana", + "extensions": ["c11amz"] + }, + "application/vnd.coffeescript": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.document-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.presentation-template": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet": { + "source": "iana" + }, + "application/vnd.collabio.xodocuments.spreadsheet-template": { + "source": "iana" + }, + "application/vnd.collection+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.doc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.collection.next+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.comicbook+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.comicbook-rar": { + "source": "iana" + }, + "application/vnd.commerce-battelle": { + "source": "iana" + }, + "application/vnd.commonspace": { + "source": "iana", + "extensions": ["csp"] + }, + "application/vnd.contact.cmsg": { + "source": "iana", + "extensions": ["cdbcmsg"] + }, + "application/vnd.coreos.ignition+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cosmocaller": { + "source": "iana", + "extensions": ["cmc"] + }, + "application/vnd.crick.clicker": { + "source": "iana", + "extensions": ["clkx"] + }, + "application/vnd.crick.clicker.keyboard": { + "source": "iana", + "extensions": ["clkk"] + }, + "application/vnd.crick.clicker.palette": { + "source": "iana", + "extensions": ["clkp"] + }, + "application/vnd.crick.clicker.template": { + "source": "iana", + "extensions": ["clkt"] + }, + "application/vnd.crick.clicker.wordbank": { + "source": "iana", + "extensions": ["clkw"] + }, + "application/vnd.criticaltools.wbs+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wbs"] + }, + "application/vnd.cryptii.pipe+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.crypto-shade-file": { + "source": "iana" + }, + "application/vnd.cryptomator.encrypted": { + "source": "iana" + }, + "application/vnd.cryptomator.vault": { + "source": "iana" + }, + "application/vnd.ctc-posml": { + "source": "iana", + "extensions": ["pml"] + }, + "application/vnd.ctct.ws+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cups-pdf": { + "source": "iana" + }, + "application/vnd.cups-postscript": { + "source": "iana" + }, + "application/vnd.cups-ppd": { + "source": "iana", + "extensions": ["ppd"] + }, + "application/vnd.cups-raster": { + "source": "iana" + }, + "application/vnd.cups-raw": { + "source": "iana" + }, + "application/vnd.curl": { + "source": "iana" + }, + "application/vnd.curl.car": { + "source": "apache", + "extensions": ["car"] + }, + "application/vnd.curl.pcurl": { + "source": "apache", + "extensions": ["pcurl"] + }, + "application/vnd.cyan.dean.root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.cybank": { + "source": "iana" + }, + "application/vnd.cyclonedx+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.cyclonedx+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.d2l.coursepackage1p0+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.d3m-dataset": { + "source": "iana" + }, + "application/vnd.d3m-problem": { + "source": "iana" + }, + "application/vnd.dart": { + "source": "iana", + "compressible": true, + "extensions": ["dart"] + }, + "application/vnd.data-vision.rdz": { + "source": "iana", + "extensions": ["rdz"] + }, + "application/vnd.datapackage+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dataresource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dbf": { + "source": "iana", + "extensions": ["dbf"] + }, + "application/vnd.debian.binary-package": { + "source": "iana" + }, + "application/vnd.dece.data": { + "source": "iana", + "extensions": ["uvf","uvvf","uvd","uvvd"] + }, + "application/vnd.dece.ttml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uvt","uvvt"] + }, + "application/vnd.dece.unspecified": { + "source": "iana", + "extensions": ["uvx","uvvx"] + }, + "application/vnd.dece.zip": { + "source": "iana", + "extensions": ["uvz","uvvz"] + }, + "application/vnd.denovo.fcselayout-link": { + "source": "iana", + "extensions": ["fe_launch"] + }, + "application/vnd.desmume.movie": { + "source": "iana" + }, + "application/vnd.dir-bi.plate-dl-nosuffix": { + "source": "iana" + }, + "application/vnd.dm.delegation+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dna": { + "source": "iana", + "extensions": ["dna"] + }, + "application/vnd.document+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.dolby.mlp": { + "source": "apache", + "extensions": ["mlp"] + }, + "application/vnd.dolby.mobile.1": { + "source": "iana" + }, + "application/vnd.dolby.mobile.2": { + "source": "iana" + }, + "application/vnd.doremir.scorecloud-binary-document": { + "source": "iana" + }, + "application/vnd.dpgraph": { + "source": "iana", + "extensions": ["dpg"] + }, + "application/vnd.dreamfactory": { + "source": "iana", + "extensions": ["dfac"] + }, + "application/vnd.drive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ds-keypoint": { + "source": "apache", + "extensions": ["kpxx"] + }, + "application/vnd.dtg.local": { + "source": "iana" + }, + "application/vnd.dtg.local.flash": { + "source": "iana" + }, + "application/vnd.dtg.local.html": { + "source": "iana" + }, + "application/vnd.dvb.ait": { + "source": "iana", + "extensions": ["ait"] + }, + "application/vnd.dvb.dvbisl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.dvbj": { + "source": "iana" + }, + "application/vnd.dvb.esgcontainer": { + "source": "iana" + }, + "application/vnd.dvb.ipdcdftnotifaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgaccess2": { + "source": "iana" + }, + "application/vnd.dvb.ipdcesgpdd": { + "source": "iana" + }, + "application/vnd.dvb.ipdcroaming": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-base": { + "source": "iana" + }, + "application/vnd.dvb.iptv.alfec-enhancement": { + "source": "iana" + }, + "application/vnd.dvb.notif-aggregate-root+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-container+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-generic+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-msglist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-ia-registration-response+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.notif-init+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.dvb.pfr": { + "source": "iana" + }, + "application/vnd.dvb.service": { + "source": "iana", + "extensions": ["svc"] + }, + "application/vnd.dxr": { + "source": "iana" + }, + "application/vnd.dynageo": { + "source": "iana", + "extensions": ["geo"] + }, + "application/vnd.dzr": { + "source": "iana" + }, + "application/vnd.easykaraoke.cdgdownload": { + "source": "iana" + }, + "application/vnd.ecdis-update": { + "source": "iana" + }, + "application/vnd.ecip.rlp": { + "source": "iana" + }, + "application/vnd.eclipse.ditto+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ecowin.chart": { + "source": "iana", + "extensions": ["mag"] + }, + "application/vnd.ecowin.filerequest": { + "source": "iana" + }, + "application/vnd.ecowin.fileupdate": { + "source": "iana" + }, + "application/vnd.ecowin.series": { + "source": "iana" + }, + "application/vnd.ecowin.seriesrequest": { + "source": "iana" + }, + "application/vnd.ecowin.seriesupdate": { + "source": "iana" + }, + "application/vnd.efi.img": { + "source": "iana" + }, + "application/vnd.efi.iso": { + "source": "iana" + }, + "application/vnd.emclient.accessrequest+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.enliven": { + "source": "iana", + "extensions": ["nml"] + }, + "application/vnd.enphase.envoy": { + "source": "iana" + }, + "application/vnd.eprints.data+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.epson.esf": { + "source": "iana", + "extensions": ["esf"] + }, + "application/vnd.epson.msf": { + "source": "iana", + "extensions": ["msf"] + }, + "application/vnd.epson.quickanime": { + "source": "iana", + "extensions": ["qam"] + }, + "application/vnd.epson.salt": { + "source": "iana", + "extensions": ["slt"] + }, + "application/vnd.epson.ssf": { + "source": "iana", + "extensions": ["ssf"] + }, + "application/vnd.ericsson.quickcall": { + "source": "iana" + }, + "application/vnd.espass-espass+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.eszigno3+xml": { + "source": "iana", + "compressible": true, + "extensions": ["es3","et3"] + }, + "application/vnd.etsi.aoc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.asic-e+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.asic-s+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.etsi.cug+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvcommand+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-bc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-cod+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsad-npvr+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvservice+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvsync+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.iptvueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mcid+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.mheg5": { + "source": "iana" + }, + "application/vnd.etsi.overload-control-policy-dataset+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.pstn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.sci+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.simservs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.timestamp-token": { + "source": "iana" + }, + "application/vnd.etsi.tsl+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.etsi.tsl.der": { + "source": "iana" + }, + "application/vnd.eu.kasparian.car+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.eudora.data": { + "source": "iana" + }, + "application/vnd.evolv.ecig.profile": { + "source": "iana" + }, + "application/vnd.evolv.ecig.settings": { + "source": "iana" + }, + "application/vnd.evolv.ecig.theme": { + "source": "iana" + }, + "application/vnd.exstream-empower+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.exstream-package": { + "source": "iana" + }, + "application/vnd.ezpix-album": { + "source": "iana", + "extensions": ["ez2"] + }, + "application/vnd.ezpix-package": { + "source": "iana", + "extensions": ["ez3"] + }, + "application/vnd.f-secure.mobile": { + "source": "iana" + }, + "application/vnd.familysearch.gedcom+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.fastcopy-disk-image": { + "source": "iana" + }, + "application/vnd.fdf": { + "source": "iana", + "extensions": ["fdf"] + }, + "application/vnd.fdsn.mseed": { + "source": "iana", + "extensions": ["mseed"] + }, + "application/vnd.fdsn.seed": { + "source": "iana", + "extensions": ["seed","dataless"] + }, + "application/vnd.ffsns": { + "source": "iana" + }, + "application/vnd.ficlab.flb+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.filmit.zfc": { + "source": "iana" + }, + "application/vnd.fints": { + "source": "iana" + }, + "application/vnd.firemonkeys.cloudcell": { + "source": "iana" + }, + "application/vnd.flographit": { + "source": "iana", + "extensions": ["gph"] + }, + "application/vnd.fluxtime.clip": { + "source": "iana", + "extensions": ["ftc"] + }, + "application/vnd.font-fontforge-sfd": { + "source": "iana" + }, + "application/vnd.framemaker": { + "source": "iana", + "extensions": ["fm","frame","maker","book"] + }, + "application/vnd.frogans.fnc": { + "source": "iana", + "extensions": ["fnc"] + }, + "application/vnd.frogans.ltf": { + "source": "iana", + "extensions": ["ltf"] + }, + "application/vnd.fsc.weblaunch": { + "source": "iana", + "extensions": ["fsc"] + }, + "application/vnd.fujifilm.fb.docuworks": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.binder": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujifilm.fb.jfi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.fujitsu.oasys": { + "source": "iana", + "extensions": ["oas"] + }, + "application/vnd.fujitsu.oasys2": { + "source": "iana", + "extensions": ["oa2"] + }, + "application/vnd.fujitsu.oasys3": { + "source": "iana", + "extensions": ["oa3"] + }, + "application/vnd.fujitsu.oasysgp": { + "source": "iana", + "extensions": ["fg5"] + }, + "application/vnd.fujitsu.oasysprs": { + "source": "iana", + "extensions": ["bh2"] + }, + "application/vnd.fujixerox.art-ex": { + "source": "iana" + }, + "application/vnd.fujixerox.art4": { + "source": "iana" + }, + "application/vnd.fujixerox.ddd": { + "source": "iana", + "extensions": ["ddd"] + }, + "application/vnd.fujixerox.docuworks": { + "source": "iana", + "extensions": ["xdw"] + }, + "application/vnd.fujixerox.docuworks.binder": { + "source": "iana", + "extensions": ["xbd"] + }, + "application/vnd.fujixerox.docuworks.container": { + "source": "iana" + }, + "application/vnd.fujixerox.hbpl": { + "source": "iana" + }, + "application/vnd.fut-misnet": { + "source": "iana" + }, + "application/vnd.futoin+cbor": { + "source": "iana" + }, + "application/vnd.futoin+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.fuzzysheet": { + "source": "iana", + "extensions": ["fzs"] + }, + "application/vnd.genomatix.tuxedo": { + "source": "iana", + "extensions": ["txd"] + }, + "application/vnd.gentics.grd+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geo+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.geocube+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.geogebra.file": { + "source": "iana", + "extensions": ["ggb"] + }, + "application/vnd.geogebra.slides": { + "source": "iana" + }, + "application/vnd.geogebra.tool": { + "source": "iana", + "extensions": ["ggt"] + }, + "application/vnd.geometry-explorer": { + "source": "iana", + "extensions": ["gex","gre"] + }, + "application/vnd.geonext": { + "source": "iana", + "extensions": ["gxt"] + }, + "application/vnd.geoplan": { + "source": "iana", + "extensions": ["g2w"] + }, + "application/vnd.geospace": { + "source": "iana", + "extensions": ["g3w"] + }, + "application/vnd.gerber": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt": { + "source": "iana" + }, + "application/vnd.globalplatform.card-content-mgt-response": { + "source": "iana" + }, + "application/vnd.gmx": { + "source": "iana", + "extensions": ["gmx"] + }, + "application/vnd.google-apps.document": { + "compressible": false, + "extensions": ["gdoc"] + }, + "application/vnd.google-apps.presentation": { + "compressible": false, + "extensions": ["gslides"] + }, + "application/vnd.google-apps.spreadsheet": { + "compressible": false, + "extensions": ["gsheet"] + }, + "application/vnd.google-earth.kml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["kml"] + }, + "application/vnd.google-earth.kmz": { + "source": "iana", + "compressible": false, + "extensions": ["kmz"] + }, + "application/vnd.gov.sk.e-form+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.gov.sk.e-form+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.gov.sk.xmldatacontainer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.grafeq": { + "source": "iana", + "extensions": ["gqf","gqs"] + }, + "application/vnd.gridmp": { + "source": "iana" + }, + "application/vnd.groove-account": { + "source": "iana", + "extensions": ["gac"] + }, + "application/vnd.groove-help": { + "source": "iana", + "extensions": ["ghf"] + }, + "application/vnd.groove-identity-message": { + "source": "iana", + "extensions": ["gim"] + }, + "application/vnd.groove-injector": { + "source": "iana", + "extensions": ["grv"] + }, + "application/vnd.groove-tool-message": { + "source": "iana", + "extensions": ["gtm"] + }, + "application/vnd.groove-tool-template": { + "source": "iana", + "extensions": ["tpl"] + }, + "application/vnd.groove-vcard": { + "source": "iana", + "extensions": ["vcg"] + }, + "application/vnd.hal+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hal+xml": { + "source": "iana", + "compressible": true, + "extensions": ["hal"] + }, + "application/vnd.handheld-entertainment+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zmm"] + }, + "application/vnd.hbci": { + "source": "iana", + "extensions": ["hbci"] + }, + "application/vnd.hc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hcl-bireports": { + "source": "iana" + }, + "application/vnd.hdt": { + "source": "iana" + }, + "application/vnd.heroku+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hhe.lesson-player": { + "source": "iana", + "extensions": ["les"] + }, + "application/vnd.hl7cda+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hl7v2+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.hp-hpgl": { + "source": "iana", + "extensions": ["hpgl"] + }, + "application/vnd.hp-hpid": { + "source": "iana", + "extensions": ["hpid"] + }, + "application/vnd.hp-hps": { + "source": "iana", + "extensions": ["hps"] + }, + "application/vnd.hp-jlyt": { + "source": "iana", + "extensions": ["jlt"] + }, + "application/vnd.hp-pcl": { + "source": "iana", + "extensions": ["pcl"] + }, + "application/vnd.hp-pclxl": { + "source": "iana", + "extensions": ["pclxl"] + }, + "application/vnd.httphone": { + "source": "iana" + }, + "application/vnd.hydrostatix.sof-data": { + "source": "iana", + "extensions": ["sfd-hdstx"] + }, + "application/vnd.hyper+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyper-item+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hyperdrive+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.hzn-3d-crossword": { + "source": "iana" + }, + "application/vnd.ibm.afplinedata": { + "source": "iana" + }, + "application/vnd.ibm.electronic-media": { + "source": "iana" + }, + "application/vnd.ibm.minipay": { + "source": "iana", + "extensions": ["mpy"] + }, + "application/vnd.ibm.modcap": { + "source": "iana", + "extensions": ["afp","listafp","list3820"] + }, + "application/vnd.ibm.rights-management": { + "source": "iana", + "extensions": ["irm"] + }, + "application/vnd.ibm.secure-container": { + "source": "iana", + "extensions": ["sc"] + }, + "application/vnd.iccprofile": { + "source": "iana", + "extensions": ["icc","icm"] + }, + "application/vnd.ieee.1905": { + "source": "iana" + }, + "application/vnd.igloader": { + "source": "iana", + "extensions": ["igl"] + }, + "application/vnd.imagemeter.folder+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.imagemeter.image+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.immervision-ivp": { + "source": "iana", + "extensions": ["ivp"] + }, + "application/vnd.immervision-ivu": { + "source": "iana", + "extensions": ["ivu"] + }, + "application/vnd.ims.imsccv1p1": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p2": { + "source": "iana" + }, + "application/vnd.ims.imsccv1p3": { + "source": "iana" + }, + "application/vnd.ims.lis.v2.result+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolconsumerprofile+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolproxy.id+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ims.lti.v2.toolsettings.simple+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.informedcontrol.rms+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.informix-visionary": { + "source": "iana" + }, + "application/vnd.infotech.project": { + "source": "iana" + }, + "application/vnd.infotech.project+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.innopath.wamp.notification": { + "source": "iana" + }, + "application/vnd.insors.igm": { + "source": "iana", + "extensions": ["igm"] + }, + "application/vnd.intercon.formnet": { + "source": "iana", + "extensions": ["xpw","xpx"] + }, + "application/vnd.intergeo": { + "source": "iana", + "extensions": ["i2g"] + }, + "application/vnd.intertrust.digibox": { + "source": "iana" + }, + "application/vnd.intertrust.nncp": { + "source": "iana" + }, + "application/vnd.intu.qbo": { + "source": "iana", + "extensions": ["qbo"] + }, + "application/vnd.intu.qfx": { + "source": "iana", + "extensions": ["qfx"] + }, + "application/vnd.iptc.g2.catalogitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.conceptitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.knowledgeitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.newsmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.packageitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.iptc.g2.planningitem+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ipunplugged.rcprofile": { + "source": "iana", + "extensions": ["rcprofile"] + }, + "application/vnd.irepository.package+xml": { + "source": "iana", + "compressible": true, + "extensions": ["irp"] + }, + "application/vnd.is-xpr": { + "source": "iana", + "extensions": ["xpr"] + }, + "application/vnd.isac.fcs": { + "source": "iana", + "extensions": ["fcs"] + }, + "application/vnd.iso11783-10+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.jam": { + "source": "iana", + "extensions": ["jam"] + }, + "application/vnd.japannet-directory-service": { + "source": "iana" + }, + "application/vnd.japannet-jpnstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-payment-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-registration": { + "source": "iana" + }, + "application/vnd.japannet-registration-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-setstore-wakeup": { + "source": "iana" + }, + "application/vnd.japannet-verification": { + "source": "iana" + }, + "application/vnd.japannet-verification-wakeup": { + "source": "iana" + }, + "application/vnd.jcp.javame.midlet-rms": { + "source": "iana", + "extensions": ["rms"] + }, + "application/vnd.jisp": { + "source": "iana", + "extensions": ["jisp"] + }, + "application/vnd.joost.joda-archive": { + "source": "iana", + "extensions": ["joda"] + }, + "application/vnd.jsk.isdn-ngn": { + "source": "iana" + }, + "application/vnd.kahootz": { + "source": "iana", + "extensions": ["ktz","ktr"] + }, + "application/vnd.kde.karbon": { + "source": "iana", + "extensions": ["karbon"] + }, + "application/vnd.kde.kchart": { + "source": "iana", + "extensions": ["chrt"] + }, + "application/vnd.kde.kformula": { + "source": "iana", + "extensions": ["kfo"] + }, + "application/vnd.kde.kivio": { + "source": "iana", + "extensions": ["flw"] + }, + "application/vnd.kde.kontour": { + "source": "iana", + "extensions": ["kon"] + }, + "application/vnd.kde.kpresenter": { + "source": "iana", + "extensions": ["kpr","kpt"] + }, + "application/vnd.kde.kspread": { + "source": "iana", + "extensions": ["ksp"] + }, + "application/vnd.kde.kword": { + "source": "iana", + "extensions": ["kwd","kwt"] + }, + "application/vnd.kenameaapp": { + "source": "iana", + "extensions": ["htke"] + }, + "application/vnd.kidspiration": { + "source": "iana", + "extensions": ["kia"] + }, + "application/vnd.kinar": { + "source": "iana", + "extensions": ["kne","knp"] + }, + "application/vnd.koan": { + "source": "iana", + "extensions": ["skp","skd","skt","skm"] + }, + "application/vnd.kodak-descriptor": { + "source": "iana", + "extensions": ["sse"] + }, + "application/vnd.las": { + "source": "iana" + }, + "application/vnd.las.las+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.las.las+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lasxml"] + }, + "application/vnd.laszip": { + "source": "iana" + }, + "application/vnd.leap+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.liberty-request+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.llamagraphics.life-balance.desktop": { + "source": "iana", + "extensions": ["lbd"] + }, + "application/vnd.llamagraphics.life-balance.exchange+xml": { + "source": "iana", + "compressible": true, + "extensions": ["lbe"] + }, + "application/vnd.logipipe.circuit+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.loom": { + "source": "iana" + }, + "application/vnd.lotus-1-2-3": { + "source": "iana", + "extensions": ["123"] + }, + "application/vnd.lotus-approach": { + "source": "iana", + "extensions": ["apr"] + }, + "application/vnd.lotus-freelance": { + "source": "iana", + "extensions": ["pre"] + }, + "application/vnd.lotus-notes": { + "source": "iana", + "extensions": ["nsf"] + }, + "application/vnd.lotus-organizer": { + "source": "iana", + "extensions": ["org"] + }, + "application/vnd.lotus-screencam": { + "source": "iana", + "extensions": ["scm"] + }, + "application/vnd.lotus-wordpro": { + "source": "iana", + "extensions": ["lwp"] + }, + "application/vnd.macports.portpkg": { + "source": "iana", + "extensions": ["portpkg"] + }, + "application/vnd.mapbox-vector-tile": { + "source": "iana", + "extensions": ["mvt"] + }, + "application/vnd.marlin.drm.actiontoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.conftoken+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.license+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.marlin.drm.mdcf": { + "source": "iana" + }, + "application/vnd.mason+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.maxar.archive.3tz+zip": { + "source": "iana", + "compressible": false + }, + "application/vnd.maxmind.maxmind-db": { + "source": "iana" + }, + "application/vnd.mcd": { + "source": "iana", + "extensions": ["mcd"] + }, + "application/vnd.medcalcdata": { + "source": "iana", + "extensions": ["mc1"] + }, + "application/vnd.mediastation.cdkey": { + "source": "iana", + "extensions": ["cdkey"] + }, + "application/vnd.meridian-slingshot": { + "source": "iana" + }, + "application/vnd.mfer": { + "source": "iana", + "extensions": ["mwf"] + }, + "application/vnd.mfmp": { + "source": "iana", + "extensions": ["mfm"] + }, + "application/vnd.micro+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.micrografx.flo": { + "source": "iana", + "extensions": ["flo"] + }, + "application/vnd.micrografx.igx": { + "source": "iana", + "extensions": ["igx"] + }, + "application/vnd.microsoft.portable-executable": { + "source": "iana" + }, + "application/vnd.microsoft.windows.thumbnail-cache": { + "source": "iana" + }, + "application/vnd.miele+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.mif": { + "source": "iana", + "extensions": ["mif"] + }, + "application/vnd.minisoft-hp3000-save": { + "source": "iana" + }, + "application/vnd.mitsubishi.misty-guard.trustweb": { + "source": "iana" + }, + "application/vnd.mobius.daf": { + "source": "iana", + "extensions": ["daf"] + }, + "application/vnd.mobius.dis": { + "source": "iana", + "extensions": ["dis"] + }, + "application/vnd.mobius.mbk": { + "source": "iana", + "extensions": ["mbk"] + }, + "application/vnd.mobius.mqy": { + "source": "iana", + "extensions": ["mqy"] + }, + "application/vnd.mobius.msl": { + "source": "iana", + "extensions": ["msl"] + }, + "application/vnd.mobius.plc": { + "source": "iana", + "extensions": ["plc"] + }, + "application/vnd.mobius.txf": { + "source": "iana", + "extensions": ["txf"] + }, + "application/vnd.mophun.application": { + "source": "iana", + "extensions": ["mpn"] + }, + "application/vnd.mophun.certificate": { + "source": "iana", + "extensions": ["mpc"] + }, + "application/vnd.motorola.flexsuite": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.adsi": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.fis": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.gotap": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.kmr": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.ttc": { + "source": "iana" + }, + "application/vnd.motorola.flexsuite.wem": { + "source": "iana" + }, + "application/vnd.motorola.iprm": { + "source": "iana" + }, + "application/vnd.mozilla.xul+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xul"] + }, + "application/vnd.ms-3mfdocument": { + "source": "iana" + }, + "application/vnd.ms-artgalry": { + "source": "iana", + "extensions": ["cil"] + }, + "application/vnd.ms-asf": { + "source": "iana" + }, + "application/vnd.ms-cab-compressed": { + "source": "iana", + "extensions": ["cab"] + }, + "application/vnd.ms-color.iccprofile": { + "source": "apache" + }, + "application/vnd.ms-excel": { + "source": "iana", + "compressible": false, + "extensions": ["xls","xlm","xla","xlc","xlt","xlw"] + }, + "application/vnd.ms-excel.addin.macroenabled.12": { + "source": "iana", + "extensions": ["xlam"] + }, + "application/vnd.ms-excel.sheet.binary.macroenabled.12": { + "source": "iana", + "extensions": ["xlsb"] + }, + "application/vnd.ms-excel.sheet.macroenabled.12": { + "source": "iana", + "extensions": ["xlsm"] + }, + "application/vnd.ms-excel.template.macroenabled.12": { + "source": "iana", + "extensions": ["xltm"] + }, + "application/vnd.ms-fontobject": { + "source": "iana", + "compressible": true, + "extensions": ["eot"] + }, + "application/vnd.ms-htmlhelp": { + "source": "iana", + "extensions": ["chm"] + }, + "application/vnd.ms-ims": { + "source": "iana", + "extensions": ["ims"] + }, + "application/vnd.ms-lrm": { + "source": "iana", + "extensions": ["lrm"] + }, + "application/vnd.ms-office.activex+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-officetheme": { + "source": "iana", + "extensions": ["thmx"] + }, + "application/vnd.ms-opentype": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-outlook": { + "compressible": false, + "extensions": ["msg"] + }, + "application/vnd.ms-package.obfuscated-opentype": { + "source": "apache" + }, + "application/vnd.ms-pki.seccat": { + "source": "apache", + "extensions": ["cat"] + }, + "application/vnd.ms-pki.stl": { + "source": "apache", + "extensions": ["stl"] + }, + "application/vnd.ms-playready.initiator+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-powerpoint": { + "source": "iana", + "compressible": false, + "extensions": ["ppt","pps","pot"] + }, + "application/vnd.ms-powerpoint.addin.macroenabled.12": { + "source": "iana", + "extensions": ["ppam"] + }, + "application/vnd.ms-powerpoint.presentation.macroenabled.12": { + "source": "iana", + "extensions": ["pptm"] + }, + "application/vnd.ms-powerpoint.slide.macroenabled.12": { + "source": "iana", + "extensions": ["sldm"] + }, + "application/vnd.ms-powerpoint.slideshow.macroenabled.12": { + "source": "iana", + "extensions": ["ppsm"] + }, + "application/vnd.ms-powerpoint.template.macroenabled.12": { + "source": "iana", + "extensions": ["potm"] + }, + "application/vnd.ms-printdevicecapabilities+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-printing.printticket+xml": { + "source": "apache", + "compressible": true + }, + "application/vnd.ms-printschematicket+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.ms-project": { + "source": "iana", + "extensions": ["mpp","mpt"] + }, + "application/vnd.ms-tnef": { + "source": "iana" + }, + "application/vnd.ms-windows.devicepairing": { + "source": "iana" + }, + "application/vnd.ms-windows.nwprinting.oob": { + "source": "iana" + }, + "application/vnd.ms-windows.printerpairing": { + "source": "iana" + }, + "application/vnd.ms-windows.wsd.oob": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.lic-resp": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-chlg-req": { + "source": "iana" + }, + "application/vnd.ms-wmdrm.meter-resp": { + "source": "iana" + }, + "application/vnd.ms-word.document.macroenabled.12": { + "source": "iana", + "extensions": ["docm"] + }, + "application/vnd.ms-word.template.macroenabled.12": { + "source": "iana", + "extensions": ["dotm"] + }, + "application/vnd.ms-works": { + "source": "iana", + "extensions": ["wps","wks","wcm","wdb"] + }, + "application/vnd.ms-wpl": { + "source": "iana", + "extensions": ["wpl"] + }, + "application/vnd.ms-xpsdocument": { + "source": "iana", + "compressible": false, + "extensions": ["xps"] + }, + "application/vnd.msa-disk-image": { + "source": "iana" + }, + "application/vnd.mseq": { + "source": "iana", + "extensions": ["mseq"] + }, + "application/vnd.msign": { + "source": "iana" + }, + "application/vnd.multiad.creator": { + "source": "iana" + }, + "application/vnd.multiad.creator.cif": { + "source": "iana" + }, + "application/vnd.music-niff": { + "source": "iana" + }, + "application/vnd.musician": { + "source": "iana", + "extensions": ["mus"] + }, + "application/vnd.muvee.style": { + "source": "iana", + "extensions": ["msty"] + }, + "application/vnd.mynfc": { + "source": "iana", + "extensions": ["taglet"] + }, + "application/vnd.nacamar.ybrid+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.ncd.control": { + "source": "iana" + }, + "application/vnd.ncd.reference": { + "source": "iana" + }, + "application/vnd.nearst.inv+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.nebumind.line": { + "source": "iana" + }, + "application/vnd.nervana": { + "source": "iana" + }, + "application/vnd.netfpx": { + "source": "iana" + }, + "application/vnd.neurolanguage.nlu": { + "source": "iana", + "extensions": ["nlu"] + }, + "application/vnd.nimn": { + "source": "iana" + }, + "application/vnd.nintendo.nitro.rom": { + "source": "iana" + }, + "application/vnd.nintendo.snes.rom": { + "source": "iana" + }, + "application/vnd.nitf": { + "source": "iana", + "extensions": ["ntf","nitf"] + }, + "application/vnd.noblenet-directory": { + "source": "iana", + "extensions": ["nnd"] + }, + "application/vnd.noblenet-sealer": { + "source": "iana", + "extensions": ["nns"] + }, + "application/vnd.noblenet-web": { + "source": "iana", + "extensions": ["nnw"] + }, + "application/vnd.nokia.catalogs": { + "source": "iana" + }, + "application/vnd.nokia.conml+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.conml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.iptv.config+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.isds-radio-presets": { + "source": "iana" + }, + "application/vnd.nokia.landmark+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.landmark+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.landmarkcollection+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.n-gage.ac+xml": { + "source": "iana", + "compressible": true, + "extensions": ["ac"] + }, + "application/vnd.nokia.n-gage.data": { + "source": "iana", + "extensions": ["ngdat"] + }, + "application/vnd.nokia.n-gage.symbian.install": { + "source": "iana", + "extensions": ["n-gage"] + }, + "application/vnd.nokia.ncd": { + "source": "iana" + }, + "application/vnd.nokia.pcd+wbxml": { + "source": "iana" + }, + "application/vnd.nokia.pcd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.nokia.radio-preset": { + "source": "iana", + "extensions": ["rpst"] + }, + "application/vnd.nokia.radio-presets": { + "source": "iana", + "extensions": ["rpss"] + }, + "application/vnd.novadigm.edm": { + "source": "iana", + "extensions": ["edm"] + }, + "application/vnd.novadigm.edx": { + "source": "iana", + "extensions": ["edx"] + }, + "application/vnd.novadigm.ext": { + "source": "iana", + "extensions": ["ext"] + }, + "application/vnd.ntt-local.content-share": { + "source": "iana" + }, + "application/vnd.ntt-local.file-transfer": { + "source": "iana" + }, + "application/vnd.ntt-local.ogw_remote-access": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_remote": { + "source": "iana" + }, + "application/vnd.ntt-local.sip-ta_tcp_stream": { + "source": "iana" + }, + "application/vnd.oasis.opendocument.chart": { + "source": "iana", + "extensions": ["odc"] + }, + "application/vnd.oasis.opendocument.chart-template": { + "source": "iana", + "extensions": ["otc"] + }, + "application/vnd.oasis.opendocument.database": { + "source": "iana", + "extensions": ["odb"] + }, + "application/vnd.oasis.opendocument.formula": { + "source": "iana", + "extensions": ["odf"] + }, + "application/vnd.oasis.opendocument.formula-template": { + "source": "iana", + "extensions": ["odft"] + }, + "application/vnd.oasis.opendocument.graphics": { + "source": "iana", + "compressible": false, + "extensions": ["odg"] + }, + "application/vnd.oasis.opendocument.graphics-template": { + "source": "iana", + "extensions": ["otg"] + }, + "application/vnd.oasis.opendocument.image": { + "source": "iana", + "extensions": ["odi"] + }, + "application/vnd.oasis.opendocument.image-template": { + "source": "iana", + "extensions": ["oti"] + }, + "application/vnd.oasis.opendocument.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["odp"] + }, + "application/vnd.oasis.opendocument.presentation-template": { + "source": "iana", + "extensions": ["otp"] + }, + "application/vnd.oasis.opendocument.spreadsheet": { + "source": "iana", + "compressible": false, + "extensions": ["ods"] + }, + "application/vnd.oasis.opendocument.spreadsheet-template": { + "source": "iana", + "extensions": ["ots"] + }, + "application/vnd.oasis.opendocument.text": { + "source": "iana", + "compressible": false, + "extensions": ["odt"] + }, + "application/vnd.oasis.opendocument.text-master": { + "source": "iana", + "extensions": ["odm"] + }, + "application/vnd.oasis.opendocument.text-template": { + "source": "iana", + "extensions": ["ott"] + }, + "application/vnd.oasis.opendocument.text-web": { + "source": "iana", + "extensions": ["oth"] + }, + "application/vnd.obn": { + "source": "iana" + }, + "application/vnd.ocf+cbor": { + "source": "iana" + }, + "application/vnd.oci.image.manifest.v1+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oftn.l10n+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessdownload+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.contentaccessstreaming+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.cspg-hexbinary": { + "source": "iana" + }, + "application/vnd.oipf.dae.svg+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.dae.xhtml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.mippvcontrolmessage+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.pae.gem": { + "source": "iana" + }, + "application/vnd.oipf.spdiscovery+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.spdlist+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.ueprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oipf.userprofile+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.olpc-sugar": { + "source": "iana", + "extensions": ["xo"] + }, + "application/vnd.oma-scws-config": { + "source": "iana" + }, + "application/vnd.oma-scws-http-request": { + "source": "iana" + }, + "application/vnd.oma-scws-http-response": { + "source": "iana" + }, + "application/vnd.oma.bcast.associated-procedure-parameter+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.drm-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.imd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.ltkm": { + "source": "iana" + }, + "application/vnd.oma.bcast.notification+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.provisioningtrigger": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgboot": { + "source": "iana" + }, + "application/vnd.oma.bcast.sgdd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sgdu": { + "source": "iana" + }, + "application/vnd.oma.bcast.simple-symbol-container": { + "source": "iana" + }, + "application/vnd.oma.bcast.smartcard-trigger+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.sprov+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.bcast.stkm": { + "source": "iana" + }, + "application/vnd.oma.cab-address-book+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-feature-handler+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-pcc+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-subs-invite+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.cab-user-prefs+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.dcd": { + "source": "iana" + }, + "application/vnd.oma.dcdc": { + "source": "iana" + }, + "application/vnd.oma.dd2+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dd2"] + }, + "application/vnd.oma.drm.risd+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.group-usage-list+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+cbor": { + "source": "iana" + }, + "application/vnd.oma.lwm2m+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.lwm2m+tlv": { + "source": "iana" + }, + "application/vnd.oma.pal+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.detailed-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.final-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.groups+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.invocation-descriptor+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.poc.optimized-progress-report+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.push": { + "source": "iana" + }, + "application/vnd.oma.scidm.messages+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oma.xcap-directory+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.omads-email+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-file+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omads-folder+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.omaloc-supl-init": { + "source": "iana" + }, + "application/vnd.onepager": { + "source": "iana" + }, + "application/vnd.onepagertamp": { + "source": "iana" + }, + "application/vnd.onepagertamx": { + "source": "iana" + }, + "application/vnd.onepagertat": { + "source": "iana" + }, + "application/vnd.onepagertatp": { + "source": "iana" + }, + "application/vnd.onepagertatx": { + "source": "iana" + }, + "application/vnd.openblox.game+xml": { + "source": "iana", + "compressible": true, + "extensions": ["obgx"] + }, + "application/vnd.openblox.game-binary": { + "source": "iana" + }, + "application/vnd.openeye.oeb": { + "source": "iana" + }, + "application/vnd.openofficeorg.extension": { + "source": "apache", + "extensions": ["oxt"] + }, + "application/vnd.openstreetmap.data+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osm"] + }, + "application/vnd.opentimestamps.ots": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.custom-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawing+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.extended-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation": { + "source": "iana", + "compressible": false, + "extensions": ["pptx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide": { + "source": "iana", + "extensions": ["sldx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow": { + "source": "iana", + "extensions": ["ppsx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.template": { + "source": "iana", + "extensions": ["potx"] + }, + "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": { + "source": "iana", + "compressible": false, + "extensions": ["xlsx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template": { + "source": "iana", + "extensions": ["xltx"] + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.theme+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.themeoverride+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.vmldrawing": { + "source": "iana" + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document": { + "source": "iana", + "compressible": false, + "extensions": ["docx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template": { + "source": "iana", + "extensions": ["dotx"] + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.core-properties+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.openxmlformats-package.relationships+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oracle.resource+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.orange.indata": { + "source": "iana" + }, + "application/vnd.osa.netdeploy": { + "source": "iana" + }, + "application/vnd.osgeo.mapguide.package": { + "source": "iana", + "extensions": ["mgp"] + }, + "application/vnd.osgi.bundle": { + "source": "iana" + }, + "application/vnd.osgi.dp": { + "source": "iana", + "extensions": ["dp"] + }, + "application/vnd.osgi.subsystem": { + "source": "iana", + "extensions": ["esa"] + }, + "application/vnd.otps.ct-kip+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.oxli.countgraph": { + "source": "iana" + }, + "application/vnd.pagerduty+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.palm": { + "source": "iana", + "extensions": ["pdb","pqa","oprc"] + }, + "application/vnd.panoply": { + "source": "iana" + }, + "application/vnd.paos.xml": { + "source": "iana" + }, + "application/vnd.patentdive": { + "source": "iana" + }, + "application/vnd.patientecommsdoc": { + "source": "iana" + }, + "application/vnd.pawaafile": { + "source": "iana", + "extensions": ["paw"] + }, + "application/vnd.pcos": { + "source": "iana" + }, + "application/vnd.pg.format": { + "source": "iana", + "extensions": ["str"] + }, + "application/vnd.pg.osasli": { + "source": "iana", + "extensions": ["ei6"] + }, + "application/vnd.piaccess.application-licence": { + "source": "iana" + }, + "application/vnd.picsel": { + "source": "iana", + "extensions": ["efif"] + }, + "application/vnd.pmi.widget": { + "source": "iana", + "extensions": ["wg"] + }, + "application/vnd.poc.group-advertisement+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.pocketlearn": { + "source": "iana", + "extensions": ["plf"] + }, + "application/vnd.powerbuilder6": { + "source": "iana", + "extensions": ["pbd"] + }, + "application/vnd.powerbuilder6-s": { + "source": "iana" + }, + "application/vnd.powerbuilder7": { + "source": "iana" + }, + "application/vnd.powerbuilder7-s": { + "source": "iana" + }, + "application/vnd.powerbuilder75": { + "source": "iana" + }, + "application/vnd.powerbuilder75-s": { + "source": "iana" + }, + "application/vnd.preminet": { + "source": "iana" + }, + "application/vnd.previewsystems.box": { + "source": "iana", + "extensions": ["box"] + }, + "application/vnd.proteus.magazine": { + "source": "iana", + "extensions": ["mgz"] + }, + "application/vnd.psfs": { + "source": "iana" + }, + "application/vnd.publishare-delta-tree": { + "source": "iana", + "extensions": ["qps"] + }, + "application/vnd.pvi.ptid1": { + "source": "iana", + "extensions": ["ptid"] + }, + "application/vnd.pwg-multiplexed": { + "source": "iana" + }, + "application/vnd.pwg-xhtml-print+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.qualcomm.brew-app-res": { + "source": "iana" + }, + "application/vnd.quarantainenet": { + "source": "iana" + }, + "application/vnd.quark.quarkxpress": { + "source": "iana", + "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"] + }, + "application/vnd.quobject-quoxdocument": { + "source": "iana" + }, + "application/vnd.radisys.moml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-conn+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-audit-stream+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-conf+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-base+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-detect+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-group+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-speech+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.radisys.msml-dialog-transform+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.rainstor.data": { + "source": "iana" + }, + "application/vnd.rapid": { + "source": "iana" + }, + "application/vnd.rar": { + "source": "iana", + "extensions": ["rar"] + }, + "application/vnd.realvnc.bed": { + "source": "iana", + "extensions": ["bed"] + }, + "application/vnd.recordare.musicxml": { + "source": "iana", + "extensions": ["mxl"] + }, + "application/vnd.recordare.musicxml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["musicxml"] + }, + "application/vnd.renlearn.rlprint": { + "source": "iana" + }, + "application/vnd.resilient.logic": { + "source": "iana" + }, + "application/vnd.restful+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.rig.cryptonote": { + "source": "iana", + "extensions": ["cryptonote"] + }, + "application/vnd.rim.cod": { + "source": "apache", + "extensions": ["cod"] + }, + "application/vnd.rn-realmedia": { + "source": "apache", + "extensions": ["rm"] + }, + "application/vnd.rn-realmedia-vbr": { + "source": "apache", + "extensions": ["rmvb"] + }, + "application/vnd.route66.link66+xml": { + "source": "iana", + "compressible": true, + "extensions": ["link66"] + }, + "application/vnd.rs-274x": { + "source": "iana" + }, + "application/vnd.ruckus.download": { + "source": "iana" + }, + "application/vnd.s3sms": { + "source": "iana" + }, + "application/vnd.sailingtracker.track": { + "source": "iana", + "extensions": ["st"] + }, + "application/vnd.sar": { + "source": "iana" + }, + "application/vnd.sbm.cid": { + "source": "iana" + }, + "application/vnd.sbm.mid2": { + "source": "iana" + }, + "application/vnd.scribus": { + "source": "iana" + }, + "application/vnd.sealed.3df": { + "source": "iana" + }, + "application/vnd.sealed.csf": { + "source": "iana" + }, + "application/vnd.sealed.doc": { + "source": "iana" + }, + "application/vnd.sealed.eml": { + "source": "iana" + }, + "application/vnd.sealed.mht": { + "source": "iana" + }, + "application/vnd.sealed.net": { + "source": "iana" + }, + "application/vnd.sealed.ppt": { + "source": "iana" + }, + "application/vnd.sealed.tiff": { + "source": "iana" + }, + "application/vnd.sealed.xls": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.html": { + "source": "iana" + }, + "application/vnd.sealedmedia.softseal.pdf": { + "source": "iana" + }, + "application/vnd.seemail": { + "source": "iana", + "extensions": ["see"] + }, + "application/vnd.seis+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.sema": { + "source": "iana", + "extensions": ["sema"] + }, + "application/vnd.semd": { + "source": "iana", + "extensions": ["semd"] + }, + "application/vnd.semf": { + "source": "iana", + "extensions": ["semf"] + }, + "application/vnd.shade-save-file": { + "source": "iana" + }, + "application/vnd.shana.informed.formdata": { + "source": "iana", + "extensions": ["ifm"] + }, + "application/vnd.shana.informed.formtemplate": { + "source": "iana", + "extensions": ["itp"] + }, + "application/vnd.shana.informed.interchange": { + "source": "iana", + "extensions": ["iif"] + }, + "application/vnd.shana.informed.package": { + "source": "iana", + "extensions": ["ipk"] + }, + "application/vnd.shootproof+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shopkick+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.shp": { + "source": "iana" + }, + "application/vnd.shx": { + "source": "iana" + }, + "application/vnd.sigrok.session": { + "source": "iana" + }, + "application/vnd.simtech-mindmapper": { + "source": "iana", + "extensions": ["twd","twds"] + }, + "application/vnd.siren+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.smaf": { + "source": "iana", + "extensions": ["mmf"] + }, + "application/vnd.smart.notebook": { + "source": "iana" + }, + "application/vnd.smart.teacher": { + "source": "iana", + "extensions": ["teacher"] + }, + "application/vnd.snesdev-page-table": { + "source": "iana" + }, + "application/vnd.software602.filler.form+xml": { + "source": "iana", + "compressible": true, + "extensions": ["fo"] + }, + "application/vnd.software602.filler.form-xml-zip": { + "source": "iana" + }, + "application/vnd.solent.sdkm+xml": { + "source": "iana", + "compressible": true, + "extensions": ["sdkm","sdkd"] + }, + "application/vnd.spotfire.dxp": { + "source": "iana", + "extensions": ["dxp"] + }, + "application/vnd.spotfire.sfs": { + "source": "iana", + "extensions": ["sfs"] + }, + "application/vnd.sqlite3": { + "source": "iana" + }, + "application/vnd.sss-cod": { + "source": "iana" + }, + "application/vnd.sss-dtf": { + "source": "iana" + }, + "application/vnd.sss-ntf": { + "source": "iana" + }, + "application/vnd.stardivision.calc": { + "source": "apache", + "extensions": ["sdc"] + }, + "application/vnd.stardivision.draw": { + "source": "apache", + "extensions": ["sda"] + }, + "application/vnd.stardivision.impress": { + "source": "apache", + "extensions": ["sdd"] + }, + "application/vnd.stardivision.math": { + "source": "apache", + "extensions": ["smf"] + }, + "application/vnd.stardivision.writer": { + "source": "apache", + "extensions": ["sdw","vor"] + }, + "application/vnd.stardivision.writer-global": { + "source": "apache", + "extensions": ["sgl"] + }, + "application/vnd.stepmania.package": { + "source": "iana", + "extensions": ["smzip"] + }, + "application/vnd.stepmania.stepchart": { + "source": "iana", + "extensions": ["sm"] + }, + "application/vnd.street-stream": { + "source": "iana" + }, + "application/vnd.sun.wadl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wadl"] + }, + "application/vnd.sun.xml.calc": { + "source": "apache", + "extensions": ["sxc"] + }, + "application/vnd.sun.xml.calc.template": { + "source": "apache", + "extensions": ["stc"] + }, + "application/vnd.sun.xml.draw": { + "source": "apache", + "extensions": ["sxd"] + }, + "application/vnd.sun.xml.draw.template": { + "source": "apache", + "extensions": ["std"] + }, + "application/vnd.sun.xml.impress": { + "source": "apache", + "extensions": ["sxi"] + }, + "application/vnd.sun.xml.impress.template": { + "source": "apache", + "extensions": ["sti"] + }, + "application/vnd.sun.xml.math": { + "source": "apache", + "extensions": ["sxm"] + }, + "application/vnd.sun.xml.writer": { + "source": "apache", + "extensions": ["sxw"] + }, + "application/vnd.sun.xml.writer.global": { + "source": "apache", + "extensions": ["sxg"] + }, + "application/vnd.sun.xml.writer.template": { + "source": "apache", + "extensions": ["stw"] + }, + "application/vnd.sus-calendar": { + "source": "iana", + "extensions": ["sus","susp"] + }, + "application/vnd.svd": { + "source": "iana", + "extensions": ["svd"] + }, + "application/vnd.swiftview-ics": { + "source": "iana" + }, + "application/vnd.sycle+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.syft+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.symbian.install": { + "source": "apache", + "extensions": ["sis","sisx"] + }, + "application/vnd.syncml+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xsm"] + }, + "application/vnd.syncml.dm+wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["bdm"] + }, + "application/vnd.syncml.dm+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["xdm"] + }, + "application/vnd.syncml.dm.notification": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmddf+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["ddf"] + }, + "application/vnd.syncml.dmtnds+wbxml": { + "source": "iana" + }, + "application/vnd.syncml.dmtnds+xml": { + "source": "iana", + "charset": "UTF-8", + "compressible": true + }, + "application/vnd.syncml.ds.notification": { + "source": "iana" + }, + "application/vnd.tableschema+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tao.intent-module-archive": { + "source": "iana", + "extensions": ["tao"] + }, + "application/vnd.tcpdump.pcap": { + "source": "iana", + "extensions": ["pcap","cap","dmp"] + }, + "application/vnd.think-cell.ppttc+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.tmd.mediaflex.api+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.tml": { + "source": "iana" + }, + "application/vnd.tmobile-livetv": { + "source": "iana", + "extensions": ["tmo"] + }, + "application/vnd.tri.onesource": { + "source": "iana" + }, + "application/vnd.trid.tpt": { + "source": "iana", + "extensions": ["tpt"] + }, + "application/vnd.triscape.mxs": { + "source": "iana", + "extensions": ["mxs"] + }, + "application/vnd.trueapp": { + "source": "iana", + "extensions": ["tra"] + }, + "application/vnd.truedoc": { + "source": "iana" + }, + "application/vnd.ubisoft.webplayer": { + "source": "iana" + }, + "application/vnd.ufdl": { + "source": "iana", + "extensions": ["ufd","ufdl"] + }, + "application/vnd.uiq.theme": { + "source": "iana", + "extensions": ["utz"] + }, + "application/vnd.umajin": { + "source": "iana", + "extensions": ["umj"] + }, + "application/vnd.unity": { + "source": "iana", + "extensions": ["unityweb"] + }, + "application/vnd.uoml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["uoml"] + }, + "application/vnd.uplanet.alert": { + "source": "iana" + }, + "application/vnd.uplanet.alert-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice": { + "source": "iana" + }, + "application/vnd.uplanet.bearer-choice-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop": { + "source": "iana" + }, + "application/vnd.uplanet.cacheop-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.channel": { + "source": "iana" + }, + "application/vnd.uplanet.channel-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.list": { + "source": "iana" + }, + "application/vnd.uplanet.list-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd": { + "source": "iana" + }, + "application/vnd.uplanet.listcmd-wbxml": { + "source": "iana" + }, + "application/vnd.uplanet.signal": { + "source": "iana" + }, + "application/vnd.uri-map": { + "source": "iana" + }, + "application/vnd.valve.source.material": { + "source": "iana" + }, + "application/vnd.vcx": { + "source": "iana", + "extensions": ["vcx"] + }, + "application/vnd.vd-study": { + "source": "iana" + }, + "application/vnd.vectorworks": { + "source": "iana" + }, + "application/vnd.vel+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.verimatrix.vcas": { + "source": "iana" + }, + "application/vnd.veritone.aion+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.veryant.thin": { + "source": "iana" + }, + "application/vnd.ves.encrypted": { + "source": "iana" + }, + "application/vnd.vidsoft.vidconference": { + "source": "iana" + }, + "application/vnd.visio": { + "source": "iana", + "extensions": ["vsd","vst","vss","vsw"] + }, + "application/vnd.visionary": { + "source": "iana", + "extensions": ["vis"] + }, + "application/vnd.vividence.scriptfile": { + "source": "iana" + }, + "application/vnd.vsf": { + "source": "iana", + "extensions": ["vsf"] + }, + "application/vnd.wap.sic": { + "source": "iana" + }, + "application/vnd.wap.slc": { + "source": "iana" + }, + "application/vnd.wap.wbxml": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["wbxml"] + }, + "application/vnd.wap.wmlc": { + "source": "iana", + "extensions": ["wmlc"] + }, + "application/vnd.wap.wmlscriptc": { + "source": "iana", + "extensions": ["wmlsc"] + }, + "application/vnd.webturbo": { + "source": "iana", + "extensions": ["wtb"] + }, + "application/vnd.wfa.dpp": { + "source": "iana" + }, + "application/vnd.wfa.p2p": { + "source": "iana" + }, + "application/vnd.wfa.wsc": { + "source": "iana" + }, + "application/vnd.windows.devicepairing": { + "source": "iana" + }, + "application/vnd.wmc": { + "source": "iana" + }, + "application/vnd.wmf.bootstrap": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica": { + "source": "iana" + }, + "application/vnd.wolfram.mathematica.package": { + "source": "iana" + }, + "application/vnd.wolfram.player": { + "source": "iana", + "extensions": ["nbp"] + }, + "application/vnd.wordperfect": { + "source": "iana", + "extensions": ["wpd"] + }, + "application/vnd.wqd": { + "source": "iana", + "extensions": ["wqd"] + }, + "application/vnd.wrq-hp3000-labelled": { + "source": "iana" + }, + "application/vnd.wt.stf": { + "source": "iana", + "extensions": ["stf"] + }, + "application/vnd.wv.csp+wbxml": { + "source": "iana" + }, + "application/vnd.wv.csp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.wv.ssp+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xacml+json": { + "source": "iana", + "compressible": true + }, + "application/vnd.xara": { + "source": "iana", + "extensions": ["xar"] + }, + "application/vnd.xfdl": { + "source": "iana", + "extensions": ["xfdl"] + }, + "application/vnd.xfdl.webform": { + "source": "iana" + }, + "application/vnd.xmi+xml": { + "source": "iana", + "compressible": true + }, + "application/vnd.xmpie.cpkg": { + "source": "iana" + }, + "application/vnd.xmpie.dpkg": { + "source": "iana" + }, + "application/vnd.xmpie.plan": { + "source": "iana" + }, + "application/vnd.xmpie.ppkg": { + "source": "iana" + }, + "application/vnd.xmpie.xlim": { + "source": "iana" + }, + "application/vnd.yamaha.hv-dic": { + "source": "iana", + "extensions": ["hvd"] + }, + "application/vnd.yamaha.hv-script": { + "source": "iana", + "extensions": ["hvs"] + }, + "application/vnd.yamaha.hv-voice": { + "source": "iana", + "extensions": ["hvp"] + }, + "application/vnd.yamaha.openscoreformat": { + "source": "iana", + "extensions": ["osf"] + }, + "application/vnd.yamaha.openscoreformat.osfpvg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["osfpvg"] + }, + "application/vnd.yamaha.remote-setup": { + "source": "iana" + }, + "application/vnd.yamaha.smaf-audio": { + "source": "iana", + "extensions": ["saf"] + }, + "application/vnd.yamaha.smaf-phrase": { + "source": "iana", + "extensions": ["spf"] + }, + "application/vnd.yamaha.through-ngn": { + "source": "iana" + }, + "application/vnd.yamaha.tunnel-udpencap": { + "source": "iana" + }, + "application/vnd.yaoweme": { + "source": "iana" + }, + "application/vnd.yellowriver-custom-menu": { + "source": "iana", + "extensions": ["cmp"] + }, + "application/vnd.youtube.yt": { + "source": "iana" + }, + "application/vnd.zul": { + "source": "iana", + "extensions": ["zir","zirz"] + }, + "application/vnd.zzazz.deck+xml": { + "source": "iana", + "compressible": true, + "extensions": ["zaz"] + }, + "application/voicexml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["vxml"] + }, + "application/voucher-cms+json": { + "source": "iana", + "compressible": true + }, + "application/vq-rtcpxr": { + "source": "iana" + }, + "application/wasm": { + "source": "iana", + "compressible": true, + "extensions": ["wasm"] + }, + "application/watcherinfo+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wif"] + }, + "application/webpush-options+json": { + "source": "iana", + "compressible": true + }, + "application/whoispp-query": { + "source": "iana" + }, + "application/whoispp-response": { + "source": "iana" + }, + "application/widget": { + "source": "iana", + "extensions": ["wgt"] + }, + "application/winhlp": { + "source": "apache", + "extensions": ["hlp"] + }, + "application/wita": { + "source": "iana" + }, + "application/wordperfect5.1": { + "source": "iana" + }, + "application/wsdl+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wsdl"] + }, + "application/wspolicy+xml": { + "source": "iana", + "compressible": true, + "extensions": ["wspolicy"] + }, + "application/x-7z-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["7z"] + }, + "application/x-abiword": { + "source": "apache", + "extensions": ["abw"] + }, + "application/x-ace-compressed": { + "source": "apache", + "extensions": ["ace"] + }, + "application/x-amf": { + "source": "apache" + }, + "application/x-apple-diskimage": { + "source": "apache", + "extensions": ["dmg"] + }, + "application/x-arj": { + "compressible": false, + "extensions": ["arj"] + }, + "application/x-authorware-bin": { + "source": "apache", + "extensions": ["aab","x32","u32","vox"] + }, + "application/x-authorware-map": { + "source": "apache", + "extensions": ["aam"] + }, + "application/x-authorware-seg": { + "source": "apache", + "extensions": ["aas"] + }, + "application/x-bcpio": { + "source": "apache", + "extensions": ["bcpio"] + }, + "application/x-bdoc": { + "compressible": false, + "extensions": ["bdoc"] + }, + "application/x-bittorrent": { + "source": "apache", + "extensions": ["torrent"] + }, + "application/x-blorb": { + "source": "apache", + "extensions": ["blb","blorb"] + }, + "application/x-bzip": { + "source": "apache", + "compressible": false, + "extensions": ["bz"] + }, + "application/x-bzip2": { + "source": "apache", + "compressible": false, + "extensions": ["bz2","boz"] + }, + "application/x-cbr": { + "source": "apache", + "extensions": ["cbr","cba","cbt","cbz","cb7"] + }, + "application/x-cdlink": { + "source": "apache", + "extensions": ["vcd"] + }, + "application/x-cfs-compressed": { + "source": "apache", + "extensions": ["cfs"] + }, + "application/x-chat": { + "source": "apache", + "extensions": ["chat"] + }, + "application/x-chess-pgn": { + "source": "apache", + "extensions": ["pgn"] + }, + "application/x-chrome-extension": { + "extensions": ["crx"] + }, + "application/x-cocoa": { + "source": "nginx", + "extensions": ["cco"] + }, + "application/x-compress": { + "source": "apache" + }, + "application/x-conference": { + "source": "apache", + "extensions": ["nsc"] + }, + "application/x-cpio": { + "source": "apache", + "extensions": ["cpio"] + }, + "application/x-csh": { + "source": "apache", + "extensions": ["csh"] + }, + "application/x-deb": { + "compressible": false + }, + "application/x-debian-package": { + "source": "apache", + "extensions": ["deb","udeb"] + }, + "application/x-dgc-compressed": { + "source": "apache", + "extensions": ["dgc"] + }, + "application/x-director": { + "source": "apache", + "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"] + }, + "application/x-doom": { + "source": "apache", + "extensions": ["wad"] + }, + "application/x-dtbncx+xml": { + "source": "apache", + "compressible": true, + "extensions": ["ncx"] + }, + "application/x-dtbook+xml": { + "source": "apache", + "compressible": true, + "extensions": ["dtb"] + }, + "application/x-dtbresource+xml": { + "source": "apache", + "compressible": true, + "extensions": ["res"] + }, + "application/x-dvi": { + "source": "apache", + "compressible": false, + "extensions": ["dvi"] + }, + "application/x-envoy": { + "source": "apache", + "extensions": ["evy"] + }, + "application/x-eva": { + "source": "apache", + "extensions": ["eva"] + }, + "application/x-font-bdf": { + "source": "apache", + "extensions": ["bdf"] + }, + "application/x-font-dos": { + "source": "apache" + }, + "application/x-font-framemaker": { + "source": "apache" + }, + "application/x-font-ghostscript": { + "source": "apache", + "extensions": ["gsf"] + }, + "application/x-font-libgrx": { + "source": "apache" + }, + "application/x-font-linux-psf": { + "source": "apache", + "extensions": ["psf"] + }, + "application/x-font-pcf": { + "source": "apache", + "extensions": ["pcf"] + }, + "application/x-font-snf": { + "source": "apache", + "extensions": ["snf"] + }, + "application/x-font-speedo": { + "source": "apache" + }, + "application/x-font-sunos-news": { + "source": "apache" + }, + "application/x-font-type1": { + "source": "apache", + "extensions": ["pfa","pfb","pfm","afm"] + }, + "application/x-font-vfont": { + "source": "apache" + }, + "application/x-freearc": { + "source": "apache", + "extensions": ["arc"] + }, + "application/x-futuresplash": { + "source": "apache", + "extensions": ["spl"] + }, + "application/x-gca-compressed": { + "source": "apache", + "extensions": ["gca"] + }, + "application/x-glulx": { + "source": "apache", + "extensions": ["ulx"] + }, + "application/x-gnumeric": { + "source": "apache", + "extensions": ["gnumeric"] + }, + "application/x-gramps-xml": { + "source": "apache", + "extensions": ["gramps"] + }, + "application/x-gtar": { + "source": "apache", + "extensions": ["gtar"] + }, + "application/x-gzip": { + "source": "apache" + }, + "application/x-hdf": { + "source": "apache", + "extensions": ["hdf"] + }, + "application/x-httpd-php": { + "compressible": true, + "extensions": ["php"] + }, + "application/x-install-instructions": { + "source": "apache", + "extensions": ["install"] + }, + "application/x-iso9660-image": { + "source": "apache", + "extensions": ["iso"] + }, + "application/x-iwork-keynote-sffkey": { + "extensions": ["key"] + }, + "application/x-iwork-numbers-sffnumbers": { + "extensions": ["numbers"] + }, + "application/x-iwork-pages-sffpages": { + "extensions": ["pages"] + }, + "application/x-java-archive-diff": { + "source": "nginx", + "extensions": ["jardiff"] + }, + "application/x-java-jnlp-file": { + "source": "apache", + "compressible": false, + "extensions": ["jnlp"] + }, + "application/x-javascript": { + "compressible": true + }, + "application/x-keepass2": { + "extensions": ["kdbx"] + }, + "application/x-latex": { + "source": "apache", + "compressible": false, + "extensions": ["latex"] + }, + "application/x-lua-bytecode": { + "extensions": ["luac"] + }, + "application/x-lzh-compressed": { + "source": "apache", + "extensions": ["lzh","lha"] + }, + "application/x-makeself": { + "source": "nginx", + "extensions": ["run"] + }, + "application/x-mie": { + "source": "apache", + "extensions": ["mie"] + }, + "application/x-mobipocket-ebook": { + "source": "apache", + "extensions": ["prc","mobi"] + }, + "application/x-mpegurl": { + "compressible": false + }, + "application/x-ms-application": { + "source": "apache", + "extensions": ["application"] + }, + "application/x-ms-shortcut": { + "source": "apache", + "extensions": ["lnk"] + }, + "application/x-ms-wmd": { + "source": "apache", + "extensions": ["wmd"] + }, + "application/x-ms-wmz": { + "source": "apache", + "extensions": ["wmz"] + }, + "application/x-ms-xbap": { + "source": "apache", + "extensions": ["xbap"] + }, + "application/x-msaccess": { + "source": "apache", + "extensions": ["mdb"] + }, + "application/x-msbinder": { + "source": "apache", + "extensions": ["obd"] + }, + "application/x-mscardfile": { + "source": "apache", + "extensions": ["crd"] + }, + "application/x-msclip": { + "source": "apache", + "extensions": ["clp"] + }, + "application/x-msdos-program": { + "extensions": ["exe"] + }, + "application/x-msdownload": { + "source": "apache", + "extensions": ["exe","dll","com","bat","msi"] + }, + "application/x-msmediaview": { + "source": "apache", + "extensions": ["mvb","m13","m14"] + }, + "application/x-msmetafile": { + "source": "apache", + "extensions": ["wmf","wmz","emf","emz"] + }, + "application/x-msmoney": { + "source": "apache", + "extensions": ["mny"] + }, + "application/x-mspublisher": { + "source": "apache", + "extensions": ["pub"] + }, + "application/x-msschedule": { + "source": "apache", + "extensions": ["scd"] + }, + "application/x-msterminal": { + "source": "apache", + "extensions": ["trm"] + }, + "application/x-mswrite": { + "source": "apache", + "extensions": ["wri"] + }, + "application/x-netcdf": { + "source": "apache", + "extensions": ["nc","cdf"] + }, + "application/x-ns-proxy-autoconfig": { + "compressible": true, + "extensions": ["pac"] + }, + "application/x-nzb": { + "source": "apache", + "extensions": ["nzb"] + }, + "application/x-perl": { + "source": "nginx", + "extensions": ["pl","pm"] + }, + "application/x-pilot": { + "source": "nginx", + "extensions": ["prc","pdb"] + }, + "application/x-pkcs12": { + "source": "apache", + "compressible": false, + "extensions": ["p12","pfx"] + }, + "application/x-pkcs7-certificates": { + "source": "apache", + "extensions": ["p7b","spc"] + }, + "application/x-pkcs7-certreqresp": { + "source": "apache", + "extensions": ["p7r"] + }, + "application/x-pki-message": { + "source": "iana" + }, + "application/x-rar-compressed": { + "source": "apache", + "compressible": false, + "extensions": ["rar"] + }, + "application/x-redhat-package-manager": { + "source": "nginx", + "extensions": ["rpm"] + }, + "application/x-research-info-systems": { + "source": "apache", + "extensions": ["ris"] + }, + "application/x-sea": { + "source": "nginx", + "extensions": ["sea"] + }, + "application/x-sh": { + "source": "apache", + "compressible": true, + "extensions": ["sh"] + }, + "application/x-shar": { + "source": "apache", + "extensions": ["shar"] + }, + "application/x-shockwave-flash": { + "source": "apache", + "compressible": false, + "extensions": ["swf"] + }, + "application/x-silverlight-app": { + "source": "apache", + "extensions": ["xap"] + }, + "application/x-sql": { + "source": "apache", + "extensions": ["sql"] + }, + "application/x-stuffit": { + "source": "apache", + "compressible": false, + "extensions": ["sit"] + }, + "application/x-stuffitx": { + "source": "apache", + "extensions": ["sitx"] + }, + "application/x-subrip": { + "source": "apache", + "extensions": ["srt"] + }, + "application/x-sv4cpio": { + "source": "apache", + "extensions": ["sv4cpio"] + }, + "application/x-sv4crc": { + "source": "apache", + "extensions": ["sv4crc"] + }, + "application/x-t3vm-image": { + "source": "apache", + "extensions": ["t3"] + }, + "application/x-tads": { + "source": "apache", + "extensions": ["gam"] + }, + "application/x-tar": { + "source": "apache", + "compressible": true, + "extensions": ["tar"] + }, + "application/x-tcl": { + "source": "apache", + "extensions": ["tcl","tk"] + }, + "application/x-tex": { + "source": "apache", + "extensions": ["tex"] + }, + "application/x-tex-tfm": { + "source": "apache", + "extensions": ["tfm"] + }, + "application/x-texinfo": { + "source": "apache", + "extensions": ["texinfo","texi"] + }, + "application/x-tgif": { + "source": "apache", + "extensions": ["obj"] + }, + "application/x-ustar": { + "source": "apache", + "extensions": ["ustar"] + }, + "application/x-virtualbox-hdd": { + "compressible": true, + "extensions": ["hdd"] + }, + "application/x-virtualbox-ova": { + "compressible": true, + "extensions": ["ova"] + }, + "application/x-virtualbox-ovf": { + "compressible": true, + "extensions": ["ovf"] + }, + "application/x-virtualbox-vbox": { + "compressible": true, + "extensions": ["vbox"] + }, + "application/x-virtualbox-vbox-extpack": { + "compressible": false, + "extensions": ["vbox-extpack"] + }, + "application/x-virtualbox-vdi": { + "compressible": true, + "extensions": ["vdi"] + }, + "application/x-virtualbox-vhd": { + "compressible": true, + "extensions": ["vhd"] + }, + "application/x-virtualbox-vmdk": { + "compressible": true, + "extensions": ["vmdk"] + }, + "application/x-wais-source": { + "source": "apache", + "extensions": ["src"] + }, + "application/x-web-app-manifest+json": { + "compressible": true, + "extensions": ["webapp"] + }, + "application/x-www-form-urlencoded": { + "source": "iana", + "compressible": true + }, + "application/x-x509-ca-cert": { + "source": "iana", + "extensions": ["der","crt","pem"] + }, + "application/x-x509-ca-ra-cert": { + "source": "iana" + }, + "application/x-x509-next-ca-cert": { + "source": "iana" + }, + "application/x-xfig": { + "source": "apache", + "extensions": ["fig"] + }, + "application/x-xliff+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xlf"] + }, + "application/x-xpinstall": { + "source": "apache", + "compressible": false, + "extensions": ["xpi"] + }, + "application/x-xz": { + "source": "apache", + "extensions": ["xz"] + }, + "application/x-zmachine": { + "source": "apache", + "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"] + }, + "application/x400-bp": { + "source": "iana" + }, + "application/xacml+xml": { + "source": "iana", + "compressible": true + }, + "application/xaml+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xaml"] + }, + "application/xcap-att+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xav"] + }, + "application/xcap-caps+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xca"] + }, + "application/xcap-diff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xdf"] + }, + "application/xcap-el+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xel"] + }, + "application/xcap-error+xml": { + "source": "iana", + "compressible": true + }, + "application/xcap-ns+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xns"] + }, + "application/xcon-conference-info+xml": { + "source": "iana", + "compressible": true + }, + "application/xcon-conference-info-diff+xml": { + "source": "iana", + "compressible": true + }, + "application/xenc+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xenc"] + }, + "application/xhtml+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xhtml","xht"] + }, + "application/xhtml-voice+xml": { + "source": "apache", + "compressible": true + }, + "application/xliff+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xlf"] + }, + "application/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml","xsl","xsd","rng"] + }, + "application/xml-dtd": { + "source": "iana", + "compressible": true, + "extensions": ["dtd"] + }, + "application/xml-external-parsed-entity": { + "source": "iana" + }, + "application/xml-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/xmpp+xml": { + "source": "iana", + "compressible": true + }, + "application/xop+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xop"] + }, + "application/xproc+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xpl"] + }, + "application/xslt+xml": { + "source": "iana", + "compressible": true, + "extensions": ["xsl","xslt"] + }, + "application/xspf+xml": { + "source": "apache", + "compressible": true, + "extensions": ["xspf"] + }, + "application/xv+xml": { + "source": "iana", + "compressible": true, + "extensions": ["mxml","xhvml","xvml","xvm"] + }, + "application/yang": { + "source": "iana", + "extensions": ["yang"] + }, + "application/yang-data+json": { + "source": "iana", + "compressible": true + }, + "application/yang-data+xml": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+json": { + "source": "iana", + "compressible": true + }, + "application/yang-patch+xml": { + "source": "iana", + "compressible": true + }, + "application/yin+xml": { + "source": "iana", + "compressible": true, + "extensions": ["yin"] + }, + "application/zip": { + "source": "iana", + "compressible": false, + "extensions": ["zip"] + }, + "application/zlib": { + "source": "iana" + }, + "application/zstd": { + "source": "iana" + }, + "audio/1d-interleaved-parityfec": { + "source": "iana" + }, + "audio/32kadpcm": { + "source": "iana" + }, + "audio/3gpp": { + "source": "iana", + "compressible": false, + "extensions": ["3gpp"] + }, + "audio/3gpp2": { + "source": "iana" + }, + "audio/aac": { + "source": "iana" + }, + "audio/ac3": { + "source": "iana" + }, + "audio/adpcm": { + "source": "apache", + "extensions": ["adp"] + }, + "audio/amr": { + "source": "iana", + "extensions": ["amr"] + }, + "audio/amr-wb": { + "source": "iana" + }, + "audio/amr-wb+": { + "source": "iana" + }, + "audio/aptx": { + "source": "iana" + }, + "audio/asc": { + "source": "iana" + }, + "audio/atrac-advanced-lossless": { + "source": "iana" + }, + "audio/atrac-x": { + "source": "iana" + }, + "audio/atrac3": { + "source": "iana" + }, + "audio/basic": { + "source": "iana", + "compressible": false, + "extensions": ["au","snd"] + }, + "audio/bv16": { + "source": "iana" + }, + "audio/bv32": { + "source": "iana" + }, + "audio/clearmode": { + "source": "iana" + }, + "audio/cn": { + "source": "iana" + }, + "audio/dat12": { + "source": "iana" + }, + "audio/dls": { + "source": "iana" + }, + "audio/dsr-es201108": { + "source": "iana" + }, + "audio/dsr-es202050": { + "source": "iana" + }, + "audio/dsr-es202211": { + "source": "iana" + }, + "audio/dsr-es202212": { + "source": "iana" + }, + "audio/dv": { + "source": "iana" + }, + "audio/dvi4": { + "source": "iana" + }, + "audio/eac3": { + "source": "iana" + }, + "audio/encaprtp": { + "source": "iana" + }, + "audio/evrc": { + "source": "iana" + }, + "audio/evrc-qcp": { + "source": "iana" + }, + "audio/evrc0": { + "source": "iana" + }, + "audio/evrc1": { + "source": "iana" + }, + "audio/evrcb": { + "source": "iana" + }, + "audio/evrcb0": { + "source": "iana" + }, + "audio/evrcb1": { + "source": "iana" + }, + "audio/evrcnw": { + "source": "iana" + }, + "audio/evrcnw0": { + "source": "iana" + }, + "audio/evrcnw1": { + "source": "iana" + }, + "audio/evrcwb": { + "source": "iana" + }, + "audio/evrcwb0": { + "source": "iana" + }, + "audio/evrcwb1": { + "source": "iana" + }, + "audio/evs": { + "source": "iana" + }, + "audio/flexfec": { + "source": "iana" + }, + "audio/fwdred": { + "source": "iana" + }, + "audio/g711-0": { + "source": "iana" + }, + "audio/g719": { + "source": "iana" + }, + "audio/g722": { + "source": "iana" + }, + "audio/g7221": { + "source": "iana" + }, + "audio/g723": { + "source": "iana" + }, + "audio/g726-16": { + "source": "iana" + }, + "audio/g726-24": { + "source": "iana" + }, + "audio/g726-32": { + "source": "iana" + }, + "audio/g726-40": { + "source": "iana" + }, + "audio/g728": { + "source": "iana" + }, + "audio/g729": { + "source": "iana" + }, + "audio/g7291": { + "source": "iana" + }, + "audio/g729d": { + "source": "iana" + }, + "audio/g729e": { + "source": "iana" + }, + "audio/gsm": { + "source": "iana" + }, + "audio/gsm-efr": { + "source": "iana" + }, + "audio/gsm-hr-08": { + "source": "iana" + }, + "audio/ilbc": { + "source": "iana" + }, + "audio/ip-mr_v2.5": { + "source": "iana" + }, + "audio/isac": { + "source": "apache" + }, + "audio/l16": { + "source": "iana" + }, + "audio/l20": { + "source": "iana" + }, + "audio/l24": { + "source": "iana", + "compressible": false + }, + "audio/l8": { + "source": "iana" + }, + "audio/lpc": { + "source": "iana" + }, + "audio/melp": { + "source": "iana" + }, + "audio/melp1200": { + "source": "iana" + }, + "audio/melp2400": { + "source": "iana" + }, + "audio/melp600": { + "source": "iana" + }, + "audio/mhas": { + "source": "iana" + }, + "audio/midi": { + "source": "apache", + "extensions": ["mid","midi","kar","rmi"] + }, + "audio/mobile-xmf": { + "source": "iana", + "extensions": ["mxmf"] + }, + "audio/mp3": { + "compressible": false, + "extensions": ["mp3"] + }, + "audio/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["m4a","mp4a"] + }, + "audio/mp4a-latm": { + "source": "iana" + }, + "audio/mpa": { + "source": "iana" + }, + "audio/mpa-robust": { + "source": "iana" + }, + "audio/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"] + }, + "audio/mpeg4-generic": { + "source": "iana" + }, + "audio/musepack": { + "source": "apache" + }, + "audio/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["oga","ogg","spx","opus"] + }, + "audio/opus": { + "source": "iana" + }, + "audio/parityfec": { + "source": "iana" + }, + "audio/pcma": { + "source": "iana" + }, + "audio/pcma-wb": { + "source": "iana" + }, + "audio/pcmu": { + "source": "iana" + }, + "audio/pcmu-wb": { + "source": "iana" + }, + "audio/prs.sid": { + "source": "iana" + }, + "audio/qcelp": { + "source": "iana" + }, + "audio/raptorfec": { + "source": "iana" + }, + "audio/red": { + "source": "iana" + }, + "audio/rtp-enc-aescm128": { + "source": "iana" + }, + "audio/rtp-midi": { + "source": "iana" + }, + "audio/rtploopback": { + "source": "iana" + }, + "audio/rtx": { + "source": "iana" + }, + "audio/s3m": { + "source": "apache", + "extensions": ["s3m"] + }, + "audio/scip": { + "source": "iana" + }, + "audio/silk": { + "source": "apache", + "extensions": ["sil"] + }, + "audio/smv": { + "source": "iana" + }, + "audio/smv-qcp": { + "source": "iana" + }, + "audio/smv0": { + "source": "iana" + }, + "audio/sofa": { + "source": "iana" + }, + "audio/sp-midi": { + "source": "iana" + }, + "audio/speex": { + "source": "iana" + }, + "audio/t140c": { + "source": "iana" + }, + "audio/t38": { + "source": "iana" + }, + "audio/telephone-event": { + "source": "iana" + }, + "audio/tetra_acelp": { + "source": "iana" + }, + "audio/tetra_acelp_bb": { + "source": "iana" + }, + "audio/tone": { + "source": "iana" + }, + "audio/tsvcis": { + "source": "iana" + }, + "audio/uemclip": { + "source": "iana" + }, + "audio/ulpfec": { + "source": "iana" + }, + "audio/usac": { + "source": "iana" + }, + "audio/vdvi": { + "source": "iana" + }, + "audio/vmr-wb": { + "source": "iana" + }, + "audio/vnd.3gpp.iufp": { + "source": "iana" + }, + "audio/vnd.4sb": { + "source": "iana" + }, + "audio/vnd.audiokoz": { + "source": "iana" + }, + "audio/vnd.celp": { + "source": "iana" + }, + "audio/vnd.cisco.nse": { + "source": "iana" + }, + "audio/vnd.cmles.radio-events": { + "source": "iana" + }, + "audio/vnd.cns.anp1": { + "source": "iana" + }, + "audio/vnd.cns.inf1": { + "source": "iana" + }, + "audio/vnd.dece.audio": { + "source": "iana", + "extensions": ["uva","uvva"] + }, + "audio/vnd.digital-winds": { + "source": "iana", + "extensions": ["eol"] + }, + "audio/vnd.dlna.adts": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.1": { + "source": "iana" + }, + "audio/vnd.dolby.heaac.2": { + "source": "iana" + }, + "audio/vnd.dolby.mlp": { + "source": "iana" + }, + "audio/vnd.dolby.mps": { + "source": "iana" + }, + "audio/vnd.dolby.pl2": { + "source": "iana" + }, + "audio/vnd.dolby.pl2x": { + "source": "iana" + }, + "audio/vnd.dolby.pl2z": { + "source": "iana" + }, + "audio/vnd.dolby.pulse.1": { + "source": "iana" + }, + "audio/vnd.dra": { + "source": "iana", + "extensions": ["dra"] + }, + "audio/vnd.dts": { + "source": "iana", + "extensions": ["dts"] + }, + "audio/vnd.dts.hd": { + "source": "iana", + "extensions": ["dtshd"] + }, + "audio/vnd.dts.uhd": { + "source": "iana" + }, + "audio/vnd.dvb.file": { + "source": "iana" + }, + "audio/vnd.everad.plj": { + "source": "iana" + }, + "audio/vnd.hns.audio": { + "source": "iana" + }, + "audio/vnd.lucent.voice": { + "source": "iana", + "extensions": ["lvp"] + }, + "audio/vnd.ms-playready.media.pya": { + "source": "iana", + "extensions": ["pya"] + }, + "audio/vnd.nokia.mobile-xmf": { + "source": "iana" + }, + "audio/vnd.nortel.vbk": { + "source": "iana" + }, + "audio/vnd.nuera.ecelp4800": { + "source": "iana", + "extensions": ["ecelp4800"] + }, + "audio/vnd.nuera.ecelp7470": { + "source": "iana", + "extensions": ["ecelp7470"] + }, + "audio/vnd.nuera.ecelp9600": { + "source": "iana", + "extensions": ["ecelp9600"] + }, + "audio/vnd.octel.sbc": { + "source": "iana" + }, + "audio/vnd.presonus.multitrack": { + "source": "iana" + }, + "audio/vnd.qcelp": { + "source": "iana" + }, + "audio/vnd.rhetorex.32kadpcm": { + "source": "iana" + }, + "audio/vnd.rip": { + "source": "iana", + "extensions": ["rip"] + }, + "audio/vnd.rn-realaudio": { + "compressible": false + }, + "audio/vnd.sealedmedia.softseal.mpeg": { + "source": "iana" + }, + "audio/vnd.vmx.cvsd": { + "source": "iana" + }, + "audio/vnd.wave": { + "compressible": false + }, + "audio/vorbis": { + "source": "iana", + "compressible": false + }, + "audio/vorbis-config": { + "source": "iana" + }, + "audio/wav": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/wave": { + "compressible": false, + "extensions": ["wav"] + }, + "audio/webm": { + "source": "apache", + "compressible": false, + "extensions": ["weba"] + }, + "audio/x-aac": { + "source": "apache", + "compressible": false, + "extensions": ["aac"] + }, + "audio/x-aiff": { + "source": "apache", + "extensions": ["aif","aiff","aifc"] + }, + "audio/x-caf": { + "source": "apache", + "compressible": false, + "extensions": ["caf"] + }, + "audio/x-flac": { + "source": "apache", + "extensions": ["flac"] + }, + "audio/x-m4a": { + "source": "nginx", + "extensions": ["m4a"] + }, + "audio/x-matroska": { + "source": "apache", + "extensions": ["mka"] + }, + "audio/x-mpegurl": { + "source": "apache", + "extensions": ["m3u"] + }, + "audio/x-ms-wax": { + "source": "apache", + "extensions": ["wax"] + }, + "audio/x-ms-wma": { + "source": "apache", + "extensions": ["wma"] + }, + "audio/x-pn-realaudio": { + "source": "apache", + "extensions": ["ram","ra"] + }, + "audio/x-pn-realaudio-plugin": { + "source": "apache", + "extensions": ["rmp"] + }, + "audio/x-realaudio": { + "source": "nginx", + "extensions": ["ra"] + }, + "audio/x-tta": { + "source": "apache" + }, + "audio/x-wav": { + "source": "apache", + "extensions": ["wav"] + }, + "audio/xm": { + "source": "apache", + "extensions": ["xm"] + }, + "chemical/x-cdx": { + "source": "apache", + "extensions": ["cdx"] + }, + "chemical/x-cif": { + "source": "apache", + "extensions": ["cif"] + }, + "chemical/x-cmdf": { + "source": "apache", + "extensions": ["cmdf"] + }, + "chemical/x-cml": { + "source": "apache", + "extensions": ["cml"] + }, + "chemical/x-csml": { + "source": "apache", + "extensions": ["csml"] + }, + "chemical/x-pdb": { + "source": "apache" + }, + "chemical/x-xyz": { + "source": "apache", + "extensions": ["xyz"] + }, + "font/collection": { + "source": "iana", + "extensions": ["ttc"] + }, + "font/otf": { + "source": "iana", + "compressible": true, + "extensions": ["otf"] + }, + "font/sfnt": { + "source": "iana" + }, + "font/ttf": { + "source": "iana", + "compressible": true, + "extensions": ["ttf"] + }, + "font/woff": { + "source": "iana", + "extensions": ["woff"] + }, + "font/woff2": { + "source": "iana", + "extensions": ["woff2"] + }, + "image/aces": { + "source": "iana", + "extensions": ["exr"] + }, + "image/apng": { + "compressible": false, + "extensions": ["apng"] + }, + "image/avci": { + "source": "iana", + "extensions": ["avci"] + }, + "image/avcs": { + "source": "iana", + "extensions": ["avcs"] + }, + "image/avif": { + "source": "iana", + "compressible": false, + "extensions": ["avif"] + }, + "image/bmp": { + "source": "iana", + "compressible": true, + "extensions": ["bmp"] + }, + "image/cgm": { + "source": "iana", + "extensions": ["cgm"] + }, + "image/dicom-rle": { + "source": "iana", + "extensions": ["drle"] + }, + "image/emf": { + "source": "iana", + "extensions": ["emf"] + }, + "image/fits": { + "source": "iana", + "extensions": ["fits"] + }, + "image/g3fax": { + "source": "iana", + "extensions": ["g3"] + }, + "image/gif": { + "source": "iana", + "compressible": false, + "extensions": ["gif"] + }, + "image/heic": { + "source": "iana", + "extensions": ["heic"] + }, + "image/heic-sequence": { + "source": "iana", + "extensions": ["heics"] + }, + "image/heif": { + "source": "iana", + "extensions": ["heif"] + }, + "image/heif-sequence": { + "source": "iana", + "extensions": ["heifs"] + }, + "image/hej2k": { + "source": "iana", + "extensions": ["hej2"] + }, + "image/hsj2": { + "source": "iana", + "extensions": ["hsj2"] + }, + "image/ief": { + "source": "iana", + "extensions": ["ief"] + }, + "image/jls": { + "source": "iana", + "extensions": ["jls"] + }, + "image/jp2": { + "source": "iana", + "compressible": false, + "extensions": ["jp2","jpg2"] + }, + "image/jpeg": { + "source": "iana", + "compressible": false, + "extensions": ["jpeg","jpg","jpe"] + }, + "image/jph": { + "source": "iana", + "extensions": ["jph"] + }, + "image/jphc": { + "source": "iana", + "extensions": ["jhc"] + }, + "image/jpm": { + "source": "iana", + "compressible": false, + "extensions": ["jpm"] + }, + "image/jpx": { + "source": "iana", + "compressible": false, + "extensions": ["jpx","jpf"] + }, + "image/jxr": { + "source": "iana", + "extensions": ["jxr"] + }, + "image/jxra": { + "source": "iana", + "extensions": ["jxra"] + }, + "image/jxrs": { + "source": "iana", + "extensions": ["jxrs"] + }, + "image/jxs": { + "source": "iana", + "extensions": ["jxs"] + }, + "image/jxsc": { + "source": "iana", + "extensions": ["jxsc"] + }, + "image/jxsi": { + "source": "iana", + "extensions": ["jxsi"] + }, + "image/jxss": { + "source": "iana", + "extensions": ["jxss"] + }, + "image/ktx": { + "source": "iana", + "extensions": ["ktx"] + }, + "image/ktx2": { + "source": "iana", + "extensions": ["ktx2"] + }, + "image/naplps": { + "source": "iana" + }, + "image/pjpeg": { + "compressible": false + }, + "image/png": { + "source": "iana", + "compressible": false, + "extensions": ["png"] + }, + "image/prs.btif": { + "source": "iana", + "extensions": ["btif"] + }, + "image/prs.pti": { + "source": "iana", + "extensions": ["pti"] + }, + "image/pwg-raster": { + "source": "iana" + }, + "image/sgi": { + "source": "apache", + "extensions": ["sgi"] + }, + "image/svg+xml": { + "source": "iana", + "compressible": true, + "extensions": ["svg","svgz"] + }, + "image/t38": { + "source": "iana", + "extensions": ["t38"] + }, + "image/tiff": { + "source": "iana", + "compressible": false, + "extensions": ["tif","tiff"] + }, + "image/tiff-fx": { + "source": "iana", + "extensions": ["tfx"] + }, + "image/vnd.adobe.photoshop": { + "source": "iana", + "compressible": true, + "extensions": ["psd"] + }, + "image/vnd.airzip.accelerator.azv": { + "source": "iana", + "extensions": ["azv"] + }, + "image/vnd.cns.inf2": { + "source": "iana" + }, + "image/vnd.dece.graphic": { + "source": "iana", + "extensions": ["uvi","uvvi","uvg","uvvg"] + }, + "image/vnd.djvu": { + "source": "iana", + "extensions": ["djvu","djv"] + }, + "image/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "image/vnd.dwg": { + "source": "iana", + "extensions": ["dwg"] + }, + "image/vnd.dxf": { + "source": "iana", + "extensions": ["dxf"] + }, + "image/vnd.fastbidsheet": { + "source": "iana", + "extensions": ["fbs"] + }, + "image/vnd.fpx": { + "source": "iana", + "extensions": ["fpx"] + }, + "image/vnd.fst": { + "source": "iana", + "extensions": ["fst"] + }, + "image/vnd.fujixerox.edmics-mmr": { + "source": "iana", + "extensions": ["mmr"] + }, + "image/vnd.fujixerox.edmics-rlc": { + "source": "iana", + "extensions": ["rlc"] + }, + "image/vnd.globalgraphics.pgb": { + "source": "iana" + }, + "image/vnd.microsoft.icon": { + "source": "iana", + "compressible": true, + "extensions": ["ico"] + }, + "image/vnd.mix": { + "source": "iana" + }, + "image/vnd.mozilla.apng": { + "source": "iana" + }, + "image/vnd.ms-dds": { + "compressible": true, + "extensions": ["dds"] + }, + "image/vnd.ms-modi": { + "source": "iana", + "extensions": ["mdi"] + }, + "image/vnd.ms-photo": { + "source": "apache", + "extensions": ["wdp"] + }, + "image/vnd.net-fpx": { + "source": "iana", + "extensions": ["npx"] + }, + "image/vnd.pco.b16": { + "source": "iana", + "extensions": ["b16"] + }, + "image/vnd.radiance": { + "source": "iana" + }, + "image/vnd.sealed.png": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.gif": { + "source": "iana" + }, + "image/vnd.sealedmedia.softseal.jpg": { + "source": "iana" + }, + "image/vnd.svf": { + "source": "iana" + }, + "image/vnd.tencent.tap": { + "source": "iana", + "extensions": ["tap"] + }, + "image/vnd.valve.source.texture": { + "source": "iana", + "extensions": ["vtf"] + }, + "image/vnd.wap.wbmp": { + "source": "iana", + "extensions": ["wbmp"] + }, + "image/vnd.xiff": { + "source": "iana", + "extensions": ["xif"] + }, + "image/vnd.zbrush.pcx": { + "source": "iana", + "extensions": ["pcx"] + }, + "image/webp": { + "source": "apache", + "extensions": ["webp"] + }, + "image/wmf": { + "source": "iana", + "extensions": ["wmf"] + }, + "image/x-3ds": { + "source": "apache", + "extensions": ["3ds"] + }, + "image/x-cmu-raster": { + "source": "apache", + "extensions": ["ras"] + }, + "image/x-cmx": { + "source": "apache", + "extensions": ["cmx"] + }, + "image/x-freehand": { + "source": "apache", + "extensions": ["fh","fhc","fh4","fh5","fh7"] + }, + "image/x-icon": { + "source": "apache", + "compressible": true, + "extensions": ["ico"] + }, + "image/x-jng": { + "source": "nginx", + "extensions": ["jng"] + }, + "image/x-mrsid-image": { + "source": "apache", + "extensions": ["sid"] + }, + "image/x-ms-bmp": { + "source": "nginx", + "compressible": true, + "extensions": ["bmp"] + }, + "image/x-pcx": { + "source": "apache", + "extensions": ["pcx"] + }, + "image/x-pict": { + "source": "apache", + "extensions": ["pic","pct"] + }, + "image/x-portable-anymap": { + "source": "apache", + "extensions": ["pnm"] + }, + "image/x-portable-bitmap": { + "source": "apache", + "extensions": ["pbm"] + }, + "image/x-portable-graymap": { + "source": "apache", + "extensions": ["pgm"] + }, + "image/x-portable-pixmap": { + "source": "apache", + "extensions": ["ppm"] + }, + "image/x-rgb": { + "source": "apache", + "extensions": ["rgb"] + }, + "image/x-tga": { + "source": "apache", + "extensions": ["tga"] + }, + "image/x-xbitmap": { + "source": "apache", + "extensions": ["xbm"] + }, + "image/x-xcf": { + "compressible": false + }, + "image/x-xpixmap": { + "source": "apache", + "extensions": ["xpm"] + }, + "image/x-xwindowdump": { + "source": "apache", + "extensions": ["xwd"] + }, + "message/cpim": { + "source": "iana" + }, + "message/delivery-status": { + "source": "iana" + }, + "message/disposition-notification": { + "source": "iana", + "extensions": [ + "disposition-notification" + ] + }, + "message/external-body": { + "source": "iana" + }, + "message/feedback-report": { + "source": "iana" + }, + "message/global": { + "source": "iana", + "extensions": ["u8msg"] + }, + "message/global-delivery-status": { + "source": "iana", + "extensions": ["u8dsn"] + }, + "message/global-disposition-notification": { + "source": "iana", + "extensions": ["u8mdn"] + }, + "message/global-headers": { + "source": "iana", + "extensions": ["u8hdr"] + }, + "message/http": { + "source": "iana", + "compressible": false + }, + "message/imdn+xml": { + "source": "iana", + "compressible": true + }, + "message/news": { + "source": "iana" + }, + "message/partial": { + "source": "iana", + "compressible": false + }, + "message/rfc822": { + "source": "iana", + "compressible": true, + "extensions": ["eml","mime"] + }, + "message/s-http": { + "source": "iana" + }, + "message/sip": { + "source": "iana" + }, + "message/sipfrag": { + "source": "iana" + }, + "message/tracking-status": { + "source": "iana" + }, + "message/vnd.si.simp": { + "source": "iana" + }, + "message/vnd.wfa.wsc": { + "source": "iana", + "extensions": ["wsc"] + }, + "model/3mf": { + "source": "iana", + "extensions": ["3mf"] + }, + "model/e57": { + "source": "iana" + }, + "model/gltf+json": { + "source": "iana", + "compressible": true, + "extensions": ["gltf"] + }, + "model/gltf-binary": { + "source": "iana", + "compressible": true, + "extensions": ["glb"] + }, + "model/iges": { + "source": "iana", + "compressible": false, + "extensions": ["igs","iges"] + }, + "model/mesh": { + "source": "iana", + "compressible": false, + "extensions": ["msh","mesh","silo"] + }, + "model/mtl": { + "source": "iana", + "extensions": ["mtl"] + }, + "model/obj": { + "source": "iana", + "extensions": ["obj"] + }, + "model/step": { + "source": "iana" + }, + "model/step+xml": { + "source": "iana", + "compressible": true, + "extensions": ["stpx"] + }, + "model/step+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpz"] + }, + "model/step-xml+zip": { + "source": "iana", + "compressible": false, + "extensions": ["stpxz"] + }, + "model/stl": { + "source": "iana", + "extensions": ["stl"] + }, + "model/vnd.collada+xml": { + "source": "iana", + "compressible": true, + "extensions": ["dae"] + }, + "model/vnd.dwf": { + "source": "iana", + "extensions": ["dwf"] + }, + "model/vnd.flatland.3dml": { + "source": "iana" + }, + "model/vnd.gdl": { + "source": "iana", + "extensions": ["gdl"] + }, + "model/vnd.gs-gdl": { + "source": "apache" + }, + "model/vnd.gs.gdl": { + "source": "iana" + }, + "model/vnd.gtw": { + "source": "iana", + "extensions": ["gtw"] + }, + "model/vnd.moml+xml": { + "source": "iana", + "compressible": true + }, + "model/vnd.mts": { + "source": "iana", + "extensions": ["mts"] + }, + "model/vnd.opengex": { + "source": "iana", + "extensions": ["ogex"] + }, + "model/vnd.parasolid.transmit.binary": { + "source": "iana", + "extensions": ["x_b"] + }, + "model/vnd.parasolid.transmit.text": { + "source": "iana", + "extensions": ["x_t"] + }, + "model/vnd.pytha.pyox": { + "source": "iana" + }, + "model/vnd.rosette.annotated-data-model": { + "source": "iana" + }, + "model/vnd.sap.vds": { + "source": "iana", + "extensions": ["vds"] + }, + "model/vnd.usdz+zip": { + "source": "iana", + "compressible": false, + "extensions": ["usdz"] + }, + "model/vnd.valve.source.compiled-map": { + "source": "iana", + "extensions": ["bsp"] + }, + "model/vnd.vtu": { + "source": "iana", + "extensions": ["vtu"] + }, + "model/vrml": { + "source": "iana", + "compressible": false, + "extensions": ["wrl","vrml"] + }, + "model/x3d+binary": { + "source": "apache", + "compressible": false, + "extensions": ["x3db","x3dbz"] + }, + "model/x3d+fastinfoset": { + "source": "iana", + "extensions": ["x3db"] + }, + "model/x3d+vrml": { + "source": "apache", + "compressible": false, + "extensions": ["x3dv","x3dvz"] + }, + "model/x3d+xml": { + "source": "iana", + "compressible": true, + "extensions": ["x3d","x3dz"] + }, + "model/x3d-vrml": { + "source": "iana", + "extensions": ["x3dv"] + }, + "multipart/alternative": { + "source": "iana", + "compressible": false + }, + "multipart/appledouble": { + "source": "iana" + }, + "multipart/byteranges": { + "source": "iana" + }, + "multipart/digest": { + "source": "iana" + }, + "multipart/encrypted": { + "source": "iana", + "compressible": false + }, + "multipart/form-data": { + "source": "iana", + "compressible": false + }, + "multipart/header-set": { + "source": "iana" + }, + "multipart/mixed": { + "source": "iana" + }, + "multipart/multilingual": { + "source": "iana" + }, + "multipart/parallel": { + "source": "iana" + }, + "multipart/related": { + "source": "iana", + "compressible": false + }, + "multipart/report": { + "source": "iana" + }, + "multipart/signed": { + "source": "iana", + "compressible": false + }, + "multipart/vnd.bint.med-plus": { + "source": "iana" + }, + "multipart/voice-message": { + "source": "iana" + }, + "multipart/x-mixed-replace": { + "source": "iana" + }, + "text/1d-interleaved-parityfec": { + "source": "iana" + }, + "text/cache-manifest": { + "source": "iana", + "compressible": true, + "extensions": ["appcache","manifest"] + }, + "text/calendar": { + "source": "iana", + "extensions": ["ics","ifb"] + }, + "text/calender": { + "compressible": true + }, + "text/cmd": { + "compressible": true + }, + "text/coffeescript": { + "extensions": ["coffee","litcoffee"] + }, + "text/cql": { + "source": "iana" + }, + "text/cql-expression": { + "source": "iana" + }, + "text/cql-identifier": { + "source": "iana" + }, + "text/css": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["css"] + }, + "text/csv": { + "source": "iana", + "compressible": true, + "extensions": ["csv"] + }, + "text/csv-schema": { + "source": "iana" + }, + "text/directory": { + "source": "iana" + }, + "text/dns": { + "source": "iana" + }, + "text/ecmascript": { + "source": "iana" + }, + "text/encaprtp": { + "source": "iana" + }, + "text/enriched": { + "source": "iana" + }, + "text/fhirpath": { + "source": "iana" + }, + "text/flexfec": { + "source": "iana" + }, + "text/fwdred": { + "source": "iana" + }, + "text/gff3": { + "source": "iana" + }, + "text/grammar-ref-list": { + "source": "iana" + }, + "text/html": { + "source": "iana", + "compressible": true, + "extensions": ["html","htm","shtml"] + }, + "text/jade": { + "extensions": ["jade"] + }, + "text/javascript": { + "source": "iana", + "compressible": true + }, + "text/jcr-cnd": { + "source": "iana" + }, + "text/jsx": { + "compressible": true, + "extensions": ["jsx"] + }, + "text/less": { + "compressible": true, + "extensions": ["less"] + }, + "text/markdown": { + "source": "iana", + "compressible": true, + "extensions": ["markdown","md"] + }, + "text/mathml": { + "source": "nginx", + "extensions": ["mml"] + }, + "text/mdx": { + "compressible": true, + "extensions": ["mdx"] + }, + "text/mizar": { + "source": "iana" + }, + "text/n3": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["n3"] + }, + "text/parameters": { + "source": "iana", + "charset": "UTF-8" + }, + "text/parityfec": { + "source": "iana" + }, + "text/plain": { + "source": "iana", + "compressible": true, + "extensions": ["txt","text","conf","def","list","log","in","ini"] + }, + "text/provenance-notation": { + "source": "iana", + "charset": "UTF-8" + }, + "text/prs.fallenstein.rst": { + "source": "iana" + }, + "text/prs.lines.tag": { + "source": "iana", + "extensions": ["dsc"] + }, + "text/prs.prop.logic": { + "source": "iana" + }, + "text/raptorfec": { + "source": "iana" + }, + "text/red": { + "source": "iana" + }, + "text/rfc822-headers": { + "source": "iana" + }, + "text/richtext": { + "source": "iana", + "compressible": true, + "extensions": ["rtx"] + }, + "text/rtf": { + "source": "iana", + "compressible": true, + "extensions": ["rtf"] + }, + "text/rtp-enc-aescm128": { + "source": "iana" + }, + "text/rtploopback": { + "source": "iana" + }, + "text/rtx": { + "source": "iana" + }, + "text/sgml": { + "source": "iana", + "extensions": ["sgml","sgm"] + }, + "text/shaclc": { + "source": "iana" + }, + "text/shex": { + "source": "iana", + "extensions": ["shex"] + }, + "text/slim": { + "extensions": ["slim","slm"] + }, + "text/spdx": { + "source": "iana", + "extensions": ["spdx"] + }, + "text/strings": { + "source": "iana" + }, + "text/stylus": { + "extensions": ["stylus","styl"] + }, + "text/t140": { + "source": "iana" + }, + "text/tab-separated-values": { + "source": "iana", + "compressible": true, + "extensions": ["tsv"] + }, + "text/troff": { + "source": "iana", + "extensions": ["t","tr","roff","man","me","ms"] + }, + "text/turtle": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["ttl"] + }, + "text/ulpfec": { + "source": "iana" + }, + "text/uri-list": { + "source": "iana", + "compressible": true, + "extensions": ["uri","uris","urls"] + }, + "text/vcard": { + "source": "iana", + "compressible": true, + "extensions": ["vcard"] + }, + "text/vnd.a": { + "source": "iana" + }, + "text/vnd.abc": { + "source": "iana" + }, + "text/vnd.ascii-art": { + "source": "iana" + }, + "text/vnd.curl": { + "source": "iana", + "extensions": ["curl"] + }, + "text/vnd.curl.dcurl": { + "source": "apache", + "extensions": ["dcurl"] + }, + "text/vnd.curl.mcurl": { + "source": "apache", + "extensions": ["mcurl"] + }, + "text/vnd.curl.scurl": { + "source": "apache", + "extensions": ["scurl"] + }, + "text/vnd.debian.copyright": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.dmclientscript": { + "source": "iana" + }, + "text/vnd.dvb.subtitle": { + "source": "iana", + "extensions": ["sub"] + }, + "text/vnd.esmertec.theme-descriptor": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.familysearch.gedcom": { + "source": "iana", + "extensions": ["ged"] + }, + "text/vnd.ficlab.flt": { + "source": "iana" + }, + "text/vnd.fly": { + "source": "iana", + "extensions": ["fly"] + }, + "text/vnd.fmi.flexstor": { + "source": "iana", + "extensions": ["flx"] + }, + "text/vnd.gml": { + "source": "iana" + }, + "text/vnd.graphviz": { + "source": "iana", + "extensions": ["gv"] + }, + "text/vnd.hans": { + "source": "iana" + }, + "text/vnd.hgl": { + "source": "iana" + }, + "text/vnd.in3d.3dml": { + "source": "iana", + "extensions": ["3dml"] + }, + "text/vnd.in3d.spot": { + "source": "iana", + "extensions": ["spot"] + }, + "text/vnd.iptc.newsml": { + "source": "iana" + }, + "text/vnd.iptc.nitf": { + "source": "iana" + }, + "text/vnd.latex-z": { + "source": "iana" + }, + "text/vnd.motorola.reflex": { + "source": "iana" + }, + "text/vnd.ms-mediapackage": { + "source": "iana" + }, + "text/vnd.net2phone.commcenter.command": { + "source": "iana" + }, + "text/vnd.radisys.msml-basic-layout": { + "source": "iana" + }, + "text/vnd.senx.warpscript": { + "source": "iana" + }, + "text/vnd.si.uricatalogue": { + "source": "iana" + }, + "text/vnd.sosi": { + "source": "iana" + }, + "text/vnd.sun.j2me.app-descriptor": { + "source": "iana", + "charset": "UTF-8", + "extensions": ["jad"] + }, + "text/vnd.trolltech.linguist": { + "source": "iana", + "charset": "UTF-8" + }, + "text/vnd.wap.si": { + "source": "iana" + }, + "text/vnd.wap.sl": { + "source": "iana" + }, + "text/vnd.wap.wml": { + "source": "iana", + "extensions": ["wml"] + }, + "text/vnd.wap.wmlscript": { + "source": "iana", + "extensions": ["wmls"] + }, + "text/vtt": { + "source": "iana", + "charset": "UTF-8", + "compressible": true, + "extensions": ["vtt"] + }, + "text/x-asm": { + "source": "apache", + "extensions": ["s","asm"] + }, + "text/x-c": { + "source": "apache", + "extensions": ["c","cc","cxx","cpp","h","hh","dic"] + }, + "text/x-component": { + "source": "nginx", + "extensions": ["htc"] + }, + "text/x-fortran": { + "source": "apache", + "extensions": ["f","for","f77","f90"] + }, + "text/x-gwt-rpc": { + "compressible": true + }, + "text/x-handlebars-template": { + "extensions": ["hbs"] + }, + "text/x-java-source": { + "source": "apache", + "extensions": ["java"] + }, + "text/x-jquery-tmpl": { + "compressible": true + }, + "text/x-lua": { + "extensions": ["lua"] + }, + "text/x-markdown": { + "compressible": true, + "extensions": ["mkd"] + }, + "text/x-nfo": { + "source": "apache", + "extensions": ["nfo"] + }, + "text/x-opml": { + "source": "apache", + "extensions": ["opml"] + }, + "text/x-org": { + "compressible": true, + "extensions": ["org"] + }, + "text/x-pascal": { + "source": "apache", + "extensions": ["p","pas"] + }, + "text/x-processing": { + "compressible": true, + "extensions": ["pde"] + }, + "text/x-sass": { + "extensions": ["sass"] + }, + "text/x-scss": { + "extensions": ["scss"] + }, + "text/x-setext": { + "source": "apache", + "extensions": ["etx"] + }, + "text/x-sfv": { + "source": "apache", + "extensions": ["sfv"] + }, + "text/x-suse-ymp": { + "compressible": true, + "extensions": ["ymp"] + }, + "text/x-uuencode": { + "source": "apache", + "extensions": ["uu"] + }, + "text/x-vcalendar": { + "source": "apache", + "extensions": ["vcs"] + }, + "text/x-vcard": { + "source": "apache", + "extensions": ["vcf"] + }, + "text/xml": { + "source": "iana", + "compressible": true, + "extensions": ["xml"] + }, + "text/xml-external-parsed-entity": { + "source": "iana" + }, + "text/yaml": { + "compressible": true, + "extensions": ["yaml","yml"] + }, + "video/1d-interleaved-parityfec": { + "source": "iana" + }, + "video/3gpp": { + "source": "iana", + "extensions": ["3gp","3gpp"] + }, + "video/3gpp-tt": { + "source": "iana" + }, + "video/3gpp2": { + "source": "iana", + "extensions": ["3g2"] + }, + "video/av1": { + "source": "iana" + }, + "video/bmpeg": { + "source": "iana" + }, + "video/bt656": { + "source": "iana" + }, + "video/celb": { + "source": "iana" + }, + "video/dv": { + "source": "iana" + }, + "video/encaprtp": { + "source": "iana" + }, + "video/ffv1": { + "source": "iana" + }, + "video/flexfec": { + "source": "iana" + }, + "video/h261": { + "source": "iana", + "extensions": ["h261"] + }, + "video/h263": { + "source": "iana", + "extensions": ["h263"] + }, + "video/h263-1998": { + "source": "iana" + }, + "video/h263-2000": { + "source": "iana" + }, + "video/h264": { + "source": "iana", + "extensions": ["h264"] + }, + "video/h264-rcdo": { + "source": "iana" + }, + "video/h264-svc": { + "source": "iana" + }, + "video/h265": { + "source": "iana" + }, + "video/iso.segment": { + "source": "iana", + "extensions": ["m4s"] + }, + "video/jpeg": { + "source": "iana", + "extensions": ["jpgv"] + }, + "video/jpeg2000": { + "source": "iana" + }, + "video/jpm": { + "source": "apache", + "extensions": ["jpm","jpgm"] + }, + "video/jxsv": { + "source": "iana" + }, + "video/mj2": { + "source": "iana", + "extensions": ["mj2","mjp2"] + }, + "video/mp1s": { + "source": "iana" + }, + "video/mp2p": { + "source": "iana" + }, + "video/mp2t": { + "source": "iana", + "extensions": ["ts"] + }, + "video/mp4": { + "source": "iana", + "compressible": false, + "extensions": ["mp4","mp4v","mpg4"] + }, + "video/mp4v-es": { + "source": "iana" + }, + "video/mpeg": { + "source": "iana", + "compressible": false, + "extensions": ["mpeg","mpg","mpe","m1v","m2v"] + }, + "video/mpeg4-generic": { + "source": "iana" + }, + "video/mpv": { + "source": "iana" + }, + "video/nv": { + "source": "iana" + }, + "video/ogg": { + "source": "iana", + "compressible": false, + "extensions": ["ogv"] + }, + "video/parityfec": { + "source": "iana" + }, + "video/pointer": { + "source": "iana" + }, + "video/quicktime": { + "source": "iana", + "compressible": false, + "extensions": ["qt","mov"] + }, + "video/raptorfec": { + "source": "iana" + }, + "video/raw": { + "source": "iana" + }, + "video/rtp-enc-aescm128": { + "source": "iana" + }, + "video/rtploopback": { + "source": "iana" + }, + "video/rtx": { + "source": "iana" + }, + "video/scip": { + "source": "iana" + }, + "video/smpte291": { + "source": "iana" + }, + "video/smpte292m": { + "source": "iana" + }, + "video/ulpfec": { + "source": "iana" + }, + "video/vc1": { + "source": "iana" + }, + "video/vc2": { + "source": "iana" + }, + "video/vnd.cctv": { + "source": "iana" + }, + "video/vnd.dece.hd": { + "source": "iana", + "extensions": ["uvh","uvvh"] + }, + "video/vnd.dece.mobile": { + "source": "iana", + "extensions": ["uvm","uvvm"] + }, + "video/vnd.dece.mp4": { + "source": "iana" + }, + "video/vnd.dece.pd": { + "source": "iana", + "extensions": ["uvp","uvvp"] + }, + "video/vnd.dece.sd": { + "source": "iana", + "extensions": ["uvs","uvvs"] + }, + "video/vnd.dece.video": { + "source": "iana", + "extensions": ["uvv","uvvv"] + }, + "video/vnd.directv.mpeg": { + "source": "iana" + }, + "video/vnd.directv.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dlna.mpeg-tts": { + "source": "iana" + }, + "video/vnd.dvb.file": { + "source": "iana", + "extensions": ["dvb"] + }, + "video/vnd.fvt": { + "source": "iana", + "extensions": ["fvt"] + }, + "video/vnd.hns.video": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.1dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-1010": { + "source": "iana" + }, + "video/vnd.iptvforum.2dparityfec-2005": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsavc": { + "source": "iana" + }, + "video/vnd.iptvforum.ttsmpeg2": { + "source": "iana" + }, + "video/vnd.motorola.video": { + "source": "iana" + }, + "video/vnd.motorola.videop": { + "source": "iana" + }, + "video/vnd.mpegurl": { + "source": "iana", + "extensions": ["mxu","m4u"] + }, + "video/vnd.ms-playready.media.pyv": { + "source": "iana", + "extensions": ["pyv"] + }, + "video/vnd.nokia.interleaved-multimedia": { + "source": "iana" + }, + "video/vnd.nokia.mp4vr": { + "source": "iana" + }, + "video/vnd.nokia.videovoip": { + "source": "iana" + }, + "video/vnd.objectvideo": { + "source": "iana" + }, + "video/vnd.radgamettools.bink": { + "source": "iana" + }, + "video/vnd.radgamettools.smacker": { + "source": "iana" + }, + "video/vnd.sealed.mpeg1": { + "source": "iana" + }, + "video/vnd.sealed.mpeg4": { + "source": "iana" + }, + "video/vnd.sealed.swf": { + "source": "iana" + }, + "video/vnd.sealedmedia.softseal.mov": { + "source": "iana" + }, + "video/vnd.uvvu.mp4": { + "source": "iana", + "extensions": ["uvu","uvvu"] + }, + "video/vnd.vivo": { + "source": "iana", + "extensions": ["viv"] + }, + "video/vnd.youtube.yt": { + "source": "iana" + }, + "video/vp8": { + "source": "iana" + }, + "video/vp9": { + "source": "iana" + }, + "video/webm": { + "source": "apache", + "compressible": false, + "extensions": ["webm"] + }, + "video/x-f4v": { + "source": "apache", + "extensions": ["f4v"] + }, + "video/x-fli": { + "source": "apache", + "extensions": ["fli"] + }, + "video/x-flv": { + "source": "apache", + "compressible": false, + "extensions": ["flv"] + }, + "video/x-m4v": { + "source": "apache", + "extensions": ["m4v"] + }, + "video/x-matroska": { + "source": "apache", + "compressible": false, + "extensions": ["mkv","mk3d","mks"] + }, + "video/x-mng": { + "source": "apache", + "extensions": ["mng"] + }, + "video/x-ms-asf": { + "source": "apache", + "extensions": ["asf","asx"] + }, + "video/x-ms-vob": { + "source": "apache", + "extensions": ["vob"] + }, + "video/x-ms-wm": { + "source": "apache", + "extensions": ["wm"] + }, + "video/x-ms-wmv": { + "source": "apache", + "compressible": false, + "extensions": ["wmv"] + }, + "video/x-ms-wmx": { + "source": "apache", + "extensions": ["wmx"] + }, + "video/x-ms-wvx": { + "source": "apache", + "extensions": ["wvx"] + }, + "video/x-msvideo": { + "source": "apache", + "extensions": ["avi"] + }, + "video/x-sgi-movie": { + "source": "apache", + "extensions": ["movie"] + }, + "video/x-smv": { + "source": "apache", + "extensions": ["smv"] + }, + "x-conference/x-cooltalk": { + "source": "apache", + "extensions": ["ice"] + }, + "x-shader/x-fragment": { + "compressible": true + }, + "x-shader/x-vertex": { + "compressible": true + } +} diff --git a/node_modules/mime-db/index.js b/node_modules/mime-db/index.js new file mode 100644 index 0000000..ec2be30 --- /dev/null +++ b/node_modules/mime-db/index.js @@ -0,0 +1,12 @@ +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ + +/** + * Module exports. + */ + +module.exports = require('./db.json') diff --git a/node_modules/mime-db/package.json b/node_modules/mime-db/package.json new file mode 100644 index 0000000..32c14b8 --- /dev/null +++ b/node_modules/mime-db/package.json @@ -0,0 +1,60 @@ +{ + "name": "mime-db", + "description": "Media Type Database", + "version": "1.52.0", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)", + "Robert Kieffer (http://github.com/broofa)" + ], + "license": "MIT", + "keywords": [ + "mime", + "db", + "type", + "types", + "database", + "charset", + "charsets" + ], + "repository": "jshttp/mime-db", + "devDependencies": { + "bluebird": "3.7.2", + "co": "4.6.0", + "cogent": "1.0.1", + "csv-parse": "4.16.3", + "eslint": "7.32.0", + "eslint-config-standard": "15.0.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.1.1", + "eslint-plugin-standard": "4.1.0", + "gnode": "0.1.2", + "media-typer": "1.1.0", + "mocha": "9.2.1", + "nyc": "15.1.0", + "raw-body": "2.5.0", + "stream-to-array": "2.3.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "README.md", + "db.json", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "build": "node scripts/build", + "fetch": "node scripts/fetch-apache && gnode scripts/fetch-iana && node scripts/fetch-nginx", + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/mime-types/HISTORY.md b/node_modules/mime-types/HISTORY.md new file mode 100644 index 0000000..c5043b7 --- /dev/null +++ b/node_modules/mime-types/HISTORY.md @@ -0,0 +1,397 @@ +2.1.35 / 2022-03-12 +=================== + + * deps: mime-db@1.52.0 + - Add extensions from IANA for more `image/*` types + - Add extension `.asc` to `application/pgp-keys` + - Add extensions to various XML types + - Add new upstream MIME types + +2.1.34 / 2021-11-08 +=================== + + * deps: mime-db@1.51.0 + - Add new upstream MIME types + +2.1.33 / 2021-10-01 +=================== + + * deps: mime-db@1.50.0 + - Add deprecated iWorks mime types and extensions + - Add new upstream MIME types + +2.1.32 / 2021-07-27 +=================== + + * deps: mime-db@1.49.0 + - Add extension `.trig` to `application/trig` + - Add new upstream MIME types + +2.1.31 / 2021-06-01 +=================== + + * deps: mime-db@1.48.0 + - Add extension `.mvt` to `application/vnd.mapbox-vector-tile` + - Add new upstream MIME types + +2.1.30 / 2021-04-02 +=================== + + * deps: mime-db@1.47.0 + - Add extension `.amr` to `audio/amr` + - Remove ambigious extensions from IANA for `application/*+xml` types + - Update primary extension to `.es` for `application/ecmascript` + +2.1.29 / 2021-02-17 +=================== + + * deps: mime-db@1.46.0 + - Add extension `.amr` to `audio/amr` + - Add extension `.m4s` to `video/iso.segment` + - Add extension `.opus` to `audio/ogg` + - Add new upstream MIME types + +2.1.28 / 2021-01-01 +=================== + + * deps: mime-db@1.45.0 + - Add `application/ubjson` with extension `.ubj` + - Add `image/avif` with extension `.avif` + - Add `image/ktx2` with extension `.ktx2` + - Add extension `.dbf` to `application/vnd.dbf` + - Add extension `.rar` to `application/vnd.rar` + - Add extension `.td` to `application/urc-targetdesc+xml` + - Add new upstream MIME types + - Fix extension of `application/vnd.apple.keynote` to be `.key` + +2.1.27 / 2020-04-23 +=================== + + * deps: mime-db@1.44.0 + - Add charsets from IANA + - Add extension `.cjs` to `application/node` + - Add new upstream MIME types + +2.1.26 / 2020-01-05 +=================== + + * deps: mime-db@1.43.0 + - Add `application/x-keepass2` with extension `.kdbx` + - Add extension `.mxmf` to `audio/mobile-xmf` + - Add extensions from IANA for `application/*+xml` types + - Add new upstream MIME types + +2.1.25 / 2019-11-12 +=================== + + * deps: mime-db@1.42.0 + - Add new upstream MIME types + - Add `application/toml` with extension `.toml` + - Add `image/vnd.ms-dds` with extension `.dds` + +2.1.24 / 2019-04-20 +=================== + + * deps: mime-db@1.40.0 + - Add extensions from IANA for `model/*` types + - Add `text/mdx` with extension `.mdx` + +2.1.23 / 2019-04-17 +=================== + + * deps: mime-db@~1.39.0 + - Add extensions `.siv` and `.sieve` to `application/sieve` + - Add new upstream MIME types + +2.1.22 / 2019-02-14 +=================== + + * deps: mime-db@~1.38.0 + - Add extension `.nq` to `application/n-quads` + - Add extension `.nt` to `application/n-triples` + - Add new upstream MIME types + +2.1.21 / 2018-10-19 +=================== + + * deps: mime-db@~1.37.0 + - Add extensions to HEIC image types + - Add new upstream MIME types + +2.1.20 / 2018-08-26 +=================== + + * deps: mime-db@~1.36.0 + - Add Apple file extensions from IANA + - Add extensions from IANA for `image/*` types + - Add new upstream MIME types + +2.1.19 / 2018-07-17 +=================== + + * deps: mime-db@~1.35.0 + - Add extension `.csl` to `application/vnd.citationstyles.style+xml` + - Add extension `.es` to `application/ecmascript` + - Add extension `.owl` to `application/rdf+xml` + - Add new upstream MIME types + - Add UTF-8 as default charset for `text/turtle` + +2.1.18 / 2018-02-16 +=================== + + * deps: mime-db@~1.33.0 + - Add `application/raml+yaml` with extension `.raml` + - Add `application/wasm` with extension `.wasm` + - Add `text/shex` with extension `.shex` + - Add extensions for JPEG-2000 images + - Add extensions from IANA for `message/*` types + - Add new upstream MIME types + - Update font MIME types + - Update `text/hjson` to registered `application/hjson` + +2.1.17 / 2017-09-01 +=================== + + * deps: mime-db@~1.30.0 + - Add `application/vnd.ms-outlook` + - Add `application/x-arj` + - Add extension `.mjs` to `application/javascript` + - Add glTF types and extensions + - Add new upstream MIME types + - Add `text/x-org` + - Add VirtualBox MIME types + - Fix `source` records for `video/*` types that are IANA + - Update `font/opentype` to registered `font/otf` + +2.1.16 / 2017-07-24 +=================== + + * deps: mime-db@~1.29.0 + - Add `application/fido.trusted-apps+json` + - Add extension `.wadl` to `application/vnd.sun.wadl+xml` + - Add extension `.gz` to `application/gzip` + - Add new upstream MIME types + - Update extensions `.md` and `.markdown` to be `text/markdown` + +2.1.15 / 2017-03-23 +=================== + + * deps: mime-db@~1.27.0 + - Add new mime types + - Add `image/apng` + +2.1.14 / 2017-01-14 +=================== + + * deps: mime-db@~1.26.0 + - Add new mime types + +2.1.13 / 2016-11-18 +=================== + + * deps: mime-db@~1.25.0 + - Add new mime types + +2.1.12 / 2016-09-18 +=================== + + * deps: mime-db@~1.24.0 + - Add new mime types + - Add `audio/mp3` + +2.1.11 / 2016-05-01 +=================== + + * deps: mime-db@~1.23.0 + - Add new mime types + +2.1.10 / 2016-02-15 +=================== + + * deps: mime-db@~1.22.0 + - Add new mime types + - Fix extension of `application/dash+xml` + - Update primary extension for `audio/mp4` + +2.1.9 / 2016-01-06 +================== + + * deps: mime-db@~1.21.0 + - Add new mime types + +2.1.8 / 2015-11-30 +================== + + * deps: mime-db@~1.20.0 + - Add new mime types + +2.1.7 / 2015-09-20 +================== + + * deps: mime-db@~1.19.0 + - Add new mime types + +2.1.6 / 2015-09-03 +================== + + * deps: mime-db@~1.18.0 + - Add new mime types + +2.1.5 / 2015-08-20 +================== + + * deps: mime-db@~1.17.0 + - Add new mime types + +2.1.4 / 2015-07-30 +================== + + * deps: mime-db@~1.16.0 + - Add new mime types + +2.1.3 / 2015-07-13 +================== + + * deps: mime-db@~1.15.0 + - Add new mime types + +2.1.2 / 2015-06-25 +================== + + * deps: mime-db@~1.14.0 + - Add new mime types + +2.1.1 / 2015-06-08 +================== + + * perf: fix deopt during mapping + +2.1.0 / 2015-06-07 +================== + + * Fix incorrectly treating extension-less file name as extension + - i.e. `'path/to/json'` will no longer return `application/json` + * Fix `.charset(type)` to accept parameters + * Fix `.charset(type)` to match case-insensitive + * Improve generation of extension to MIME mapping + * Refactor internals for readability and no argument reassignment + * Prefer `application/*` MIME types from the same source + * Prefer any type over `application/octet-stream` + * deps: mime-db@~1.13.0 + - Add nginx as a source + - Add new mime types + +2.0.14 / 2015-06-06 +=================== + + * deps: mime-db@~1.12.0 + - Add new mime types + +2.0.13 / 2015-05-31 +=================== + + * deps: mime-db@~1.11.0 + - Add new mime types + +2.0.12 / 2015-05-19 +=================== + + * deps: mime-db@~1.10.0 + - Add new mime types + +2.0.11 / 2015-05-05 +=================== + + * deps: mime-db@~1.9.1 + - Add new mime types + +2.0.10 / 2015-03-13 +=================== + + * deps: mime-db@~1.8.0 + - Add new mime types + +2.0.9 / 2015-02-09 +================== + + * deps: mime-db@~1.7.0 + - Add new mime types + - Community extensions ownership transferred from `node-mime` + +2.0.8 / 2015-01-29 +================== + + * deps: mime-db@~1.6.0 + - Add new mime types + +2.0.7 / 2014-12-30 +================== + + * deps: mime-db@~1.5.0 + - Add new mime types + - Fix various invalid MIME type entries + +2.0.6 / 2014-12-30 +================== + + * deps: mime-db@~1.4.0 + - Add new mime types + - Fix various invalid MIME type entries + - Remove example template MIME types + +2.0.5 / 2014-12-29 +================== + + * deps: mime-db@~1.3.1 + - Fix missing extensions + +2.0.4 / 2014-12-10 +================== + + * deps: mime-db@~1.3.0 + - Add new mime types + +2.0.3 / 2014-11-09 +================== + + * deps: mime-db@~1.2.0 + - Add new mime types + +2.0.2 / 2014-09-28 +================== + + * deps: mime-db@~1.1.0 + - Add new mime types + - Update charsets + +2.0.1 / 2014-09-07 +================== + + * Support Node.js 0.6 + +2.0.0 / 2014-09-02 +================== + + * Use `mime-db` + * Remove `.define()` + +1.0.2 / 2014-08-04 +================== + + * Set charset=utf-8 for `text/javascript` + +1.0.1 / 2014-06-24 +================== + + * Add `text/jsx` type + +1.0.0 / 2014-05-12 +================== + + * Return `false` for unknown types + * Set charset=utf-8 for `application/json` + +0.1.0 / 2014-05-02 +================== + + * Initial release diff --git a/node_modules/mime-types/LICENSE b/node_modules/mime-types/LICENSE new file mode 100644 index 0000000..0616607 --- /dev/null +++ b/node_modules/mime-types/LICENSE @@ -0,0 +1,23 @@ +(The MIT License) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2015 Douglas Christopher Wilson + +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/mime-types/README.md b/node_modules/mime-types/README.md new file mode 100644 index 0000000..48d2fb4 --- /dev/null +++ b/node_modules/mime-types/README.md @@ -0,0 +1,113 @@ +# mime-types + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +The ultimate javascript content-type utility. + +Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except: + +- __No fallbacks.__ Instead of naively returning the first available type, + `mime-types` simply returns `false`, so do + `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. +- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. +- No `.define()` functionality +- Bug fixes for `.lookup(path)` + +Otherwise, the API is compatible with `mime` 1.x. + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install mime-types +``` + +## Adding Types + +All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), +so open a PR there if you'd like to add mime types. + +## API + +```js +var mime = require('mime-types') +``` + +All functions return `false` if input is invalid or not found. + +### mime.lookup(path) + +Lookup the content-type associated with a file. + +```js +mime.lookup('json') // 'application/json' +mime.lookup('.md') // 'text/markdown' +mime.lookup('file.html') // 'text/html' +mime.lookup('folder/file.js') // 'application/javascript' +mime.lookup('folder/.htaccess') // false + +mime.lookup('cats') // false +``` + +### mime.contentType(type) + +Create a full content-type header given a content-type or extension. +When given an extension, `mime.lookup` is used to get the matching +content-type, otherwise the given content-type is used. Then if the +content-type does not already have a `charset` parameter, `mime.charset` +is used to get the default charset and add to the returned content-type. + +```js +mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' +mime.contentType('file.json') // 'application/json; charset=utf-8' +mime.contentType('text/html') // 'text/html; charset=utf-8' +mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' + +// from a full path +mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' +``` + +### mime.extension(type) + +Get the default extension for a content-type. + +```js +mime.extension('application/octet-stream') // 'bin' +``` + +### mime.charset(type) + +Lookup the implied default charset of a content-type. + +```js +mime.charset('text/markdown') // 'UTF-8' +``` + +### var type = mime.types[extension] + +A map of content-types by extension. + +### [extensions...] = mime.extensions[type] + +A map of extensions by content-type. + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci +[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master +[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master +[node-version-image]: https://badgen.net/npm/node/mime-types +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/mime-types +[npm-url]: https://npmjs.org/package/mime-types +[npm-version-image]: https://badgen.net/npm/v/mime-types diff --git a/node_modules/mime-types/index.js b/node_modules/mime-types/index.js new file mode 100644 index 0000000..b9f34d5 --- /dev/null +++ b/node_modules/mime-types/index.js @@ -0,0 +1,188 @@ +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var db = require('mime-db') +var extname = require('path').extname + +/** + * Module variables. + * @private + */ + +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] + + if (mime && mime.charset) { + return mime.charset + } + + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } + + return false +} + +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ + +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } + + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str + + if (!mime) { + return false + } + + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } + + return mime +} + +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } + + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] +} + +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ + +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } + + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) + + if (!extension) { + return false + } + + return exports.types[extension] || false +} + +/** + * Populate the extensions and types maps. + * @private + */ + +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] + + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions + + if (!exts || !exts.length) { + return + } + + // mime -> extensions + extensions[type] = exts + + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type + } + }) +} diff --git a/node_modules/mime-types/package.json b/node_modules/mime-types/package.json new file mode 100644 index 0000000..bbef696 --- /dev/null +++ b/node_modules/mime-types/package.json @@ -0,0 +1,44 @@ +{ + "name": "mime-types", + "description": "The ultimate javascript content-type utility.", + "version": "2.1.35", + "contributors": [ + "Douglas Christopher Wilson ", + "Jeremiah Senkpiel (https://searchbeam.jit.su)", + "Jonathan Ong (http://jongleberry.com)" + ], + "license": "MIT", + "keywords": [ + "mime", + "types" + ], + "repository": "jshttp/mime-types", + "dependencies": { + "mime-db": "1.52.0" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0" + }, + "files": [ + "HISTORY.md", + "LICENSE", + "index.js" + ], + "engines": { + "node": ">= 0.6" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec test/test.js", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test" + } +} diff --git a/node_modules/ms/index.js b/node_modules/ms/index.js new file mode 100644 index 0000000..ea734fb --- /dev/null +++ b/node_modules/ms/index.js @@ -0,0 +1,162 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var w = d * 7; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); +} diff --git a/node_modules/ms/license.md b/node_modules/ms/license.md new file mode 100644 index 0000000..fa5d39b --- /dev/null +++ b/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2020 Vercel, Inc. + +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/ms/package.json b/node_modules/ms/package.json new file mode 100644 index 0000000..4997189 --- /dev/null +++ b/node_modules/ms/package.json @@ -0,0 +1,38 @@ +{ + "name": "ms", + "version": "2.1.3", + "description": "Tiny millisecond conversion utility", + "repository": "vercel/ms", + "main": "./index", + "files": [ + "index.js" + ], + "scripts": { + "precommit": "lint-staged", + "lint": "eslint lib/* bin/*", + "test": "mocha tests.js" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "license": "MIT", + "devDependencies": { + "eslint": "4.18.2", + "expect.js": "0.3.1", + "husky": "0.14.3", + "lint-staged": "5.0.0", + "mocha": "4.0.1", + "prettier": "2.0.5" + } +} diff --git a/node_modules/ms/readme.md b/node_modules/ms/readme.md new file mode 100644 index 0000000..0fc1abb --- /dev/null +++ b/node_modules/ms/readme.md @@ -0,0 +1,59 @@ +# ms + +![CI](https://github.com/vercel/ms/workflows/CI/badge.svg) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +ms('-3 days') // -259200000 +ms('-1h') // -3600000 +ms('-200') // -200 +``` + +### Convert from Milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(-3 * 60000) // "-3m" +ms(ms('10 hours')) // "10h" +``` + +### Time Format Written-Out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(-3 * 60000, { long: true }) // "-3 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [Node.js](https://nodejs.org) and in the browser +- If a number is supplied to `ms`, a string with a unit is returned +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`) +- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned + +## Related Packages + +- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time. + +## Caught a Bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/node_modules/node-domexception/.history/README_20210527203617.md b/node_modules/node-domexception/.history/README_20210527203617.md new file mode 100644 index 0000000..38d8f85 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527203617.md @@ -0,0 +1,2 @@ +# node-domexception +An implementation of the DOMException class from NodeJS diff --git a/node_modules/node-domexception/.history/README_20210527212714.md b/node_modules/node-domexception/.history/README_20210527212714.md new file mode 100644 index 0000000..eed1d13 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527212714.md @@ -0,0 +1,41 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMexception provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' + +hello().catch(err => { + if (err instanceof DOMException) { + ... + } +}) + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 7); + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10); +``` + +## APIs + +This package exposes two flavors of the `DOMException` interface depending on the imported module. + +### `domexception` module + +This module default-exports the `DOMException` interface constructor. + +### `domexception/webidl2js-wrapper` module + +This module exports the `DOMException` [interface wrapper API](https://github.com/jsdom/webidl2js#for-interfaces) generated by [webidl2js](https://github.com/jsdom/webidl2js). diff --git a/node_modules/node-domexception/.history/README_20210527213345.md b/node_modules/node-domexception/.history/README_20210527213345.md new file mode 100644 index 0000000..5825416 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527213345.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class, from NodeJS itself. (including the legacy codes) +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/README_20210527213411.md b/node_modules/node-domexception/.history/README_20210527213411.md new file mode 100644 index 0000000..4c21ec8 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527213411.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package implements the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including the legacy codes) +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/README_20210527213803.md b/node_modules/node-domexception/.history/README_20210527213803.md new file mode 100644 index 0000000..4cb8571 --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527213803.md @@ -0,0 +1,36 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/README_20210527214323.md b/node_modules/node-domexception/.history/README_20210527214323.md new file mode 100644 index 0000000..a32a91b --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527214323.md @@ -0,0 +1,38 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/README_20210527214408.md b/node_modules/node-domexception/.history/README_20210527214408.md new file mode 100644 index 0000000..a32a91b --- /dev/null +++ b/node_modules/node-domexception/.history/README_20210527214408.md @@ -0,0 +1,38 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the deprecated legacy codes) +NodeJS has it built in, but it's not globally available, and you can't require/import it from somewhere. + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws an error and catch the constructor. +This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException. +The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` diff --git a/node_modules/node-domexception/.history/index_20210527203842.js b/node_modules/node-domexception/.history/index_20210527203842.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/node-domexception/.history/index_20210527203947.js b/node_modules/node-domexception/.history/index_20210527203947.js new file mode 100644 index 0000000..b9a8b76 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527203947.js @@ -0,0 +1,8 @@ +const { MessageChannel } = require('worker_threads') + +if (!globalThis.DOMException) { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} diff --git a/node_modules/node-domexception/.history/index_20210527204259.js b/node_modules/node-domexception/.history/index_20210527204259.js new file mode 100644 index 0000000..e9332a8 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527204259.js @@ -0,0 +1,9 @@ +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports diff --git a/node_modules/node-domexception/.history/index_20210527204418.js b/node_modules/node-domexception/.history/index_20210527204418.js new file mode 100644 index 0000000..cb362cc --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527204418.js @@ -0,0 +1,9 @@ +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527204756.js b/node_modules/node-domexception/.history/index_20210527204756.js new file mode 100644 index 0000000..87d2655 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527204756.js @@ -0,0 +1,11 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527204833.js b/node_modules/node-domexception/.history/index_20210527204833.js new file mode 100644 index 0000000..837ebda --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527204833.js @@ -0,0 +1,11 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads') + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { globalThis.DOMException = err.constructor } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527211208.js b/node_modules/node-domexception/.history/index_20210527211208.js new file mode 100644 index 0000000..ba215ce --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527211208.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + var { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527211248.js b/node_modules/node-domexception/.history/index_20210527211248.js new file mode 100644 index 0000000..f5c434e --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527211248.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527212722.js b/node_modules/node-domexception/.history/index_20210527212722.js new file mode 100644 index 0000000..91b3b52 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527212722.js @@ -0,0 +1,23 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 7); diff --git a/node_modules/node-domexception/.history/index_20210527212731.js b/node_modules/node-domexception/.history/index_20210527212731.js new file mode 100644 index 0000000..cf28864 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527212731.js @@ -0,0 +1,23 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + +const e1 = new DOMException("Something went wrong", "BadThingsError"); +console.assert(e1.name === "BadThingsError"); +console.assert(e1.code === 0); + +const e2 = new DOMException("Another exciting error message", "NoModificationAllowedError"); +console.assert(e2.name === "NoModificationAllowedError"); +console.assert(e2.code === 2); diff --git a/node_modules/node-domexception/.history/index_20210527212746.js b/node_modules/node-domexception/.history/index_20210527212746.js new file mode 100644 index 0000000..f5c434e --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527212746.js @@ -0,0 +1,15 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527212900.js b/node_modules/node-domexception/.history/index_20210527212900.js new file mode 100644 index 0000000..efa2442 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527212900.js @@ -0,0 +1,16 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213022.js b/node_modules/node-domexception/.history/index_20210527213022.js new file mode 100644 index 0000000..e59f047 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213022.js @@ -0,0 +1,16 @@ +/*! blob-to-buffer. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213822.js b/node_modules/node-domexception/.history/index_20210527213822.js new file mode 100644 index 0000000..7f4e13d --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213822.js @@ -0,0 +1,16 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + try { port.postMessage(ab, [ab, ab]) } + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213843.js b/node_modules/node-domexception/.history/index_20210527213843.js new file mode 100644 index 0000000..ee75b73 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213843.js @@ -0,0 +1,17 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213852.js b/node_modules/node-domexception/.history/index_20210527213852.js new file mode 100644 index 0000000..a82bee3 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213852.js @@ -0,0 +1,17 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + console.log(err.code, err.name, err.message) + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527213910.js b/node_modules/node-domexception/.history/index_20210527213910.js new file mode 100644 index 0000000..1e1ca29 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527213910.js @@ -0,0 +1,16 @@ +/*! node-DOMException. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527214034.js b/node_modules/node-domexception/.history/index_20210527214034.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527214034.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/index_20210527214643.js b/node_modules/node-domexception/.history/index_20210527214643.js new file mode 100644 index 0000000..92ed847 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527214643.js @@ -0,0 +1,41 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +const { MessageChannel } = require('worker_threads') + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) diff --git a/node_modules/node-domexception/.history/index_20210527214654.js b/node_modules/node-domexception/.history/index_20210527214654.js new file mode 100644 index 0000000..6d5cb8e --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527214654.js @@ -0,0 +1,41 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException + + +const { MessageChannel } = require('worker_threads') + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 21) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) diff --git a/node_modules/node-domexception/.history/index_20210527214700.js b/node_modules/node-domexception/.history/index_20210527214700.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/node_modules/node-domexception/.history/index_20210527214700.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/.history/package_20210527203733.json b/node_modules/node-domexception/.history/package_20210527203733.json new file mode 100644 index 0000000..5eeb306 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527203733.json @@ -0,0 +1,19 @@ +{ + "name": "domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/node_modules/node-domexception/.history/package_20210527203825.json b/node_modules/node-domexception/.history/package_20210527203825.json new file mode 100644 index 0000000..4ca1713 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527203825.json @@ -0,0 +1,16 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/node_modules/node-domexception/.history/package_20210527204621.json b/node_modules/node-domexception/.history/package_20210527204621.json new file mode 100644 index 0000000..3c414e9 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527204621.json @@ -0,0 +1,19 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme" +} diff --git a/node_modules/node-domexception/.history/package_20210527204913.json b/node_modules/node-domexception/.history/package_20210527204913.json new file mode 100644 index 0000000..dbbb5d2 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527204913.json @@ -0,0 +1,25 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + } + ] +} diff --git a/node_modules/node-domexception/.history/package_20210527204925.json b/node_modules/node-domexception/.history/package_20210527204925.json new file mode 100644 index 0000000..dbbb5d2 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527204925.json @@ -0,0 +1,25 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + } + ] +} diff --git a/node_modules/node-domexception/.history/package_20210527205145.json b/node_modules/node-domexception/.history/package_20210527205145.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527205145.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/node_modules/node-domexception/.history/package_20210527205156.json b/node_modules/node-domexception/.history/package_20210527205156.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/node_modules/node-domexception/.history/package_20210527205156.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/node_modules/node-domexception/.history/test_20210527205603.js b/node_modules/node-domexception/.history/test_20210527205603.js new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/node-domexception/.history/test_20210527205957.js b/node_modules/node-domexception/.history/test_20210527205957.js new file mode 100644 index 0000000..73feac5 --- /dev/null +++ b/node_modules/node-domexception/.history/test_20210527205957.js @@ -0,0 +1,3 @@ +require('./index.js') + +console.log(DOMException.INDEX_SIZE_ERR) diff --git a/node_modules/node-domexception/.history/test_20210527210021.js b/node_modules/node-domexception/.history/test_20210527210021.js new file mode 100644 index 0000000..be47491 --- /dev/null +++ b/node_modules/node-domexception/.history/test_20210527210021.js @@ -0,0 +1,3 @@ +const e = require('./index.js') + +console.log(e.INDEX_SIZE_ERR) diff --git a/node_modules/node-domexception/LICENSE b/node_modules/node-domexception/LICENSE new file mode 100644 index 0000000..bc8ceb7 --- /dev/null +++ b/node_modules/node-domexception/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Jimmy Wärting + +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/node-domexception/README.md b/node_modules/node-domexception/README.md new file mode 100644 index 0000000..a369461 --- /dev/null +++ b/node_modules/node-domexception/README.md @@ -0,0 +1,46 @@ +# DOMException +An implementation of the DOMException class from NodeJS + +NodeJS has DOMException built in, but it's not globally available, and you can't require/import it from somewhere. + +This package exposes the [`DOMException`](https://developer.mozilla.org/en-US/docs/Web/API/DOMException) class that comes from NodeJS itself. (including all of the legacy codes) + +(plz don't depend on this package in any other environment other than node >=10.5) + +```js +import DOMException from 'node-domexception' +import { MessageChannel } from 'worker_threads' + +async function hello() { + const port = new MessageChannel().port1 + const ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) +} + +hello().catch(err => { + console.assert(err.name === 'DataCloneError') + console.assert(err.code === 25) + console.assert(err instanceof DOMException) +}) + +const e1 = new DOMException('Something went wrong', 'BadThingsError') +console.assert(e1.name === 'BadThingsError') +console.assert(e1.code === 0) + +const e2 = new DOMException('Another exciting error message', 'NoModificationAllowedError') +console.assert(e2.name === 'NoModificationAllowedError') +console.assert(e2.code === 7) + +console.assert(DOMException.INUSE_ATTRIBUTE_ERR === 10) +``` + +# Background + +The only possible way is to use some web-ish tools that have been introduced into NodeJS that throws a DOMException and catch the constructor. This is exactly what this package dose for you and exposes it.
+This way you will have the same class that NodeJS has and you can check if the error is a instance of DOMException.
+The instanceof check would not have worked with a custom class such as the DOMException provided by domenic which also is much larger in size since it has to re-construct the hole class from the ground up. + +The DOMException is used in many places such as the Fetch API, File & Blobs, PostMessaging and more.
+Why they decided to call it **DOM**, I don't know + +Please consider sponsoring if you find this helpful diff --git a/node_modules/node-domexception/index.js b/node_modules/node-domexception/index.js new file mode 100644 index 0000000..b7bbe95 --- /dev/null +++ b/node_modules/node-domexception/index.js @@ -0,0 +1,16 @@ +/*! node-domexception. MIT License. Jimmy Wärting */ + +if (!globalThis.DOMException) { + try { + const { MessageChannel } = require('worker_threads'), + port = new MessageChannel().port1, + ab = new ArrayBuffer() + port.postMessage(ab, [ab, ab]) + } catch (err) { + err.constructor.name === 'DOMException' && ( + globalThis.DOMException = err.constructor + ) + } +} + +module.exports = globalThis.DOMException diff --git a/node_modules/node-domexception/package.json b/node_modules/node-domexception/package.json new file mode 100644 index 0000000..cd08e70 --- /dev/null +++ b/node_modules/node-domexception/package.json @@ -0,0 +1,29 @@ +{ + "name": "node-domexception", + "version": "1.0.0", + "description": "An implementation of the DOMException class from NodeJS", + "main": "index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/jimmywarting/node-domexception.git" + }, + "engines": { + "node": ">=10.5.0" + }, + "author": "Jimmy Wärting", + "license": "MIT", + "bugs": { + "url": "https://github.com/jimmywarting/node-domexception/issues" + }, + "homepage": "https://github.com/jimmywarting/node-domexception#readme", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ] +} diff --git a/node_modules/node-fetch/LICENSE.md b/node_modules/node-fetch/LICENSE.md new file mode 100644 index 0000000..660ffec --- /dev/null +++ b/node_modules/node-fetch/LICENSE.md @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2016 David Frank + +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/node-fetch/README.md b/node_modules/node-fetch/README.md new file mode 100644 index 0000000..55f09b7 --- /dev/null +++ b/node_modules/node-fetch/README.md @@ -0,0 +1,634 @@ +node-fetch +========== + +[![npm version][npm-image]][npm-url] +[![build status][travis-image]][travis-url] +[![coverage status][codecov-image]][codecov-url] +[![install size][install-size-image]][install-size-url] +[![Discord][discord-image]][discord-url] + +A light-weight module that brings `window.fetch` to Node.js + +(We are looking for [v2 maintainers and collaborators](https://github.com/bitinn/node-fetch/issues/567)) + +[![Backers][opencollective-image]][opencollective-url] + + + +- [Motivation](#motivation) +- [Features](#features) +- [Difference from client-side fetch](#difference-from-client-side-fetch) +- [Installation](#installation) +- [Loading and configuring the module](#loading-and-configuring-the-module) +- [Common Usage](#common-usage) + - [Plain text or HTML](#plain-text-or-html) + - [JSON](#json) + - [Simple Post](#simple-post) + - [Post with JSON](#post-with-json) + - [Post with form parameters](#post-with-form-parameters) + - [Handling exceptions](#handling-exceptions) + - [Handling client and server errors](#handling-client-and-server-errors) +- [Advanced Usage](#advanced-usage) + - [Streams](#streams) + - [Buffer](#buffer) + - [Accessing Headers and other Meta data](#accessing-headers-and-other-meta-data) + - [Extract Set-Cookie Header](#extract-set-cookie-header) + - [Post data using a file stream](#post-data-using-a-file-stream) + - [Post with form-data (detect multipart)](#post-with-form-data-detect-multipart) + - [Request cancellation with AbortSignal](#request-cancellation-with-abortsignal) +- [API](#api) + - [fetch(url[, options])](#fetchurl-options) + - [Options](#options) + - [Class: Request](#class-request) + - [Class: Response](#class-response) + - [Class: Headers](#class-headers) + - [Interface: Body](#interface-body) + - [Class: FetchError](#class-fetcherror) +- [License](#license) +- [Acknowledgement](#acknowledgement) + + + +## Motivation + +Instead of implementing `XMLHttpRequest` in Node.js to run browser-specific [Fetch polyfill](https://github.com/github/fetch), why not go from native `http` to `fetch` API directly? Hence, `node-fetch`, minimal code for a `window.fetch` compatible API on Node.js runtime. + +See Matt Andrews' [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) or Leonardo Quixada's [cross-fetch](https://github.com/lquixada/cross-fetch) for isomorphic usage (exports `node-fetch` for server-side, `whatwg-fetch` for client-side). + +## Features + +- Stay consistent with `window.fetch` API. +- Make conscious trade-off when following [WHATWG fetch spec][whatwg-fetch] and [stream spec](https://streams.spec.whatwg.org/) implementation details, document known differences. +- Use native promise but allow substituting it with [insert your favorite promise library]. +- Use native Node streams for body on both request and response. +- Decode content encoding (gzip/deflate) properly and convert string output (such as `res.text()` and `res.json()`) to UTF-8 automatically. +- Useful extensions such as timeout, redirect limit, response size limit, [explicit errors](ERROR-HANDLING.md) for troubleshooting. + +## Difference from client-side fetch + +- See [Known Differences](LIMITS.md) for details. +- If you happen to use a missing feature that `window.fetch` offers, feel free to open an issue. +- Pull requests are welcomed too! + +## Installation + +Current stable release (`2.x`) + +```sh +$ npm install node-fetch +``` + +## Loading and configuring the module +We suggest you load the module via `require` until the stabilization of ES modules in node: +```js +const fetch = require('node-fetch'); +``` + +If you are using a Promise library other than native, set it through `fetch.Promise`: +```js +const Bluebird = require('bluebird'); + +fetch.Promise = Bluebird; +``` + +## Common Usage + +NOTE: The documentation below is up-to-date with `2.x` releases; see the [`1.x` readme](https://github.com/bitinn/node-fetch/blob/1.x/README.md), [changelog](https://github.com/bitinn/node-fetch/blob/1.x/CHANGELOG.md) and [2.x upgrade guide](UPGRADE-GUIDE.md) for the differences. + +#### Plain text or HTML +```js +fetch('https://github.com/') + .then(res => res.text()) + .then(body => console.log(body)); +``` + +#### JSON + +```js + +fetch('https://api.github.com/users/github') + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Simple Post +```js +fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' }) + .then(res => res.json()) // expecting a json response + .then(json => console.log(json)); +``` + +#### Post with JSON + +```js +const body = { a: 1 }; + +fetch('https://httpbin.org/post', { + method: 'post', + body: JSON.stringify(body), + headers: { 'Content-Type': 'application/json' }, + }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form parameters +`URLSearchParams` is available in Node.js as of v7.5.0. See [official documentation](https://nodejs.org/api/url.html#url_class_urlsearchparams) for more usage methods. + +NOTE: The `Content-Type` header is only set automatically to `x-www-form-urlencoded` when an instance of `URLSearchParams` is given as such: + +```js +const { URLSearchParams } = require('url'); + +const params = new URLSearchParams(); +params.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: params }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Handling exceptions +NOTE: 3xx-5xx responses are *NOT* exceptions and should be handled in `then()`; see the next section for more information. + +Adding a catch to the fetch promise chain will catch *all* exceptions, such as errors originating from node core libraries, network errors and operational errors, which are instances of FetchError. See the [error handling document](ERROR-HANDLING.md) for more details. + +```js +fetch('https://domain.invalid/') + .catch(err => console.error(err)); +``` + +#### Handling client and server errors +It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses: + +```js +function checkStatus(res) { + if (res.ok) { // res.status >= 200 && res.status < 300 + return res; + } else { + throw MyCustomError(res.statusText); + } +} + +fetch('https://httpbin.org/status/400') + .then(checkStatus) + .then(res => console.log('will not get here...')) +``` + +## Advanced Usage + +#### Streams +The "Node.js way" is to use streams when possible: + +```js +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => { + const dest = fs.createWriteStream('./octocat.png'); + res.body.pipe(dest); + }); +``` + +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +const fetch = require('node-fetch'); +const response = await fetch('https://httpbin.org/stream/3'); +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +const fetch = require('node-fetch'); +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + +#### Buffer +If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) + +```js +const fileType = require('file-type'); + +fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') + .then(res => res.buffer()) + .then(buffer => fileType(buffer)) + .then(type => { /* ... */ }); +``` + +#### Accessing Headers and other Meta data +```js +fetch('https://github.com/') + .then(res => { + console.log(res.ok); + console.log(res.status); + console.log(res.statusText); + console.log(res.headers.raw()); + console.log(res.headers.get('content-type')); + }); +``` + +#### Extract Set-Cookie Header + +Unlike browsers, you can access raw `Set-Cookie` headers manually using `Headers.raw()`. This is a `node-fetch` only API. + +```js +fetch(url).then(res => { + // returns an array of values, instead of a string of comma-separated values + console.log(res.headers.raw()['set-cookie']); +}); +``` + +#### Post data using a file stream + +```js +const { createReadStream } = require('fs'); + +const stream = createReadStream('input.txt'); + +fetch('https://httpbin.org/post', { method: 'POST', body: stream }) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Post with form-data (detect multipart) + +```js +const FormData = require('form-data'); + +const form = new FormData(); +form.append('a', 1); + +fetch('https://httpbin.org/post', { method: 'POST', body: form }) + .then(res => res.json()) + .then(json => console.log(json)); + +// OR, using custom headers +// NOTE: getHeaders() is non-standard API + +const form = new FormData(); +form.append('a', 1); + +const options = { + method: 'POST', + body: form, + headers: form.getHeaders() +} + +fetch('https://httpbin.org/post', options) + .then(res => res.json()) + .then(json => console.log(json)); +``` + +#### Request cancellation with AbortSignal + +> NOTE: You may cancel streamed requests only on Node >= v8.0.0 + +You may cancel requests with `AbortController`. A suggested implementation is [`abort-controller`](https://www.npmjs.com/package/abort-controller). + +An example of timing out a request after 150ms could be achieved as the following: + +```js +import AbortController from 'abort-controller'; + +const controller = new AbortController(); +const timeout = setTimeout( + () => { controller.abort(); }, + 150, +); + +fetch(url, { signal: controller.signal }) + .then(res => res.json()) + .then( + data => { + useData(data) + }, + err => { + if (err.name === 'AbortError') { + // request was aborted + } + }, + ) + .finally(() => { + clearTimeout(timeout); + }); +``` + +See [test cases](https://github.com/bitinn/node-fetch/blob/master/test/test.js) for more examples. + + +## API + +### fetch(url[, options]) + +- `url` A string representing the URL for fetching +- `options` [Options](#fetch-options) for the HTTP(S) request +- Returns: Promise<[Response](#class-response)> + +Perform an HTTP(S) fetch. + +`url` should be an absolute url, such as `https://example.com/`. A path-relative URL (`/file/under/root`) or protocol-relative URL (`//can-be-http-or-https.com/`) will result in a rejected `Promise`. + + +### Options + +The default values are shown after each option key. + +```js +{ + // These properties are part of the Fetch Standard + method: 'GET', + headers: {}, // request headers. format is the identical to that accepted by the Headers constructor (see below) + body: null, // request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream + redirect: 'follow', // set to `manual` to extract redirect headers, `error` to reject redirect + signal: null, // pass an instance of AbortSignal to optionally abort requests + + // The following properties are node-fetch extensions + follow: 20, // maximum redirect count. 0 to not follow redirect + timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead. + compress: true, // support gzip/deflate content encoding. false to disable + size: 0, // maximum response body size in bytes. 0 to disable + agent: null // http(s).Agent instance or function that returns an instance (see below) +} +``` + +##### Default Headers + +If no values are set, the following request headers will be sent automatically: + +Header | Value +------------------- | -------------------------------------------------------- +`Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ +`Accept` | `*/*` +`Content-Length` | _(automatically calculated, if possible)_ +`Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ +`User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` + +Note: when `body` is a `Stream`, `Content-Length` is not set automatically. + +##### Custom Agent + +The `agent` option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following: + +- Support self-signed certificate +- Use only IPv4 or IPv6 +- Custom DNS Lookup + +See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. + +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + +In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. + +```js +const httpAgent = new http.Agent({ + keepAlive: true +}); +const httpsAgent = new https.Agent({ + keepAlive: true +}); + +const options = { + agent: function (_parsedURL) { + if (_parsedURL.protocol == 'http:') { + return httpAgent; + } else { + return httpsAgent; + } + } +} +``` + + +### Class: Request + +An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the [Body](#iface-body) interface. + +Due to the nature of Node.js, the following properties are not implemented at this moment: + +- `type` +- `destination` +- `referrer` +- `referrerPolicy` +- `mode` +- `credentials` +- `cache` +- `integrity` +- `keepalive` + +The following node-fetch extension properties are provided: + +- `follow` +- `compress` +- `counter` +- `agent` + +See [options](#fetch-options) for exact meaning of these extensions. + +#### new Request(input[, options]) + +*(spec-compliant)* + +- `input` A string representing a URL, or another `Request` (which will be cloned) +- `options` [Options][#fetch-options] for the HTTP(S) request + +Constructs a new `Request` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request). + +In most cases, directly `fetch(url, options)` is simpler than creating a `Request` object. + + +### Class: Response + +An HTTP(S) response. This class implements the [Body](#iface-body) interface. + +The following properties are not implemented in node-fetch at this moment: + +- `Response.error()` +- `Response.redirect()` +- `type` +- `trailer` + +#### new Response([body[, options]]) + +*(spec-compliant)* + +- `body` A `String` or [`Readable` stream][node-readable] +- `options` A [`ResponseInit`][response-init] options dictionary + +Constructs a new `Response` object. The constructor is identical to that in the [browser](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response). + +Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a `Response` directly. + +#### response.ok + +*(spec-compliant)* + +Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300. + +#### response.redirected + +*(spec-compliant)* + +Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0. + + +### Class: Headers + +This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the [Fetch Standard][whatwg-fetch] are implemented. + +#### new Headers([init]) + +*(spec-compliant)* + +- `init` Optional argument to pre-fill the `Headers` object + +Construct a new `Headers` object. `init` can be either `null`, a `Headers` object, an key-value map object or any iterable object. + +```js +// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class + +const meta = { + 'Content-Type': 'text/xml', + 'Breaking-Bad': '<3' +}; +const headers = new Headers(meta); + +// The above is equivalent to +const meta = [ + [ 'Content-Type', 'text/xml' ], + [ 'Breaking-Bad', '<3' ] +]; +const headers = new Headers(meta); + +// You can in fact use any iterable objects, like a Map or even another Headers +const meta = new Map(); +meta.set('Content-Type', 'text/xml'); +meta.set('Breaking-Bad', '<3'); +const headers = new Headers(meta); +const copyOfHeaders = new Headers(headers); +``` + + +### Interface: Body + +`Body` is an abstract interface with methods that are applicable to both `Request` and `Response` classes. + +The following methods are not yet implemented in node-fetch at this moment: + +- `formData()` + +#### body.body + +*(deviation from spec)* + +* Node.js [`Readable` stream][node-readable] + +Data are encapsulated in the `Body` object. Note that while the [Fetch Standard][whatwg-fetch] requires the property to always be a WHATWG `ReadableStream`, in node-fetch it is a Node.js [`Readable` stream][node-readable]. + +#### body.bodyUsed + +*(spec-compliant)* + +* `Boolean` + +A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again. + +#### body.arrayBuffer() +#### body.blob() +#### body.json() +#### body.text() + +*(spec-compliant)* + +* Returns: Promise + +Consume the body and return a promise that will resolve to one of these formats. + +#### body.buffer() + +*(node-fetch extension)* + +* Returns: Promise<Buffer> + +Consume the body and return a promise that will resolve to a Buffer. + +#### body.textConverted() + +*(node-fetch extension)* + +* Returns: Promise<String> + +Identical to `body.text()`, except instead of always converting to UTF-8, encoding sniffing will be performed and text converted to UTF-8 if possible. + +(This API requires an optional dependency of the npm package [encoding](https://www.npmjs.com/package/encoding), which you need to install manually. `webpack` users may see [a warning message](https://github.com/bitinn/node-fetch/issues/412#issuecomment-379007792) due to this optional dependency.) + + +### Class: FetchError + +*(node-fetch extension)* + +An operational error in the fetching process. See [ERROR-HANDLING.md][] for more info. + + +### Class: AbortError + +*(node-fetch extension)* + +An Error thrown when the request is aborted in response to an `AbortSignal`'s `abort` event. It has a `name` property of `AbortError`. See [ERROR-HANDLING.MD][] for more info. + +## Acknowledgement + +Thanks to [github/fetch](https://github.com/github/fetch) for providing a solid implementation reference. + +`node-fetch` v1 was maintained by [@bitinn](https://github.com/bitinn); v2 was maintained by [@TimothyGu](https://github.com/timothygu), [@bitinn](https://github.com/bitinn) and [@jimmywarting](https://github.com/jimmywarting); v2 readme is written by [@jkantr](https://github.com/jkantr). + +## License + +MIT + +[npm-image]: https://flat.badgen.net/npm/v/node-fetch +[npm-url]: https://www.npmjs.com/package/node-fetch +[travis-image]: https://flat.badgen.net/travis/bitinn/node-fetch +[travis-url]: https://travis-ci.org/bitinn/node-fetch +[codecov-image]: https://flat.badgen.net/codecov/c/github/bitinn/node-fetch/master +[codecov-url]: https://codecov.io/gh/bitinn/node-fetch +[install-size-image]: https://flat.badgen.net/packagephobia/install/node-fetch +[install-size-url]: https://packagephobia.now.sh/result?p=node-fetch +[discord-image]: https://img.shields.io/discord/619915844268326952?color=%237289DA&label=Discord&style=flat-square +[discord-url]: https://discord.gg/Zxbndcm +[opencollective-image]: https://opencollective.com/node-fetch/backers.svg +[opencollective-url]: https://opencollective.com/node-fetch +[whatwg-fetch]: https://fetch.spec.whatwg.org/ +[response-init]: https://fetch.spec.whatwg.org/#responseinit +[node-readable]: https://nodejs.org/api/stream.html#stream_readable_streams +[mdn-headers]: https://developer.mozilla.org/en-US/docs/Web/API/Headers +[LIMITS.md]: https://github.com/bitinn/node-fetch/blob/master/LIMITS.md +[ERROR-HANDLING.md]: https://github.com/bitinn/node-fetch/blob/master/ERROR-HANDLING.md +[UPGRADE-GUIDE.md]: https://github.com/bitinn/node-fetch/blob/master/UPGRADE-GUIDE.md diff --git a/node_modules/node-fetch/browser.js b/node_modules/node-fetch/browser.js new file mode 100644 index 0000000..ee86265 --- /dev/null +++ b/node_modules/node-fetch/browser.js @@ -0,0 +1,25 @@ +"use strict"; + +// ref: https://github.com/tc39/proposal-global +var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof global !== 'undefined') { return global; } + throw new Error('unable to locate global object'); +} + +var globalObject = getGlobal(); + +module.exports = exports = globalObject.fetch; + +// Needed for TypeScript and Webpack. +if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); +} + +exports.Headers = globalObject.Headers; +exports.Request = globalObject.Request; +exports.Response = globalObject.Response; diff --git a/node_modules/node-fetch/lib/index.es.js b/node_modules/node-fetch/lib/index.es.js new file mode 100644 index 0000000..aae9799 --- /dev/null +++ b/node_modules/node-fetch/lib/index.es.js @@ -0,0 +1,1777 @@ +process.emitWarning("The .es.js file is deprecated. Use .mjs instead."); + +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/lib/index.js b/node_modules/node-fetch/lib/index.js new file mode 100644 index 0000000..567ff5d --- /dev/null +++ b/node_modules/node-fetch/lib/index.js @@ -0,0 +1,1787 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var Stream = _interopDefault(require('stream')); +var http = _interopDefault(require('http')); +var Url = _interopDefault(require('url')); +var whatwgUrl = _interopDefault(require('whatwg-url')); +var https = _interopDefault(require('https')); +var zlib = _interopDefault(require('zlib')); + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/node_modules/node-fetch/lib/index.mjs b/node_modules/node-fetch/lib/index.mjs new file mode 100644 index 0000000..2863dd9 --- /dev/null +++ b/node_modules/node-fetch/lib/index.mjs @@ -0,0 +1,1775 @@ +import Stream from 'stream'; +import http from 'http'; +import Url from 'url'; +import whatwgUrl from 'whatwg-url'; +import https from 'https'; +import zlib from 'zlib'; + +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; + +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); + +class Blob { + constructor() { + this[TYPE] = ''; + + const blobParts = arguments[0]; + const options = arguments[1]; + + const buffers = []; + let size = 0; + + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } + + this[BUFFER] = Buffer.concat(buffers); + + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; + + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); + + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } +} + +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); + +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ + +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); + + this.message = message; + this.type = type; + + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; + } + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; + +let convert; +try { + convert = require('encoding').convert; +} catch (e) {} + +const INTERNALS = Symbol('Body internals'); + +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; + +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; + + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; + + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; + + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; + + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } +} + +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, + + get bodyUsed() { + return this[INTERNALS].disturbed; + }, + + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, + + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, + + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; + + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, + + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, + + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, + + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; + + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; + +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); + +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; + +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; + + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } + + this[INTERNALS].disturbed = true; + + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } + + let body = this.body; + + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is blob + if (isBlob(body)) { + body = body.stream(); + } + + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } + + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } + + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; + + return new Body.Promise(function (resolve, reject) { + let resTimeout; + + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } + + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } + + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } + + accumBytes += chunk.length; + accum.push(chunk); + }); + + body.on('end', function () { + if (abort) { + return; + } + + clearTimeout(resTimeout); + + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); +} + +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } + + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; + + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } + + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); + + // html5 + if (!res && str) { + res = / 0 && arguments[0] !== undefined ? arguments[0] : undefined; + + this[MAP] = Object.create(null); + + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); + + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } + + return; + } + + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } + + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } + + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } + + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } + + return this[MAP][key].join(', '); + } + + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; + + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } + + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } + + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } + + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } + + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } + + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } + + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } +} +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; + +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); + +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; + + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} + +const INTERNAL = Symbol('internal'); + +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; +} + +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } + + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; + + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } + + this[INTERNAL].index = index + 1; + + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); + +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); + +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); + + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } + + return obj; +} + +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} + +const INTERNALS$1 = Symbol('Response internals'); + +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; + +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + Body.call(this, body, opts); + + const status = opts.status || 200; + const headers = new Headers(opts.headers); + + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } + + get url() { + return this[INTERNALS$1].url || ''; + } + + get status() { + return this[INTERNALS$1].status; + } + + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } + + get redirected() { + return this[INTERNALS$1].counter > 0; + } + + get statusText() { + return this[INTERNALS$1].statusText; + } + + get headers() { + return this[INTERNALS$1].headers; + } + + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } +} + +Body.mixIn(Response.prototype); + +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); + +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; + +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; + +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } + + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); +} + +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; + +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; +} + +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} + +/** + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void + */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let parsedURL; + + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } + + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); + + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } + + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); + + const headers = new Headers(init.headers || input.headers || {}); + + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } + + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; + + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } + + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; + + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } + + get method() { + return this[INTERNALS$2].method; + } + + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } + + get headers() { + return this[INTERNALS$2].headers; + } + + get redirect() { + return this[INTERNALS$2].redirect; + } + + get signal() { + return this[INTERNALS$2].signal; + } + + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } +} + +Body.mixIn(Request.prototype); + +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); + +/** + * Convert a Request to Node.js http request options. + * + * @param Request A Request instance + * @return Object The options object to be passed to http.request + */ +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); + + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } + + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } + + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } + + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } + + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } + + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } + + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } + + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); +} + +/** + * abort-error.js + * + * AbortError interface for cancelled requests + */ + +/** + * Create AbortError instance + * + * @param String message Error message for human + * @return AbortError + */ +function AbortError(message) { + Error.call(this, message); + + this.type = 'aborted'; + this.message = message; + + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} + +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; + +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + +/** + * Fetch function + * + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise + */ +function fetch(url, opts) { + + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } + + Body.Promise = fetch.Promise; + + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); + + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; + + let response = null; + + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; + + if (signal && signal.aborted) { + abort(); + return; + } + + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; + + // send request + const req = send(options); + let reqTimeout; + + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } + + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } + + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + + finalize(); + }); + + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + + req.on('response', function (res) { + clearTimeout(reqTimeout); + + const headers = createHeadersLenient(res.headers); + + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); + + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } + + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } + + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; + + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } + + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } + + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } + + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } + + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); + + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; + + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); + + // HTTP-network fetch step 12.1.1.4: handle content codings + + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } + + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); +} +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + +/** + * Redirect code matching + * + * @param Number code Status code + * @return Boolean + */ +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; + +// expose Promise +fetch.Promise = global.Promise; + +export default fetch; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/package.json b/node_modules/node-fetch/package.json new file mode 100644 index 0000000..e0be176 --- /dev/null +++ b/node_modules/node-fetch/package.json @@ -0,0 +1,89 @@ +{ + "name": "node-fetch", + "version": "2.7.0", + "description": "A light-weight module that brings window.fetch to node.js", + "main": "lib/index.js", + "browser": "./browser.js", + "module": "lib/index.mjs", + "files": [ + "lib/index.js", + "lib/index.mjs", + "lib/index.es.js", + "browser.js" + ], + "engines": { + "node": "4.x || >=6.0.0" + }, + "scripts": { + "build": "cross-env BABEL_ENV=rollup rollup -c", + "prepare": "npm run build", + "test": "cross-env BABEL_ENV=test mocha --require babel-register --throw-deprecation test/test.js", + "report": "cross-env BABEL_ENV=coverage nyc --reporter lcov --reporter text mocha -R spec test/test.js", + "coverage": "cross-env BABEL_ENV=coverage nyc --reporter json --reporter text mocha -R spec test/test.js && codecov -f coverage/coverage-final.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/bitinn/node-fetch.git" + }, + "keywords": [ + "fetch", + "http", + "promise" + ], + "author": "David Frank", + "license": "MIT", + "bugs": { + "url": "https://github.com/bitinn/node-fetch/issues" + }, + "homepage": "https://github.com/bitinn/node-fetch", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + }, + "devDependencies": { + "@ungap/url-search-params": "^0.1.2", + "abort-controller": "^1.1.0", + "abortcontroller-polyfill": "^1.3.0", + "babel-core": "^6.26.3", + "babel-plugin-istanbul": "^4.1.6", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "1.4.0", + "babel-register": "^6.16.3", + "chai": "^3.5.0", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^1.1.1", + "chai-string": "~1.3.0", + "codecov": "3.3.0", + "cross-env": "^5.2.0", + "form-data": "^2.3.3", + "is-builtin-module": "^1.0.0", + "mocha": "^5.0.0", + "nyc": "11.9.0", + "parted": "^0.1.1", + "promise": "^8.0.3", + "resumer": "0.0.0", + "rollup": "^0.63.4", + "rollup-plugin-babel": "^3.0.7", + "string-to-arraybuffer": "^1.0.2", + "teeny-request": "3.7.0" + }, + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] + } +} diff --git a/node_modules/openai/CHANGELOG.md b/node_modules/openai/CHANGELOG.md new file mode 100644 index 0000000..2dc86a5 --- /dev/null +++ b/node_modules/openai/CHANGELOG.md @@ -0,0 +1,694 @@ +# Changelog + +## 4.26.0 (2024-01-25) + +Full Changelog: [v4.25.0...v4.26.0](https://github.com/openai/openai-node/compare/v4.25.0...v4.26.0) + +### Features + +* **api:** add text embeddings dimensions param ([#650](https://github.com/openai/openai-node/issues/650)) ([1b5a977](https://github.com/openai/openai-node/commit/1b5a977d0eef7f5cf97daf27333cbbeb6bb479f3)) + + +### Chores + +* **internal:** add internal helpers & improve build scripts ([#643](https://github.com/openai/openai-node/issues/643)) ([9392f50](https://github.com/openai/openai-node/commit/9392f50e47f26b16632c9eb12187ea7f8a565e09)) +* **internal:** adjust ecosystem-tests logging in CI ([#646](https://github.com/openai/openai-node/issues/646)) ([156084b](https://github.com/openai/openai-node/commit/156084b8734194a5856612378115b948c82ec6e4)) +* **internal:** don't re-export streaming type ([#648](https://github.com/openai/openai-node/issues/648)) ([4c4be94](https://github.com/openai/openai-node/commit/4c4be945fa3f54036183e2d0877060db47ea564b)) +* **internal:** fix binary files ([#645](https://github.com/openai/openai-node/issues/645)) ([e1fbc39](https://github.com/openai/openai-node/commit/e1fbc396f4d1dd8ba980c25ba03b670dfed887a0)) +* **internal:** minor streaming updates ([#647](https://github.com/openai/openai-node/issues/647)) ([2f073e4](https://github.com/openai/openai-node/commit/2f073e4e6c9cd0ff3ad434907da710704765a005)) +* **internal:** pin deno version ([#649](https://github.com/openai/openai-node/issues/649)) ([7e4b903](https://github.com/openai/openai-node/commit/7e4b9039320e4ccbafb45f57dce273bedc9b7cb3)) + +## 4.25.0 (2024-01-21) + +Full Changelog: [v4.24.7...v4.25.0](https://github.com/openai/openai-node/compare/v4.24.7...v4.25.0) + +### Features + +* **api:** add usage to runs and run steps ([#640](https://github.com/openai/openai-node/issues/640)) ([3caa416](https://github.com/openai/openai-node/commit/3caa4166b8abb5bffb4c8be1495834b7f16af32d)) + + +### Bug Fixes + +* allow body type in RequestOptions to be null ([#637](https://github.com/openai/openai-node/issues/637)) ([c4f8a36](https://github.com/openai/openai-node/commit/c4f8a3698dc1d80439131c5097975d6a5db1b4e2)) +* handle system_fingerprint in streaming helpers ([#636](https://github.com/openai/openai-node/issues/636)) ([f273530](https://github.com/openai/openai-node/commit/f273530ac491300842aef463852821a1a27805fb)) +* **types:** accept undefined for optional client options ([#635](https://github.com/openai/openai-node/issues/635)) ([e48cd57](https://github.com/openai/openai-node/commit/e48cd57931cd0e81a77b55653cb1f663111dd733)) + + +### Chores + +* **internal:** debug logging for retries; speculative retry-after-ms support ([#633](https://github.com/openai/openai-node/issues/633)) ([fd64971](https://github.com/openai/openai-node/commit/fd64971612d1d7fcbd8a63885d333485bff68ab1)) +* **internal:** update comment ([#631](https://github.com/openai/openai-node/issues/631)) ([e109d40](https://github.com/openai/openai-node/commit/e109d40a5c02c5bf4586e54d92bf0e355d254c1b)) + +## 4.24.7 (2024-01-13) + +Full Changelog: [v4.24.6...v4.24.7](https://github.com/openai/openai-node/compare/v4.24.6...v4.24.7) + +### Chores + +* **ecosystem-tests:** fix flaky vercel-edge, cloudflare-worker, and deno tests ([#626](https://github.com/openai/openai-node/issues/626)) ([ae412a5](https://github.com/openai/openai-node/commit/ae412a5f12e701e07e71bd9791c55a56858e8383)) +* **ecosystem-tests:** fix typo in deno test ([#628](https://github.com/openai/openai-node/issues/628)) ([048ec94](https://github.com/openai/openai-node/commit/048ec943f8d12acba9829c35ebf0b2d3f24930c8)) + +## 4.24.6 (2024-01-12) + +Full Changelog: [v4.24.5...v4.24.6](https://github.com/openai/openai-node/compare/v4.24.5...v4.24.6) + +### Chores + +* **ecosystem-tests:** fix flaky tests and remove fine tuning calls ([#623](https://github.com/openai/openai-node/issues/623)) ([258d79f](https://github.com/openai/openai-node/commit/258d79f52bb31f4f3723f6f4b97ebe8f3fa187bd)) +* **ecosystem-tests:** fix flaky tests and remove fine tuning calls ([#625](https://github.com/openai/openai-node/issues/625)) ([58e5fd8](https://github.com/openai/openai-node/commit/58e5fd8f27052be6ac9587256b161f4bf3a3805f)) + +## 4.24.5 (2024-01-12) + +Full Changelog: [v4.24.4...v4.24.5](https://github.com/openai/openai-node/compare/v4.24.4...v4.24.5) + +### Refactors + +* **api:** remove deprecated endpoints ([#621](https://github.com/openai/openai-node/issues/621)) ([2054d71](https://github.com/openai/openai-node/commit/2054d71e6b0d407229a4c5aecd75e38c336c2c02)) + +## 4.24.4 (2024-01-11) + +Full Changelog: [v4.24.3...v4.24.4](https://github.com/openai/openai-node/compare/v4.24.3...v4.24.4) + +### Chores + +* **internal:** narrow type into stringifyQuery ([#619](https://github.com/openai/openai-node/issues/619)) ([88fb9cd](https://github.com/openai/openai-node/commit/88fb9cd1bb415850b0b4868944617282d0b92e2a)) + +## 4.24.3 (2024-01-10) + +Full Changelog: [v4.24.2...v4.24.3](https://github.com/openai/openai-node/compare/v4.24.2...v4.24.3) + +### Bug Fixes + +* use default base url if BASE_URL env var is blank ([#615](https://github.com/openai/openai-node/issues/615)) ([a27ad3d](https://github.com/openai/openai-node/commit/a27ad3d4e06f2202daa169668d0e7d89e87a38a7)) + +## 4.24.2 (2024-01-08) + +Full Changelog: [v4.24.1...v4.24.2](https://github.com/openai/openai-node/compare/v4.24.1...v4.24.2) + +### Bug Fixes + +* **headers:** always send lowercase headers and strip undefined (BREAKING in rare cases) ([#608](https://github.com/openai/openai-node/issues/608)) ([4ea159f](https://github.com/openai/openai-node/commit/4ea159f0aa9a1f4c365c74ee726714fe692ddf9f)) + + +### Chores + +* add .keep files for examples and custom code directories ([#612](https://github.com/openai/openai-node/issues/612)) ([5e0f733](https://github.com/openai/openai-node/commit/5e0f733d3cd3c8e6d41659141168cd0708e017a3)) +* **internal:** bump license ([#605](https://github.com/openai/openai-node/issues/605)) ([045ee74](https://github.com/openai/openai-node/commit/045ee74fd3ffba9e6d1301fe1ffd8bd3c63720a2)) +* **internal:** improve type signatures ([#609](https://github.com/openai/openai-node/issues/609)) ([e1ccc82](https://github.com/openai/openai-node/commit/e1ccc82e4991262a631dcffa4d09bdc553e50fbb)) + + +### Documentation + +* fix docstring typos ([#600](https://github.com/openai/openai-node/issues/600)) ([1934fa1](https://github.com/openai/openai-node/commit/1934fa15f654ea89e226457f76febe6015616f6c)) +* improve audio example to show how to stream to a file ([#598](https://github.com/openai/openai-node/issues/598)) ([e950ad9](https://github.com/openai/openai-node/commit/e950ad969e845d608ed71bd3e3095cd6c941d93d)) + +## 4.24.1 (2023-12-22) + +Full Changelog: [v4.24.0...v4.24.1](https://github.com/openai/openai-node/compare/v4.24.0...v4.24.1) + +### Bug Fixes + +* **pagination:** correct type annotation object field ([#590](https://github.com/openai/openai-node/issues/590)) ([4066eda](https://github.com/openai/openai-node/commit/4066edad4b5305e82e610f44f4720843f2b69d39)) + + +### Documentation + +* **messages:** improvements to helpers reference + typos ([#595](https://github.com/openai/openai-node/issues/595)) ([96a59b9](https://github.com/openai/openai-node/commit/96a59b91c424db67b8a5bdb7cab5da68c57282d4)) +* reformat README.md ([#592](https://github.com/openai/openai-node/issues/592)) ([8ffc7f8](https://github.com/openai/openai-node/commit/8ffc7f876cc8f4b7afaf68a37f94f826ef22a6b8)) + + +### Refactors + +* write jest config in typescript ([#588](https://github.com/openai/openai-node/issues/588)) ([eb6ceeb](https://github.com/openai/openai-node/commit/eb6ceebf90ba45ec5b803f32b9b080829f6a973a)) + +## 4.24.0 (2023-12-19) + +Full Changelog: [v4.23.0...v4.24.0](https://github.com/openai/openai-node/compare/v4.23.0...v4.24.0) + +### Features + +* **api:** add additional instructions for runs ([#586](https://github.com/openai/openai-node/issues/586)) ([401d93e](https://github.com/openai/openai-node/commit/401d93ea39fe0e90088799858299322035c0a7e8)) + + +### Chores + +* **deps:** update dependency start-server-and-test to v2.0.3 ([#580](https://github.com/openai/openai-node/issues/580)) ([8e1aca1](https://github.com/openai/openai-node/commit/8e1aca1f8be6e583483919ed9ef9b04fab076066)) +* **deps:** update dependency ts-jest to v29.1.1 ([#578](https://github.com/openai/openai-node/issues/578)) ([a6edb7b](https://github.com/openai/openai-node/commit/a6edb7bc3cfc447d0c55ae23cc1c2219105d3666)) +* **deps:** update jest ([#582](https://github.com/openai/openai-node/issues/582)) ([e49e471](https://github.com/openai/openai-node/commit/e49e471ec7a136f2cbaf82551ccaaea366c87a91)) +* **internal:** bump deps ([#583](https://github.com/openai/openai-node/issues/583)) ([2e07b4c](https://github.com/openai/openai-node/commit/2e07b4c66ab1fdbb353fdd00994e293f93e981db)) +* **internal:** update deps ([#581](https://github.com/openai/openai-node/issues/581)) ([7b690dc](https://github.com/openai/openai-node/commit/7b690dca67ee8c3b0a89caf7f786ede5dc612a76)) + + +### Documentation + +* upgrade models in examples to latest version ([#585](https://github.com/openai/openai-node/issues/585)) ([60101a4](https://github.com/openai/openai-node/commit/60101a4117b1a8223d09fb9fe21d89af32431939)) + +## 4.23.0 (2023-12-17) + +Full Changelog: [v4.22.1...v4.23.0](https://github.com/openai/openai-node/compare/v4.22.1...v4.23.0) + +### Features + +* **api:** add token logprobs to chat completions ([#576](https://github.com/openai/openai-node/issues/576)) ([8d4292e](https://github.com/openai/openai-node/commit/8d4292e6358920b2c9d8df49c6a154231c468512)) + + +### Chores + +* **ci:** run release workflow once per day ([#574](https://github.com/openai/openai-node/issues/574)) ([529f09f](https://github.com/openai/openai-node/commit/529f09f827a675d6e851590acff4e6f4f2af2d26)) + +## 4.22.1 (2023-12-15) + +Full Changelog: [v4.22.0...v4.22.1](https://github.com/openai/openai-node/compare/v4.22.0...v4.22.1) + +### Chores + +* update dependencies ([#572](https://github.com/openai/openai-node/issues/572)) ([a51e620](https://github.com/openai/openai-node/commit/a51e62065224a516b17dd850ae564f5436d8db52)) + + +### Documentation + +* replace runFunctions with runTools in readme ([#570](https://github.com/openai/openai-node/issues/570)) ([c3b9ad5](https://github.com/openai/openai-node/commit/c3b9ad58e5f74d3339889aeb1d758c8c18f54de7)) + +## 4.22.0 (2023-12-15) + +Full Changelog: [v4.21.0...v4.22.0](https://github.com/openai/openai-node/compare/v4.21.0...v4.22.0) + +### Features + +* **api:** add optional `name` argument + improve docs ([#569](https://github.com/openai/openai-node/issues/569)) ([3b68ace](https://github.com/openai/openai-node/commit/3b68ace533976aedbf642d9b018d0de8d9a8bb88)) + + +### Chores + +* update prettier ([#567](https://github.com/openai/openai-node/issues/567)) ([83dec2a](https://github.com/openai/openai-node/commit/83dec2af62c481d7de16d8a3644aa239ded9e30c)) + +## 4.21.0 (2023-12-11) + +Full Changelog: [v4.20.1...v4.21.0](https://github.com/openai/openai-node/compare/v4.20.1...v4.21.0) + +### Features + +* **client:** support reading the base url from an env variable ([#547](https://github.com/openai/openai-node/issues/547)) ([06fb68d](https://github.com/openai/openai-node/commit/06fb68de1ff80983e349b6715d1037e2072c8dd4)) + + +### Bug Fixes + +* correct some runTools behavior and deprecate runFunctions ([#562](https://github.com/openai/openai-node/issues/562)) ([f5cdd0f](https://github.com/openai/openai-node/commit/f5cdd0f704d3d075cdfc5bc2df1f7a8bae5cd9f1)) +* prevent 400 when using runTools/runFunctions with Azure OpenAI API ([#544](https://github.com/openai/openai-node/issues/544)) ([735d9b8](https://github.com/openai/openai-node/commit/735d9b86acdc067e1ee6ebe1ea50de2955431050)) + + +### Documentation + +* **readme:** update example snippets ([#546](https://github.com/openai/openai-node/issues/546)) ([566d290](https://github.com/openai/openai-node/commit/566d290006920f536788bb77f4d24a6906e2971f)) + + +### Build System + +* specify `packageManager: yarn` ([#561](https://github.com/openai/openai-node/issues/561)) ([935b898](https://github.com/openai/openai-node/commit/935b8983c74f7b03b67d22f4d194989838f963f3)) + +## 4.20.1 (2023-11-24) + +Full Changelog: [v4.20.0...v4.20.1](https://github.com/openai/openai-node/compare/v4.20.0...v4.20.1) + +### Chores + +* **internal:** remove file import and conditionally run prepare ([#533](https://github.com/openai/openai-node/issues/533)) ([48cb729](https://github.com/openai/openai-node/commit/48cb729bfc484ce3d04273be417b307a0d20644f)) + + +### Documentation + +* **readme:** fix typo and add examples link ([#529](https://github.com/openai/openai-node/issues/529)) ([cf959b1](https://github.com/openai/openai-node/commit/cf959b17db0a4f8dd7eb59add333c4a461b02459)) + +## 4.20.0 (2023-11-22) + +Full Changelog: [v4.19.1...v4.20.0](https://github.com/openai/openai-node/compare/v4.19.1...v4.20.0) + +### Features + +* allow installing package directly from github ([#522](https://github.com/openai/openai-node/issues/522)) ([51926d7](https://github.com/openai/openai-node/commit/51926d7a0092744e49de39f4988feddf313adafa)) + + +### Chores + +* **internal:** don't call prepare in dist ([#525](https://github.com/openai/openai-node/issues/525)) ([d09411e](https://github.com/openai/openai-node/commit/d09411ebaa28d6610e1b880d03339d520b4a1833)) + +## 4.19.1 (2023-11-20) + +Full Changelog: [v4.19.0...v4.19.1](https://github.com/openai/openai-node/compare/v4.19.0...v4.19.1) + +## 4.19.0 (2023-11-15) + +Full Changelog: [v4.18.0...v4.19.0](https://github.com/openai/openai-node/compare/v4.18.0...v4.19.0) + +### Features + +* **api:** updates ([#501](https://github.com/openai/openai-node/issues/501)) ([944d58e](https://github.com/openai/openai-node/commit/944d58e5fc46f1a0671aaa2b809d28e67edf6023)) + +## 4.18.0 (2023-11-14) + +Full Changelog: [v4.17.5...v4.18.0](https://github.com/openai/openai-node/compare/v4.17.5...v4.18.0) + +### Features + +* **api:** add gpt-3.5-turbo-1106 ([#496](https://github.com/openai/openai-node/issues/496)) ([45f7672](https://github.com/openai/openai-node/commit/45f7672ccf4856ac309b08c6c96f0e73ab48b525)) + +## 4.17.5 (2023-11-13) + +Full Changelog: [v4.17.4...v4.17.5](https://github.com/openai/openai-node/compare/v4.17.4...v4.17.5) + +### Chores + +* fix typo in docs and add request header for function calls ([#494](https://github.com/openai/openai-node/issues/494)) ([22ce244](https://github.com/openai/openai-node/commit/22ce2443a77f10988b3215bd81ba17d4eda4b10e)) + +## 4.17.4 (2023-11-10) + +Full Changelog: [v4.17.3...v4.17.4](https://github.com/openai/openai-node/compare/v4.17.3...v4.17.4) + +### Chores + +* **internal:** update jest config ([#482](https://github.com/openai/openai-node/issues/482)) ([3013e8c](https://github.com/openai/openai-node/commit/3013e8c73a61a397a418ca75b996f0a7dd03a744)) + +## 4.17.3 (2023-11-09) + +Full Changelog: [v4.17.2...v4.17.3](https://github.com/openai/openai-node/compare/v4.17.2...v4.17.3) + +## 4.17.2 (2023-11-09) + +Full Changelog: [v4.17.1...v4.17.2](https://github.com/openai/openai-node/compare/v4.17.1...v4.17.2) + +### Chores + +* **internal:** bump deno version number ([#478](https://github.com/openai/openai-node/issues/478)) ([69913f3](https://github.com/openai/openai-node/commit/69913f3a4b0123394029759375445dae7b4f15ab)) + +## 4.17.1 (2023-11-09) + +Full Changelog: [v4.17.0...v4.17.1](https://github.com/openai/openai-node/compare/v4.17.0...v4.17.1) + +### Refactors + +* **client:** deprecate files.retrieveContent in favour of files.content ([#474](https://github.com/openai/openai-node/issues/474)) ([7c7bfc2](https://github.com/openai/openai-node/commit/7c7bfc2fad5a786c9172110e90c9566a943e49f9)) + +## 4.17.0 (2023-11-08) + +Full Changelog: [v4.16.2...v4.17.0](https://github.com/openai/openai-node/compare/v4.16.2...v4.17.0) + +### Features + +* **api:** unify function types ([#467](https://github.com/openai/openai-node/issues/467)) ([d51cd94](https://github.com/openai/openai-node/commit/d51cd94b3103219789447e2e9afc4762ae672e5a)) + + +### Refactors + +* **api:** rename FunctionObject to FunctionDefinition ([#470](https://github.com/openai/openai-node/issues/470)) ([f3990c7](https://github.com/openai/openai-node/commit/f3990c779e596309b62f41d7a1253d8629aca3bf)) + +## 4.16.2 (2023-11-08) + +Full Changelog: [v4.16.1...v4.16.2](https://github.com/openai/openai-node/compare/v4.16.1...v4.16.2) + +### Bug Fixes + +* **api:** accidentally required params, add new models & other fixes ([#463](https://github.com/openai/openai-node/issues/463)) ([1cb403e](https://github.com/openai/openai-node/commit/1cb403e4ccde61bb1613d362f6bdbca8b1681e00)) +* **api:** update embedding response object type ([#466](https://github.com/openai/openai-node/issues/466)) ([53b7e25](https://github.com/openai/openai-node/commit/53b7e2539cca0b272be96136c123d2b33745e7f6)) +* asssitant_deleted -> assistant_deleted ([#452](https://github.com/openai/openai-node/issues/452)) ([ef89bd7](https://github.com/openai/openai-node/commit/ef89bd74d85c833bf7de500eecd1b092a0ad3f37)) +* **types:** ensure all code paths return a value ([#458](https://github.com/openai/openai-node/issues/458)) ([19402c3](https://github.com/openai/openai-node/commit/19402c365572a99cbee58bcd34a9942e741269bf)) + + +### Chores + +* **docs:** fix github links ([#457](https://github.com/openai/openai-node/issues/457)) ([6b9b94e](https://github.com/openai/openai-node/commit/6b9b94e4e123349a908b708cd574ff107f40a8e1)) +* **internal:** fix typo in comment ([#456](https://github.com/openai/openai-node/issues/456)) ([fe24342](https://github.com/openai/openai-node/commit/fe2434284a91d424510873a18079b8870469c672)) + + +### Documentation + +* update deno deploy link to include v ([#441](https://github.com/openai/openai-node/issues/441)) ([47b13aa](https://github.com/openai/openai-node/commit/47b13aaa6fac86fffabee1f752ee6d2efc3def9b)) + +## 4.16.1 (2023-11-06) + +Full Changelog: [v4.16.0...v4.16.1](https://github.com/openai/openai-node/compare/v4.16.0...v4.16.1) + +### Bug Fixes + +* **api:** retreival -> retrieval ([#437](https://github.com/openai/openai-node/issues/437)) ([b4bd3ee](https://github.com/openai/openai-node/commit/b4bd3eefdd3903abcc57c431382cc2124d39307b)) + + +### Documentation + +* **api:** improve docstrings ([#435](https://github.com/openai/openai-node/issues/435)) ([ee8b24c](https://github.com/openai/openai-node/commit/ee8b24c70a5ccb944e02ff2201668d6bc2b597b3)) + +## 4.16.0 (2023-11-06) + +Full Changelog: [v4.15.4...v4.16.0](https://github.com/openai/openai-node/compare/v4.15.4...v4.16.0) + +### Features + +* **api:** releases from DevDay; assistants, multimodality, tools, dall-e-3, tts, and more ([#433](https://github.com/openai/openai-node/issues/433)) ([fb92f5e](https://github.com/openai/openai-node/commit/fb92f5e6e3b6e7969b3d91f4ccdaef87e5fea0a4)) + + +### Bug Fixes + +* improve deno readme ([#429](https://github.com/openai/openai-node/issues/429)) ([871ceac](https://github.com/openai/openai-node/commit/871ceac2b37f53f7fc7c0163454115c709cd7ced)) + + +### Documentation + +* deno version ([#432](https://github.com/openai/openai-node/issues/432)) ([74bf336](https://github.com/openai/openai-node/commit/74bf3364379fd23252fde01401c44b2fa796cba4)) +* update deno link in more places ([#431](https://github.com/openai/openai-node/issues/431)) ([5da63d4](https://github.com/openai/openai-node/commit/5da63d4a9143c0ab493b742f7fde22b01a372844)) + +## 4.15.4 (2023-11-05) + +Full Changelog: [v4.15.3...v4.15.4](https://github.com/openai/openai-node/compare/v4.15.3...v4.15.4) + +### Documentation + +* **readme:** remove redundant whitespace ([#427](https://github.com/openai/openai-node/issues/427)) ([aa3a178](https://github.com/openai/openai-node/commit/aa3a1782914a4a285263e4d070bca73e72ed47ec)) + +## 4.15.3 (2023-11-04) + +Full Changelog: [v4.15.2...v4.15.3](https://github.com/openai/openai-node/compare/v4.15.2...v4.15.3) + +### Bug Fixes + +* improve deno releases ([#425](https://github.com/openai/openai-node/issues/425)) ([19469f2](https://github.com/openai/openai-node/commit/19469f266ff69a4e549402188d9f6ad87f5a7778)) + +## 4.15.2 (2023-11-04) + +Full Changelog: [v4.15.1...v4.15.2](https://github.com/openai/openai-node/compare/v4.15.1...v4.15.2) + +### Documentation + +* fix deno.land import ([#423](https://github.com/openai/openai-node/issues/423)) ([e5415a2](https://github.com/openai/openai-node/commit/e5415a29ab447ced8535fafda7928b0a6748c8d1)) + +## 4.15.1 (2023-11-04) + +Full Changelog: [v4.15.0...v4.15.1](https://github.com/openai/openai-node/compare/v4.15.0...v4.15.1) + +### Documentation + +* document customizing fetch ([#420](https://github.com/openai/openai-node/issues/420)) ([1ca982f](https://github.com/openai/openai-node/commit/1ca982f192daf49e33b7acb5505ed26c9d891255)) + +## 4.15.0 (2023-11-03) + +Full Changelog: [v4.14.2...v4.15.0](https://github.com/openai/openai-node/compare/v4.14.2...v4.15.0) + +### Features + +* **beta:** add streaming and function calling helpers ([#409](https://github.com/openai/openai-node/issues/409)) ([510c1f3](https://github.com/openai/openai-node/commit/510c1f325ee55197b4c2f434475128c265500746)) +* **client:** allow binary returns ([#416](https://github.com/openai/openai-node/issues/416)) ([02f7ad7](https://github.com/openai/openai-node/commit/02f7ad7f736751e0e7687e6744bae464d4e40b79)) +* **github:** include a devcontainer setup ([#413](https://github.com/openai/openai-node/issues/413)) ([fb2996f](https://github.com/openai/openai-node/commit/fb2996f0d291210878145aacf9b952f8133d9414)) +* streaming improvements ([#411](https://github.com/openai/openai-node/issues/411)) ([37b622c](https://github.com/openai/openai-node/commit/37b622c79ddbd6c286b730e740403c82b542e796)) + +## 4.14.2 (2023-10-30) + +Full Changelog: [v4.14.1...v4.14.2](https://github.com/openai/openai-node/compare/v4.14.1...v4.14.2) + +### Chores + +* **docs:** update deno link ([#407](https://github.com/openai/openai-node/issues/407)) ([0328882](https://github.com/openai/openai-node/commit/0328882cccb3e5386283ffa5eb9cd8ad9442f3a0)) + +## 4.14.1 (2023-10-27) + +Full Changelog: [v4.14.0...v4.14.1](https://github.com/openai/openai-node/compare/v4.14.0...v4.14.1) + +### Bug Fixes + +* deploy deno in a github workflow instead of postpublish step ([#405](https://github.com/openai/openai-node/issues/405)) ([3a6dba0](https://github.com/openai/openai-node/commit/3a6dba074258274bffcfe3a4260ca1b95bcd6bdc)) +* typo in build script ([#403](https://github.com/openai/openai-node/issues/403)) ([76c5c96](https://github.com/openai/openai-node/commit/76c5c96a359f750f58ea38b5d32365db7e34409a)) + + +### Chores + +* **internal:** update gitignore ([#406](https://github.com/openai/openai-node/issues/406)) ([986b0bb](https://github.com/openai/openai-node/commit/986b0bbac9f5ca43a0df6f29f2a468dd4223e053)) + +## 4.14.0 (2023-10-25) + +Full Changelog: [v4.13.0...v4.14.0](https://github.com/openai/openai-node/compare/v4.13.0...v4.14.0) + +### Features + +* **client:** adjust retry behavior to be exponential backoff ([#400](https://github.com/openai/openai-node/issues/400)) ([2bc14ce](https://github.com/openai/openai-node/commit/2bc14ce300ef020bc045199fe3d76dd352d78ef9)) + + +### Chores + +* **docs:** update deno version ([#399](https://github.com/openai/openai-node/issues/399)) ([cdee077](https://github.com/openai/openai-node/commit/cdee0770690d4b66b357d970827e9ba1597ffb89)) + +## 4.13.0 (2023-10-22) + +Full Changelog: [v4.12.4...v4.13.0](https://github.com/openai/openai-node/compare/v4.12.4...v4.13.0) + +### Features + +* **api:** add embeddings encoding_format ([#390](https://github.com/openai/openai-node/issues/390)) ([cf70dea](https://github.com/openai/openai-node/commit/cf70deaba1426786aba9b938d280c61aeb516e34)) +* handle 204 No Content gracefully ([#391](https://github.com/openai/openai-node/issues/391)) ([2dd005c](https://github.com/openai/openai-node/commit/2dd005c1c497605036d3524f19d130b3fc5f8d8b)) + +## 4.12.4 (2023-10-17) + +Full Changelog: [v4.12.3...v4.12.4](https://github.com/openai/openai-node/compare/v4.12.3...v4.12.4) + +### Bug Fixes + +* import web-streams-polyfill without overriding globals ([#385](https://github.com/openai/openai-node/issues/385)) ([be8e18b](https://github.com/openai/openai-node/commit/be8e18ba4c6a16e7b6413c77246f83230e0b8fc2)) + +## 4.12.3 (2023-10-16) + +Full Changelog: [v4.12.2...v4.12.3](https://github.com/openai/openai-node/compare/v4.12.2...v4.12.3) + +### Documentation + +* organisation -> organization (UK to US English) ([#382](https://github.com/openai/openai-node/issues/382)) ([516f0ad](https://github.com/openai/openai-node/commit/516f0ade1ec1fd8fc4c78999ee0f656cc2b5ae58)) + +## 4.12.2 (2023-10-16) + +Full Changelog: [v4.12.1...v4.12.2](https://github.com/openai/openai-node/compare/v4.12.1...v4.12.2) + +### Bug Fixes + +* **client:** correctly handle errors during streaming ([#377](https://github.com/openai/openai-node/issues/377)) ([09233b1](https://github.com/openai/openai-node/commit/09233b1ccc80ee900be19050f438cc8aa9dbb513)) +* **client:** correctly handle errors during streaming ([#379](https://github.com/openai/openai-node/issues/379)) ([9ced580](https://github.com/openai/openai-node/commit/9ced5804777a5857d6775a49ddf30ed9cc016fab)) +* improve status code in error messages ([#381](https://github.com/openai/openai-node/issues/381)) ([68dfb17](https://github.com/openai/openai-node/commit/68dfb17cce300ade8d29afc854d616833b3283ca)) + + +### Chores + +* add case insensitive get header function ([#373](https://github.com/openai/openai-node/issues/373)) ([b088998](https://github.com/openai/openai-node/commit/b088998ae610de54bb8700eefd6b664eb9a2fcc3)) +* **internal:** add debug logs for stream responses ([#380](https://github.com/openai/openai-node/issues/380)) ([689db0b](https://github.com/openai/openai-node/commit/689db0b8058527ae5c3af5e457c962d8a6635297)) +* show deprecation notice on re-export ([#368](https://github.com/openai/openai-node/issues/368)) ([b176703](https://github.com/openai/openai-node/commit/b176703102998f0e9d8ca2ed93ccd495fd10a6ee)) +* update comment ([#376](https://github.com/openai/openai-node/issues/376)) ([a06c685](https://github.com/openai/openai-node/commit/a06c6850bfdd756dc8f07dd1f70218be610faa30)) +* update comment ([#378](https://github.com/openai/openai-node/issues/378)) ([b04031d](https://github.com/openai/openai-node/commit/b04031d19210a66f82c7d233a50f7bc427a1bf92)) + + +### Refactors + +* **streaming:** change Stream constructor signature ([#370](https://github.com/openai/openai-node/issues/370)) ([71984ed](https://github.com/openai/openai-node/commit/71984edc3141ba99ffa1327bab6a182b4452209f)) +* **test:** refactor authentication tests ([#371](https://github.com/openai/openai-node/issues/371)) ([e0d459f](https://github.com/openai/openai-node/commit/e0d459f958451a99e15a11a0e5ea6471abbe1ac1)) + +## 4.12.1 (2023-10-11) + +Full Changelog: [v4.12.0...v4.12.1](https://github.com/openai/openai-node/compare/v4.12.0...v4.12.1) + +### Bug Fixes + +* fix namespace exports regression ([#366](https://github.com/openai/openai-node/issues/366)) ([b2b1d85](https://github.com/openai/openai-node/commit/b2b1d85d90eef51e689ca75c0ca2f35bb63cccc0)) + +## 4.12.0 (2023-10-11) + +Full Changelog: [v4.11.1...v4.12.0](https://github.com/openai/openai-node/compare/v4.11.1...v4.12.0) + +### Features + +* **api:** remove `content_filter` stop_reason and update documentation ([#352](https://github.com/openai/openai-node/issues/352)) ([a4b401e](https://github.com/openai/openai-node/commit/a4b401e91a0b3fbf55aedfb6ed6d93396377bf27)) +* re-export chat completion types at the top level, and work around webpack limitations ([#365](https://github.com/openai/openai-node/issues/365)) ([bb815d0](https://github.com/openai/openai-node/commit/bb815d0373ae33f58329e34e8983f5b3881db22d)) + + +### Bug Fixes + +* prevent ReferenceError, update compatibility to ES2020 and Node 18+ ([#356](https://github.com/openai/openai-node/issues/356)) ([fc71a4b](https://github.com/openai/openai-node/commit/fc71a4b6b73208ff3e8f0c8792a9a03e3790d26b)) + + +### Chores + +* **internal:** minor formatting improvement ([#354](https://github.com/openai/openai-node/issues/354)) ([3799863](https://github.com/openai/openai-node/commit/3799863da4ff2a27940ef0b7e57360c72e44d986)) + +## 4.11.1 (2023-10-03) + +Full Changelog: [v4.11.0...v4.11.1](https://github.com/openai/openai-node/compare/v4.11.0...v4.11.1) + +## 4.11.0 (2023-09-29) + +Full Changelog: [v4.10.0...v4.11.0](https://github.com/openai/openai-node/compare/v4.10.0...v4.11.0) + +### Features + +* **client:** handle retry-after with a date ([#340](https://github.com/openai/openai-node/issues/340)) ([b6dd384](https://github.com/openai/openai-node/commit/b6dd38488ea7cc4c22495f16d027b7ffdb87da53)) +* **package:** export a root error type ([#338](https://github.com/openai/openai-node/issues/338)) ([462bcda](https://github.com/openai/openai-node/commit/462bcda7140611afa20bc25de4aec6d4b205b37d)) + + +### Bug Fixes + +* **api:** add content_filter to chat completion finish reason ([#344](https://github.com/openai/openai-node/issues/344)) ([f10c757](https://github.com/openai/openai-node/commit/f10c757d831d90407ba47b4659d9cd34b1a35b1d)) + + +### Chores + +* **internal:** bump lock file ([#334](https://github.com/openai/openai-node/issues/334)) ([fd2337b](https://github.com/openai/openai-node/commit/fd2337b018ab2f31bcea8f9feda0ddaf755390c7)) +* **internal:** update lock file ([#339](https://github.com/openai/openai-node/issues/339)) ([1bf84b6](https://github.com/openai/openai-node/commit/1bf84b672c386f8ca46bb8fc120eb8d8d48b3a82)) +* **internal:** update lock file ([#342](https://github.com/openai/openai-node/issues/342)) ([0001f06](https://github.com/openai/openai-node/commit/0001f062728b0e2047d2bf03b9d947a4be0c7206)) +* **internal:** update lock file ([#343](https://github.com/openai/openai-node/issues/343)) ([a02ac8e](https://github.com/openai/openai-node/commit/a02ac8e7f881551527a3cbcadad53b7e424650e8)) + +## 4.10.0 (2023-09-21) + +Full Changelog: [v4.9.1...v4.10.0](https://github.com/openai/openai-node/compare/v4.9.1...v4.10.0) + +### Features + +* **api:** add 'gpt-3.5-turbo-instruct', fine-tune error objects, update documentation ([#329](https://github.com/openai/openai-node/issues/329)) ([e5f3852](https://github.com/openai/openai-node/commit/e5f385233737002b4bb47a94cba33da7fedfe64d)) + +## 4.10.0 (2023-09-21) + +Full Changelog: [v4.9.1...v4.10.0](https://github.com/openai/openai-node/compare/v4.9.1...v4.10.0) + +### Features + +* **api:** add 'gpt-3.5-turbo-instruct', fine-tune error objects, update documentation ([#329](https://github.com/openai/openai-node/issues/329)) ([e5f3852](https://github.com/openai/openai-node/commit/e5f385233737002b4bb47a94cba33da7fedfe64d)) + +## 4.9.1 (2023-09-21) + +Full Changelog: [v4.9.0...v4.9.1](https://github.com/openai/openai-node/compare/v4.9.0...v4.9.1) + +### Documentation + +* **README:** fix variable names in some examples ([#327](https://github.com/openai/openai-node/issues/327)) ([5e05b31](https://github.com/openai/openai-node/commit/5e05b31c132545ce166cea92c5f3e4410fd40711)) + +## 4.9.0 (2023-09-20) + +Full Changelog: [v4.8.0...v4.9.0](https://github.com/openai/openai-node/compare/v4.8.0...v4.9.0) + +### Features + +* **client:** support importing node or web shims manually ([#325](https://github.com/openai/openai-node/issues/325)) ([628f293](https://github.com/openai/openai-node/commit/628f2935a8791625685f68f73db8f3759b8f4f91)) + +## 4.8.0 (2023-09-15) + +Full Changelog: [v4.7.1...v4.8.0](https://github.com/openai/openai-node/compare/v4.7.1...v4.8.0) + +### Features + +* **errors:** add status code to error message ([#315](https://github.com/openai/openai-node/issues/315)) ([9341219](https://github.com/openai/openai-node/commit/93412197c67cb3fb203f35e3ae0a7c3fb173453e)) + +## 4.7.1 (2023-09-15) + +Full Changelog: [v4.7.0...v4.7.1](https://github.com/openai/openai-node/compare/v4.7.0...v4.7.1) + +### Documentation + +* declare Bun 1.0 officially supported ([#314](https://github.com/openai/openai-node/issues/314)) ([a16e268](https://github.com/openai/openai-node/commit/a16e26863390235cb43e2fe0e569298a4f84c32f)) + +## 4.7.0 (2023-09-14) + +Full Changelog: [v4.6.0...v4.7.0](https://github.com/openai/openai-node/compare/v4.6.0...v4.7.0) + +### Features + +* **client:** retry on 408 Request Timeout ([#310](https://github.com/openai/openai-node/issues/310)) ([1f98eac](https://github.com/openai/openai-node/commit/1f98eac5be956e56d75ef5456115165b45a4763c)) +* make docs urls in comments absolute ([#306](https://github.com/openai/openai-node/issues/306)) ([9db3819](https://github.com/openai/openai-node/commit/9db381961e38d2280b0602447e7d91691b327bde)) + +## 4.6.0 (2023-09-08) + +Full Changelog: [v4.5.0...v4.6.0](https://github.com/openai/openai-node/compare/v4.5.0...v4.6.0) + +### Features + +* **types:** extract ChatCompletionRole enum to its own type ([#298](https://github.com/openai/openai-node/issues/298)) ([5893e37](https://github.com/openai/openai-node/commit/5893e37406ff85331c85a3baa519ca3051a28e00)) + + +### Bug Fixes + +* fix module not found errors in Vercel edge ([#300](https://github.com/openai/openai-node/issues/300)) ([47c79fe](https://github.com/openai/openai-node/commit/47c79fee0fa715ad04410e73530829602736d85f)) + +## 4.5.0 (2023-09-06) + +Full Changelog: [v4.4.0...v4.5.0](https://github.com/openai/openai-node/compare/v4.4.0...v4.5.0) + +### Features + +* **client:** add files.waitForProcessing() method ([#292](https://github.com/openai/openai-node/issues/292)) ([ef59010](https://github.com/openai/openai-node/commit/ef59010cab0c666fa8a437ec6e27800789aa8705)) +* fixes tests where an array has to have unique enum values ([#290](https://github.com/openai/openai-node/issues/290)) ([a10b895](https://github.com/openai/openai-node/commit/a10b8956b3eaae7cdcb90329a8386a41219ca021)) +* make docs more readable by eliminating unnecessary escape sequences ([#287](https://github.com/openai/openai-node/issues/287)) ([a068043](https://github.com/openai/openai-node/commit/a06804314d4815d420c97f6f965c926ea70d56df)) + + +### Bug Fixes + +* **client:** fix TS errors that appear when users Go to Source in VSCode ([#281](https://github.com/openai/openai-node/issues/281)) ([8dc59bc](https://github.com/openai/openai-node/commit/8dc59bcf924cc991747ca475c714d915e04c6012)), closes [#249](https://github.com/openai/openai-node/issues/249) +* **client:** handle case where the client is instantiated with a undefined baseURL ([#285](https://github.com/openai/openai-node/issues/285)) ([5095cf3](https://github.com/openai/openai-node/commit/5095cf340743e4627b4f0ad2f055ebe332824d23)) +* **client:** use explicit file extensions in _shims imports ([#276](https://github.com/openai/openai-node/issues/276)) ([16fe929](https://github.com/openai/openai-node/commit/16fe929688d35c2ebe52c8cf1c1570bafda5f97e)) + + +### Documentation + +* **api:** update docstrings ([#286](https://github.com/openai/openai-node/issues/286)) ([664e953](https://github.com/openai/openai-node/commit/664e9532c8acfbf981e9a788ab40c111ebe2fda0)) +* **readme:** add link to api.md ([#291](https://github.com/openai/openai-node/issues/291)) ([0d1cce2](https://github.com/openai/openai-node/commit/0d1cce26cdc6567c10c8d72bbc72a788ffb8f2be)) + +## 4.4.0 (2023-09-01) + +Full Changelog: [v4.3.1...v4.4.0](https://github.com/openai/openai-node/compare/v4.3.1...v4.4.0) + +### Features + +* **package:** add Bun export map ([#269](https://github.com/openai/openai-node/issues/269)) ([16f239c](https://github.com/openai/openai-node/commit/16f239c6b4e8526371b01c511d2e0ebba4c5c8c6)) +* re-export chat completion types at the top level ([#268](https://github.com/openai/openai-node/issues/268)) ([1a71a39](https://github.com/openai/openai-node/commit/1a71a39421828fdde7b8605094363a5047d2fdc9)) +* **tests:** unskip multipart form data tests ([#275](https://github.com/openai/openai-node/issues/275)) ([47d3e18](https://github.com/openai/openai-node/commit/47d3e18a3ee987d04b958dad1a51821ad5472d54)) +* **types:** fix ambiguous auto-import for chat completions params ([#266](https://github.com/openai/openai-node/issues/266)) ([19c99fb](https://github.com/openai/openai-node/commit/19c99fb268d6d6c7fc7aaa66475c35f45d12b4bd)) + + +### Bug Fixes + +* revert import change which triggered circular import bug in webpack ([#274](https://github.com/openai/openai-node/issues/274)) ([6534e36](https://github.com/openai/openai-node/commit/6534e3620d7e2983e98b42cf95fa966deab1ab1d)) + +## 4.3.1 (2023-08-29) + +Full Changelog: [v4.3.0...v4.3.1](https://github.com/openai/openai-node/compare/v4.3.0...v4.3.1) + +### Bug Fixes + +* **types:** improve getNextPage() return type ([#262](https://github.com/openai/openai-node/issues/262)) ([245a984](https://github.com/openai/openai-node/commit/245a9847d1ba5bbe5262bc06b2f7bb7385cd3a9a)) + + +### Chores + +* **ci:** setup workflows to create releases and release PRs ([#259](https://github.com/openai/openai-node/issues/259)) ([290908c](https://github.com/openai/openai-node/commit/290908ce24dc6c31df18b2eb7808d5b495387454)) + +## [4.3.0](https://github.com/openai/openai-node/compare/v4.2.0...v4.3.0) (2023-08-27) + + +### Features + +* **client:** add auto-pagination to fine tuning list endpoints ([#254](https://github.com/openai/openai-node/issues/254)) ([5f89c5e](https://github.com/openai/openai-node/commit/5f89c5e6b9088cc2e86405a32b60cae91c078ce1)) +* **cli:** rewrite in JS for better compatibility ([#244](https://github.com/openai/openai-node/issues/244)) ([d8d7c05](https://github.com/openai/openai-node/commit/d8d7c0592bfad89669cd2f174e6207370cd7d3fb)) + + +### Bug Fixes + +* **stream:** declare Stream.controller as public ([#252](https://github.com/openai/openai-node/issues/252)) ([81e5de7](https://github.com/openai/openai-node/commit/81e5de7ba94c992cafa3d08e2697c8122382497a)) + + +### Documentation + +* **readme:** mention Azure support ([#253](https://github.com/openai/openai-node/issues/253)) ([294727a](https://github.com/openai/openai-node/commit/294727ad3543d91ef59df285ce1616c442d369db)) + + +### Chores + +* **internal:** add helper method ([#255](https://github.com/openai/openai-node/issues/255)) ([6d8cff0](https://github.com/openai/openai-node/commit/6d8cff00164c0f65ed40b941486f2e0d752feb1e)) + +## [4.2.0](https://github.com/openai/openai-node/compare/v4.1.0...v4.2.0) (2023-08-23) + + +### Features + +* **types:** export RequestOptions type ([#240](https://github.com/openai/openai-node/issues/240)) ([ecf3bce](https://github.com/openai/openai-node/commit/ecf3bcee3c64a80a3cd901aa32d3db78d1364645)) + + +### Chores + +* **internal:** export HeadersInit type shim ([#241](https://github.com/openai/openai-node/issues/241)) ([cf9f672](https://github.com/openai/openai-node/commit/cf9f6729b5b232a37841c33db33b2519b54f19b2)) diff --git a/node_modules/openai/LICENSE b/node_modules/openai/LICENSE new file mode 100644 index 0000000..621a6be --- /dev/null +++ b/node_modules/openai/LICENSE @@ -0,0 +1,201 @@ + 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 2024 OpenAI + + 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/openai/README.md b/node_modules/openai/README.md new file mode 100644 index 0000000..6ea0192 --- /dev/null +++ b/node_modules/openai/README.md @@ -0,0 +1,500 @@ +# OpenAI Node API Library + +[![NPM version](https://img.shields.io/npm/v/openai.svg)](https://npmjs.org/package/openai) + +This library provides convenient access to the OpenAI REST API from TypeScript or JavaScript. + +It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/). + +To learn how to use the OpenAI API, check out our [API Reference](https://platform.openai.com/docs/api-reference) and [Documentation](https://platform.openai.com/docs). + +## Installation + +```sh +npm install --save openai +# or +yarn add openai +``` + +You can import in Deno via: + + + +```ts +import OpenAI from 'https://deno.land/x/openai@v4.26.0/mod.ts'; +``` + + + +## Usage + +The full API of this library can be found in [api.md file](api.md) along with many [code examples](https://github.com/openai/openai-node/tree/master/examples). The code below shows how to get started using the chat completions API. + + +```js +import OpenAI from 'openai'; + +const openai = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted +}); + +async function main() { + const chatCompletion = await openai.chat.completions.create({ + messages: [{ role: 'user', content: 'Say this is a test' }], + model: 'gpt-3.5-turbo', + }); +} + +main(); +``` + +## Streaming Responses + +We provide support for streaming responses using Server Sent Events (SSE). + +```ts +import OpenAI from 'openai'; + +const openai = new OpenAI(); + +async function main() { + const stream = await openai.chat.completions.create({ + model: 'gpt-4', + messages: [{ role: 'user', content: 'Say this is a test' }], + stream: true, + }); + for await (const chunk of stream) { + process.stdout.write(chunk.choices[0]?.delta?.content || ''); + } +} + +main(); +``` + +If you need to cancel a stream, you can `break` from the loop +or call `stream.controller.abort()`. + +### Request & Response types + +This library includes TypeScript definitions for all request params and response fields. You may import and use them like so: + + +```ts +import OpenAI from 'openai'; + +const openai = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted +}); + +async function main() { + const params: OpenAI.Chat.ChatCompletionCreateParams = { + messages: [{ role: 'user', content: 'Say this is a test' }], + model: 'gpt-3.5-turbo', + }; + const chatCompletion: OpenAI.Chat.ChatCompletion = await openai.chat.completions.create(params); +} + +main(); +``` + +Documentation for each method, request param, and response field are available in docstrings and will appear on hover in most modern editors. + +> [!IMPORTANT] +> Previous versions of this SDK used a `Configuration` class. See the [v3 to v4 migration guide](https://github.com/openai/openai-node/discussions/217). + +### Streaming responses + +This library provides several conveniences for streaming chat completions, for example: + +```ts +import OpenAI from 'openai'; + +const openai = new OpenAI(); + +async function main() { + const stream = await openai.beta.chat.completions.stream({ + model: 'gpt-4', + messages: [{ role: 'user', content: 'Say this is a test' }], + stream: true, + }); + + stream.on('content', (delta, snapshot) => { + process.stdout.write(delta); + }); + + // or, equivalently: + for await (const chunk of stream) { + process.stdout.write(chunk.choices[0]?.delta?.content || ''); + } + + const chatCompletion = await stream.finalChatCompletion(); + console.log(chatCompletion); // {id: "…", choices: […], …} +} + +main(); +``` + +Streaming with `openai.beta.chat.completions.stream({…})` exposes +[various helpers for your convenience](helpers.md#events) including event handlers and promises. + +Alternatively, you can use `openai.chat.completions.create({ stream: true, … })` +which only returns an async iterable of the chunks in the stream and thus uses less memory +(it does not build up a final chat completion object for you). + +If you need to cancel a stream, you can `break` from a `for await` loop or call `stream.abort()`. + +### Automated function calls + +We provide the `openai.beta.chat.completions.runTools({…})` +convenience helper for using function tool calls with the `/chat/completions` endpoint +which automatically call the JavaScript functions you provide +and sends their results back to the `/chat/completions` endpoint, +looping as long as the model requests tool calls. + +If you pass a `parse` function, it will automatically parse the `arguments` for you +and returns any parsing errors to the model to attempt auto-recovery. +Otherwise, the args will be passed to the function you provide as a string. + +If you pass `tool_choice: {function: {name: …}}` instead of `auto`, +it returns immediately after calling that function (and only loops to auto-recover parsing errors). + +```ts +import OpenAI from 'openai'; + +const client = new OpenAI(); + +async function main() { + const runner = client.beta.chat.completions + .runTools({ + model: 'gpt-3.5-turbo', + messages: [{ role: 'user', content: 'How is the weather this week?' }], + tools: [ + { + type: 'function', + function: { + function: getCurrentLocation, + parameters: { type: 'object', properties: {} }, + }, + }, + { + type: 'function', + function: { + function: getWeather, + parse: JSON.parse, // or use a validation library like zod for typesafe parsing. + parameters: { + type: 'object', + properties: { + location: { type: 'string' }, + }, + }, + }, + }, + ], + }) + .on('message', (message) => console.log(message)); + + const finalContent = await runner.finalContent(); + console.log(); + console.log('Final content:', finalContent); +} + +async function getCurrentLocation() { + return 'Boston'; // Simulate lookup +} + +async function getWeather(args: { location: string }) { + const { location } = args; + // … do lookup … + return { temperature, precipitation }; +} + +main(); + +// {role: "user", content: "How's the weather this week?"} +// {role: "assistant", tool_calls: [{type: "function", function: {name: "getCurrentLocation", arguments: "{}"}, id: "123"} +// {role: "tool", name: "getCurrentLocation", content: "Boston", tool_call_id: "123"} +// {role: "assistant", tool_calls: [{type: "function", function: {name: "getWeather", arguments: '{"location": "Boston"}'}, id: "1234"}]} +// {role: "tool", name: "getWeather", content: '{"temperature": "50degF", "preciptation": "high"}', tool_call_id: "1234"} +// {role: "assistant", content: "It's looking cold and rainy - you might want to wear a jacket!"} +// +// Final content: "It's looking cold and rainy - you might want to wear a jacket!" +``` + +Like with `.stream()`, we provide a variety of [helpers and events](helpers.md#events). + +Note that `runFunctions` was previously available as well, but has been deprecated in favor of `runTools`. + +Read more about various examples such as with integrating with [zod](helpers.md#integrate-with-zod), +[next.js](helpers.md#integrate-wtih-next-js), and [proxying a stream to the browser](helpers.md#proxy-streaming-to-a-browser). + +## File Uploads + +Request parameters that correspond to file uploads can be passed in many different forms: + +- `File` (or an object with the same structure) +- a `fetch` `Response` (or an object with the same structure) +- an `fs.ReadStream` +- the return value of our `toFile` helper + +```ts +import fs from 'fs'; +import fetch from 'node-fetch'; +import OpenAI, { toFile } from 'openai'; + +const openai = new OpenAI(); + +// If you have access to Node `fs` we recommend using `fs.createReadStream()`: +await openai.files.create({ file: fs.createReadStream('input.jsonl'), purpose: 'fine-tune' }); + +// Or if you have the web `File` API you can pass a `File` instance: +await openai.files.create({ file: new File(['my bytes'], 'input.jsonl'), purpose: 'fine-tune' }); + +// You can also pass a `fetch` `Response`: +await openai.files.create({ file: await fetch('https://somesite/input.jsonl'), purpose: 'fine-tune' }); + +// Finally, if none of the above are convenient, you can use our `toFile` helper: +await openai.files.create({ + file: await toFile(Buffer.from('my bytes'), 'input.jsonl'), + purpose: 'fine-tune', +}); +await openai.files.create({ + file: await toFile(new Uint8Array([0, 1, 2]), 'input.jsonl'), + purpose: 'fine-tune', +}); +``` + +## Handling errors + +When the library is unable to connect to the API, +or if the API returns a non-success status code (i.e., 4xx or 5xx response), +a subclass of `APIError` will be thrown: + + +```ts +async function main() { + const job = await openai.fineTuning.jobs + .create({ model: 'gpt-3.5-turbo', training_file: 'file-abc123' }) + .catch((err) => { + if (err instanceof OpenAI.APIError) { + console.log(err.status); // 400 + console.log(err.name); // BadRequestError + console.log(err.headers); // {server: 'nginx', ...} + } else { + throw err; + } + }); +} + +main(); +``` + +Error codes are as followed: + +| Status Code | Error Type | +| ----------- | -------------------------- | +| 400 | `BadRequestError` | +| 401 | `AuthenticationError` | +| 403 | `PermissionDeniedError` | +| 404 | `NotFoundError` | +| 422 | `UnprocessableEntityError` | +| 429 | `RateLimitError` | +| >=500 | `InternalServerError` | +| N/A | `APIConnectionError` | + +### Azure OpenAI + +An example of using this library with Azure OpenAI can be found [here](https://github.com/openai/openai-node/blob/master/examples/azure.ts). + +Please note there are subtle differences in API shape & behavior between the Azure OpenAI API and the OpenAI API, +so using this library with Azure OpenAI may result in incorrect types, which can lead to bugs. + +See [`@azure/openai`](https://www.npmjs.com/package/@azure/openai) for an Azure-specific SDK provided by Microsoft. + +### Retries + +Certain errors will be automatically retried 2 times by default, with a short exponential backoff. +Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, +429 Rate Limit, and >=500 Internal errors will all be retried by default. + +You can use the `maxRetries` option to configure or disable this: + + +```js +// Configure the default for all requests: +const openai = new OpenAI({ + maxRetries: 0, // default is 2 +}); + +// Or, configure per-request: +await openai.chat.completions.create({ messages: [{ role: 'user', content: 'How can I get the name of the current day in Node.js?' }], model: 'gpt-3.5-turbo' }, { + maxRetries: 5, +}); +``` + +### Timeouts + +Requests time out after 10 minutes by default. You can configure this with a `timeout` option: + + +```ts +// Configure the default for all requests: +const openai = new OpenAI({ + timeout: 20 * 1000, // 20 seconds (default is 10 minutes) +}); + +// Override per-request: +await openai.chat.completions.create({ messages: [{ role: 'user', content: 'How can I list all files in a directory using Python?' }], model: 'gpt-3.5-turbo' }, { + timeout: 5 * 1000, +}); +``` + +On timeout, an `APIConnectionTimeoutError` is thrown. + +Note that requests which time out will be [retried twice by default](#retries). + +## Auto-pagination + +List methods in the OpenAI API are paginated. +You can use `for await … of` syntax to iterate through items across all pages: + +```ts +async function fetchAllFineTuningJobs(params) { + const allFineTuningJobs = []; + // Automatically fetches more pages as needed. + for await (const fineTuningJob of openai.fineTuning.jobs.list({ limit: 20 })) { + allFineTuningJobs.push(fineTuningJob); + } + return allFineTuningJobs; +} +``` + +Alternatively, you can make request a single page at a time: + +```ts +let page = await openai.fineTuning.jobs.list({ limit: 20 }); +for (const fineTuningJob of page.data) { + console.log(fineTuningJob); +} + +// Convenience methods are provided for manually paginating: +while (page.hasNextPage()) { + page = page.getNextPage(); + // ... +} +``` + +## Advanced Usage + +### Accessing raw Response data (e.g., headers) + +The "raw" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return. + +You can also use the `.withResponse()` method to get the raw `Response` along with the parsed data. + + +```ts +const openai = new OpenAI(); + +const response = await openai.chat.completions + .create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-3.5-turbo' }) + .asResponse(); +console.log(response.headers.get('X-My-Header')); +console.log(response.statusText); // access the underlying Response object + +const { data: chatCompletion, response: raw } = await openai.chat.completions + .create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-3.5-turbo' }) + .withResponse(); +console.log(raw.headers.get('X-My-Header')); +console.log(chatCompletion); +``` + +## Customizing the fetch client + +By default, this library uses `node-fetch` in Node, and expects a global `fetch` function in other environments. + +If you would prefer to use a global, web-standards-compliant `fetch` function even in a Node environment, +(for example, if you are running Node with `--experimental-fetch` or using NextJS which polyfills with `undici`), +add the following import before your first import `from "OpenAI"`: + +```ts +// Tell TypeScript and the package to use the global web fetch instead of node-fetch. +// Note, despite the name, this does not add any polyfills, but expects them to be provided if needed. +import 'openai/shims/web'; +import OpenAI from 'openai'; +``` + +To do the inverse, add `import "openai/shims/node"` (which does import polyfills). +This can also be useful if you are getting the wrong TypeScript types for `Response` - more details [here](https://github.com/openai/openai-node/tree/master/src/_shims#readme). + +You may also provide a custom `fetch` function when instantiating the client, +which can be used to inspect or alter the `Request` or `Response` before/after each request: + +```ts +import { fetch } from 'undici'; // as one example +import OpenAI from 'openai'; + +const client = new OpenAI({ + fetch: async (url: RequestInfo, init?: RequestInfo): Promise => { + console.log('About to make a request', url, init); + const response = await fetch(url, init); + console.log('Got response', response); + return response; + }, +}); +``` + +Note that if given a `DEBUG=true` environment variable, this library will log all requests and responses automatically. +This is intended for debugging purposes only and may change in the future without notice. + +## Configuring an HTTP(S) Agent (e.g., for proxies) + +By default, this library uses a stable agent for all http/https requests to reuse TCP connections, eliminating many TCP & TLS handshakes and shaving around 100ms off most requests. + +If you would like to disable or customize this behavior, for example to use the API behind a proxy, you can pass an `httpAgent` which is used for all requests (be they http or https), for example: + + +```ts +import http from 'http'; +import HttpsProxyAgent from 'https-proxy-agent'; + +// Configure the default for all requests: +const openai = new OpenAI({ + httpAgent: new HttpsProxyAgent(process.env.PROXY_URL), +}); + +// Override per-request: +await openai.models.list({ + baseURL: 'http://localhost:8080/test-api', + httpAgent: new http.Agent({ keepAlive: false }), +}) +``` + +## Semantic Versioning + +This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions: + +1. Changes that only affect static types, without breaking runtime behavior. +2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals)_. +3. Changes that we do not expect to impact the vast majority of users in practice. + +We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience. + +We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-node/issues) with questions, bugs, or suggestions. + +## Requirements + +TypeScript >= 4.5 is supported. + +The following runtimes are supported: + +- Node.js 18 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions. +- Deno v1.28.0 or higher, using `import OpenAI from "npm:openai"`. +- Bun 1.0 or later. +- Cloudflare Workers. +- Vercel Edge Runtime. +- Jest 28 or greater with the `"node"` environment (`"jsdom"` is not supported at this time). +- Nitro v2.6 or greater. + +Note that React Native is not supported at this time. + +If you are interested in other runtime environments, please open or upvote an issue on GitHub. diff --git a/node_modules/openai/_shims/MultipartBody.d.ts b/node_modules/openai/_shims/MultipartBody.d.ts new file mode 100644 index 0000000..d9118c8 --- /dev/null +++ b/node_modules/openai/_shims/MultipartBody.d.ts @@ -0,0 +1,9 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export declare class MultipartBody { + body: any; + constructor(body: any); + get [Symbol.toStringTag](): string; +} +//# sourceMappingURL=MultipartBody.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/MultipartBody.d.ts.map b/node_modules/openai/_shims/MultipartBody.d.ts.map new file mode 100644 index 0000000..fc6a8b6 --- /dev/null +++ b/node_modules/openai/_shims/MultipartBody.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"MultipartBody.d.ts","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,qBAAa,aAAa;IACL,IAAI,EAAE,GAAG;gBAAT,IAAI,EAAE,GAAG;IAC5B,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,MAAM,CAEjC;CACF"} \ No newline at end of file diff --git a/node_modules/openai/_shims/MultipartBody.js b/node_modules/openai/_shims/MultipartBody.js new file mode 100644 index 0000000..67efb46 --- /dev/null +++ b/node_modules/openai/_shims/MultipartBody.js @@ -0,0 +1,16 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MultipartBody = void 0; +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +class MultipartBody { + constructor(body) { + this.body = body; + } + get [Symbol.toStringTag]() { + return 'MultipartBody'; + } +} +exports.MultipartBody = MultipartBody; +//# sourceMappingURL=MultipartBody.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/MultipartBody.js.map b/node_modules/openai/_shims/MultipartBody.js.map new file mode 100644 index 0000000..adad49f --- /dev/null +++ b/node_modules/openai/_shims/MultipartBody.js.map @@ -0,0 +1 @@ +{"version":3,"file":"MultipartBody.js","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,MAAa,aAAa;IACxB,YAAmB,IAAS;QAAT,SAAI,GAAJ,IAAI,CAAK;IAAG,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AALD,sCAKC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/MultipartBody.mjs b/node_modules/openai/_shims/MultipartBody.mjs new file mode 100644 index 0000000..68a8280 --- /dev/null +++ b/node_modules/openai/_shims/MultipartBody.mjs @@ -0,0 +1,12 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export class MultipartBody { + constructor(body) { + this.body = body; + } + get [Symbol.toStringTag]() { + return 'MultipartBody'; + } +} +//# sourceMappingURL=MultipartBody.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/MultipartBody.mjs.map b/node_modules/openai/_shims/MultipartBody.mjs.map new file mode 100644 index 0000000..6aca413 --- /dev/null +++ b/node_modules/openai/_shims/MultipartBody.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"MultipartBody.mjs","sourceRoot":"","sources":["../src/_shims/MultipartBody.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,OAAO,aAAa;IACxB,YAAmB,IAAS;QAAT,SAAI,GAAJ,IAAI,CAAK;IAAG,CAAC;IAChC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC;QACtB,OAAO,eAAe,CAAC;IACzB,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/openai/_shims/README.md b/node_modules/openai/_shims/README.md new file mode 100644 index 0000000..b3a349b --- /dev/null +++ b/node_modules/openai/_shims/README.md @@ -0,0 +1,46 @@ +# 👋 Wondering what everything in here does? + +`openai` supports a wide variety of runtime environments like Node.js, Deno, Bun, browsers, and various +edge runtimes, as well as both CommonJS (CJS) and EcmaScript Modules (ESM). + +To do this, `openai` provides shims for either using `node-fetch` when in Node (because `fetch` is still experimental there) or the global `fetch` API built into the environment when not in Node. + +It uses [conditional exports](https://nodejs.org/api/packages.html#conditional-exports) to +automatically select the correct shims for each environment. However, conditional exports are a fairly new +feature and not supported everywhere. For instance, the TypeScript `"moduleResolution": "node"` + +setting doesn't consult the `exports` map, compared to `"moduleResolution": "nodeNext"`, which does. +Unfortunately that's still the default setting, and it can result in errors like +getting the wrong raw `Response` type from `.asResponse()`, for example. + +The user can work around these issues by manually importing one of: + +- `import 'openai/shims/node'` +- `import 'openai/shims/web'` + +All of the code here in `_shims` handles selecting the automatic default shims or manual overrides. + +### How it works - Runtime + +Runtime shims get installed by calling `setShims` exported by `openai/_shims/registry`. + +Manually importing `openai/shims/node` or `openai/shims/web`, calls `setShims` with the respective runtime shims. + +All client code imports shims from `openai/_shims/index`, which: + +- checks if shims have been set manually +- if not, calls `setShims` with the shims from `openai/_shims/auto/runtime` +- re-exports the installed shims from `openai/_shims/registry`. + +`openai/_shims/auto/runtime` exports web runtime shims. +If the `node` export condition is set, the export map replaces it with `openai/_shims/auto/runtime-node`. + +### How it works - Type time + +All client code imports shim types from `openai/_shims/index`, which selects the manual types from `openai/_shims/manual-types` if they have been declared, otherwise it exports the auto types from `openai/_shims/auto/types`. + +`openai/_shims/manual-types` exports an empty namespace. +Manually importing `openai/shims/node` or `openai/shims/web` merges declarations into this empty namespace, so they get picked up by `openai/_shims/index`. + +`openai/_shims/auto/types` exports web type definitions. +If the `node` export condition is set, the export map replaces it with `openai/_shims/auto/types-node`, though TS only picks this up if `"moduleResolution": "nodenext"` or `"moduleResolution": "bundler"`. diff --git a/node_modules/openai/_shims/auto/runtime-bun.d.ts b/node_modules/openai/_shims/auto/runtime-bun.d.ts new file mode 100644 index 0000000..1baecb8 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-bun.d.ts @@ -0,0 +1,5 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from "../bun-runtime.js"; +//# sourceMappingURL=runtime-bun.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-bun.d.ts.map b/node_modules/openai/_shims/auto/runtime-bun.d.ts.map new file mode 100644 index 0000000..8d57eee --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-bun.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-bun.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,gBAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-bun.js b/node_modules/openai/_shims/auto/runtime-bun.js new file mode 100644 index 0000000..312c535 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-bun.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +__exportStar(require("../bun-runtime.js"), exports); +//# sourceMappingURL=runtime-bun.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-bun.js.map b/node_modules/openai/_shims/auto/runtime-bun.js.map new file mode 100644 index 0000000..c78786e --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-bun.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-bun.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,oDAA+B"} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-bun.mjs b/node_modules/openai/_shims/auto/runtime-bun.mjs new file mode 100644 index 0000000..3197fae --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-bun.mjs @@ -0,0 +1,2 @@ +export * from "../bun-runtime.mjs"; +//# sourceMappingURL=runtime-bun.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-bun.mjs.map b/node_modules/openai/_shims/auto/runtime-bun.mjs.map new file mode 100644 index 0000000..32011c5 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-bun.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-bun.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime-bun.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-node.d.ts b/node_modules/openai/_shims/auto/runtime-node.d.ts new file mode 100644 index 0000000..9db3401 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-node.d.ts @@ -0,0 +1,5 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from "../node-runtime.js"; +//# sourceMappingURL=runtime-node.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-node.d.ts.map b/node_modules/openai/_shims/auto/runtime-node.d.ts.map new file mode 100644 index 0000000..63a03d6 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-node.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,iBAAiB,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-node.js b/node_modules/openai/_shims/auto/runtime-node.js new file mode 100644 index 0000000..318ae7c --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-node.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +__exportStar(require("../node-runtime.js"), exports); +//# sourceMappingURL=runtime-node.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-node.js.map b/node_modules/openai/_shims/auto/runtime-node.js.map new file mode 100644 index 0000000..4d43fab --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-node.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-node.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,qDAAgC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-node.mjs b/node_modules/openai/_shims/auto/runtime-node.mjs new file mode 100644 index 0000000..f846bd3 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-node.mjs @@ -0,0 +1,2 @@ +export * from "../node-runtime.mjs"; +//# sourceMappingURL=runtime-node.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime-node.mjs.map b/node_modules/openai/_shims/auto/runtime-node.mjs.map new file mode 100644 index 0000000..aa25d93 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime-node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime-node.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime-node.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime.d.ts b/node_modules/openai/_shims/auto/runtime.d.ts new file mode 100644 index 0000000..ad73696 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime.d.ts @@ -0,0 +1,5 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from "../web-runtime.js"; +//# sourceMappingURL=runtime.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime.d.ts.map b/node_modules/openai/_shims/auto/runtime.d.ts.map new file mode 100644 index 0000000..256985a --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,gBAAgB,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime.js b/node_modules/openai/_shims/auto/runtime.js new file mode 100644 index 0000000..2559391 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +__exportStar(require("../web-runtime.js"), exports); +//# sourceMappingURL=runtime.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime.js.map b/node_modules/openai/_shims/auto/runtime.js.map new file mode 100644 index 0000000..3cbe401 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,oDAA+B"} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime.mjs b/node_modules/openai/_shims/auto/runtime.mjs new file mode 100644 index 0000000..c16bf9e --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime.mjs @@ -0,0 +1,2 @@ +export * from "../web-runtime.mjs"; +//# sourceMappingURL=runtime.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/runtime.mjs.map b/node_modules/openai/_shims/auto/runtime.mjs.map new file mode 100644 index 0000000..5a61fc6 --- /dev/null +++ b/node_modules/openai/_shims/auto/runtime.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"runtime.mjs","sourceRoot":"","sources":["../../src/_shims/auto/runtime.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/types-node.d.ts b/node_modules/openai/_shims/auto/types-node.d.ts new file mode 100644 index 0000000..66e5296 --- /dev/null +++ b/node_modules/openai/_shims/auto/types-node.d.ts @@ -0,0 +1,5 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export * from "../node-types.js"; +//# sourceMappingURL=types-node.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/types-node.d.ts.map b/node_modules/openai/_shims/auto/types-node.d.ts.map new file mode 100644 index 0000000..bc0e15d --- /dev/null +++ b/node_modules/openai/_shims/auto/types-node.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types-node.d.ts","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,cAAc,eAAe,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/types-node.js b/node_modules/openai/_shims/auto/types-node.js new file mode 100644 index 0000000..b7577b3 --- /dev/null +++ b/node_modules/openai/_shims/auto/types-node.js @@ -0,0 +1,21 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __exportStar = (this && this.__exportStar) || function(m, exports) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +__exportStar(require("../node-types.js"), exports); +//# sourceMappingURL=types-node.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/types-node.js.map b/node_modules/openai/_shims/auto/types-node.js.map new file mode 100644 index 0000000..553fe3e --- /dev/null +++ b/node_modules/openai/_shims/auto/types-node.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types-node.js","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA;;GAEG;AACH,mDAA8B"} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/types-node.mjs b/node_modules/openai/_shims/auto/types-node.mjs new file mode 100644 index 0000000..10c37f2 --- /dev/null +++ b/node_modules/openai/_shims/auto/types-node.mjs @@ -0,0 +1,2 @@ +export * from "../node-types.mjs"; +//# sourceMappingURL=types-node.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/types-node.mjs.map b/node_modules/openai/_shims/auto/types-node.mjs.map new file mode 100644 index 0000000..27e85a2 --- /dev/null +++ b/node_modules/openai/_shims/auto/types-node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"types-node.mjs","sourceRoot":"","sources":["../../src/_shims/auto/types-node.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/openai/_shims/auto/types.d.ts b/node_modules/openai/_shims/auto/types.d.ts new file mode 100644 index 0000000..d775507 --- /dev/null +++ b/node_modules/openai/_shims/auto/types.d.ts @@ -0,0 +1,101 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export type Agent = any; + +// @ts-ignore +declare const _fetch: unknown extends typeof fetch ? never : typeof fetch; +export { _fetch as fetch }; + +// @ts-ignore +type _Request = unknown extends Request ? never : Request; +export { _Request as Request }; + +// @ts-ignore +type _RequestInfo = unknown extends RequestInfo ? never : RequestInfo; +export { type _RequestInfo as RequestInfo }; + +// @ts-ignore +type _RequestInit = unknown extends RequestInit ? never : RequestInit; +export { type _RequestInit as RequestInit }; + +// @ts-ignore +type _Response = unknown extends Response ? never : Response; +export { _Response as Response }; + +// @ts-ignore +type _ResponseInit = unknown extends ResponseInit ? never : ResponseInit; +export { type _ResponseInit as ResponseInit }; + +// @ts-ignore +type _ResponseType = unknown extends ResponseType ? never : ResponseType; +export { type _ResponseType as ResponseType }; + +// @ts-ignore +type _BodyInit = unknown extends BodyInit ? never : BodyInit; +export { type _BodyInit as BodyInit }; + +// @ts-ignore +type _Headers = unknown extends Headers ? never : Headers; +export { _Headers as Headers }; + +// @ts-ignore +type _HeadersInit = unknown extends HeadersInit ? never : HeadersInit; +export { type _HeadersInit as HeadersInit }; + +type EndingType = 'native' | 'transparent'; + +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +// @ts-ignore +type _FormData = unknown extends FormData ? never : FormData; +// @ts-ignore +declare const _FormData: unknown extends typeof FormData ? never : typeof FormData; +export { _FormData as FormData }; + +// @ts-ignore +type _File = unknown extends File ? never : File; +// @ts-ignore +declare const _File: unknown extends typeof File ? never : typeof File; +export { _File as File }; + +// @ts-ignore +type _Blob = unknown extends Blob ? never : Blob; +// @ts-ignore +declare const _Blob: unknown extends typeof Blob ? never : typeof Blob; +export { _Blob as Blob }; + +export declare class Readable { + readable: boolean; + readonly readableEnded: boolean; + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + readonly readableObjectMode: boolean; + destroyed: boolean; + read(size?: number): any; + pause(): this; + resume(): this; + isPaused(): boolean; + destroy(error?: Error): this; + [Symbol.asyncIterator](): AsyncIterableIterator; +} + +export declare class FsReadStream extends Readable { + path: {}; // node type is string | Buffer +} + +// @ts-ignore +type _ReadableStream = unknown extends ReadableStream ? never : ReadableStream; +// @ts-ignore +declare const _ReadableStream: unknown extends typeof ReadableStream ? never : typeof ReadableStream; +export { _ReadableStream as ReadableStream }; diff --git a/node_modules/openai/_shims/auto/types.js b/node_modules/openai/_shims/auto/types.js new file mode 100644 index 0000000..ddbdb79 --- /dev/null +++ b/node_modules/openai/_shims/auto/types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/node_modules/openai/_shims/auto/types.mjs b/node_modules/openai/_shims/auto/types.mjs new file mode 100644 index 0000000..ddbdb79 --- /dev/null +++ b/node_modules/openai/_shims/auto/types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/node_modules/openai/_shims/bun-runtime.d.ts b/node_modules/openai/_shims/bun-runtime.d.ts new file mode 100644 index 0000000..7228102 --- /dev/null +++ b/node_modules/openai/_shims/bun-runtime.d.ts @@ -0,0 +1,6 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { type Shims } from "./registry.js"; +export declare function getRuntime(): Shims; +//# sourceMappingURL=bun-runtime.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/bun-runtime.d.ts.map b/node_modules/openai/_shims/bun-runtime.d.ts.map new file mode 100644 index 0000000..9de8c65 --- /dev/null +++ b/node_modules/openai/_shims/bun-runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bun-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAIxC,wBAAgB,UAAU,IAAI,KAAK,CAMlC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/bun-runtime.js b/node_modules/openai/_shims/bun-runtime.js new file mode 100644 index 0000000..e098e16 --- /dev/null +++ b/node_modules/openai/_shims/bun-runtime.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntime = void 0; +const web_runtime_1 = require("./web-runtime.js"); +const node_fs_1 = require("node:fs"); +function getRuntime() { + const runtime = (0, web_runtime_1.getRuntime)(); + function isFsReadStream(value) { + return value instanceof node_fs_1.ReadStream; + } + return { ...runtime, isFsReadStream }; +} +exports.getRuntime = getRuntime; +//# sourceMappingURL=bun-runtime.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/bun-runtime.js.map b/node_modules/openai/_shims/bun-runtime.js.map new file mode 100644 index 0000000..fdea462 --- /dev/null +++ b/node_modules/openai/_shims/bun-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bun-runtime.js","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":";;;AAIA,kDAA4D;AAC5D,qCAAqD;AAErD,SAAgB,UAAU;IACxB,MAAM,OAAO,GAAG,IAAA,wBAAa,GAAE,CAAC;IAChC,SAAS,cAAc,CAAC,KAAU;QAChC,OAAO,KAAK,YAAY,oBAAY,CAAC;IACvC,CAAC;IACD,OAAO,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,CAAC;AACxC,CAAC;AAND,gCAMC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/bun-runtime.mjs b/node_modules/openai/_shims/bun-runtime.mjs new file mode 100644 index 0000000..8f52de8 --- /dev/null +++ b/node_modules/openai/_shims/bun-runtime.mjs @@ -0,0 +1,10 @@ +import { getRuntime as getWebRuntime } from "./web-runtime.mjs"; +import { ReadStream as FsReadStream } from 'node:fs'; +export function getRuntime() { + const runtime = getWebRuntime(); + function isFsReadStream(value) { + return value instanceof FsReadStream; + } + return { ...runtime, isFsReadStream }; +} +//# sourceMappingURL=bun-runtime.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/bun-runtime.mjs.map b/node_modules/openai/_shims/bun-runtime.mjs.map new file mode 100644 index 0000000..4a1b11d --- /dev/null +++ b/node_modules/openai/_shims/bun-runtime.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bun-runtime.mjs","sourceRoot":"","sources":["../src/_shims/bun-runtime.ts"],"names":[],"mappings":"OAIO,EAAE,UAAU,IAAI,aAAa,EAAE;OAC/B,EAAE,UAAU,IAAI,YAAY,EAAE,MAAM,SAAS;AAEpD,MAAM,UAAU,UAAU;IACxB,MAAM,OAAO,GAAG,aAAa,EAAE,CAAC;IAChC,SAAS,cAAc,CAAC,KAAU;QAChC,OAAO,KAAK,YAAY,YAAY,CAAC;IACvC,CAAC;IACD,OAAO,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/index.d.ts b/node_modules/openai/_shims/index.d.ts new file mode 100644 index 0000000..7ff9513 --- /dev/null +++ b/node_modules/openai/_shims/index.d.ts @@ -0,0 +1,81 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { manual } from "./manual-types.js"; +import * as auto from 'openai/_shims/auto/types'; +import { type RequestOptions } from "../core.js"; + +type SelectType = unknown extends Manual ? Auto : Manual; + +export const kind: string; + +// @ts-ignore +export type Agent = SelectType; + +// @ts-ignore +export const fetch: SelectType; + +// @ts-ignore +export type Request = SelectType; +// @ts-ignore +export type RequestInfo = SelectType; +// @ts-ignore +export type RequestInit = SelectType; + +// @ts-ignore +export type Response = SelectType; +// @ts-ignore +export type ResponseInit = SelectType; +// @ts-ignore +export type ResponseType = SelectType; +// @ts-ignore +export type BodyInit = SelectType; +// @ts-ignore +export type Headers = SelectType; +// @ts-ignore +export const Headers: SelectType; +// @ts-ignore +export type HeadersInit = SelectType; + +// @ts-ignore +export type BlobPropertyBag = SelectType; +// @ts-ignore +export type FilePropertyBag = SelectType; +// @ts-ignore +export type FileFromPathOptions = SelectType; +// @ts-ignore +export type FormData = SelectType; +// @ts-ignore +export const FormData: SelectType; +// @ts-ignore +export type File = SelectType; +// @ts-ignore +export const File: SelectType; +// @ts-ignore +export type Blob = SelectType; +// @ts-ignore +export const Blob: SelectType; + +// @ts-ignore +export type Readable = SelectType; +// @ts-ignore +export type FsReadStream = SelectType; +// @ts-ignore +export type ReadableStream = SelectType; +// @ts-ignore +export const ReadableStream: SelectType; + +export function getMultipartRequestOptions>( + form: FormData, + opts: RequestOptions, +): Promise>; + +export function getDefaultAgent(url: string): any; + +// @ts-ignore +export type FileFromPathOptions = SelectType; + +export function fileFromPath(path: string, options?: FileFromPathOptions): Promise; +export function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise; + +export function isFsReadStream(value: any): value is FsReadStream; diff --git a/node_modules/openai/_shims/index.js b/node_modules/openai/_shims/index.js new file mode 100644 index 0000000..b5fc822 --- /dev/null +++ b/node_modules/openai/_shims/index.js @@ -0,0 +1,13 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +const shims = require('./registry'); +const auto = require('openai/_shims/auto/runtime'); +if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true }); +for (const property of Object.keys(shims)) { + Object.defineProperty(exports, property, { + get() { + return shims[property]; + }, + }); +} diff --git a/node_modules/openai/_shims/index.mjs b/node_modules/openai/_shims/index.mjs new file mode 100644 index 0000000..81665e6 --- /dev/null +++ b/node_modules/openai/_shims/index.mjs @@ -0,0 +1,7 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import * as shims from './registry.mjs'; +import * as auto from 'openai/_shims/auto/runtime'; +if (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true }); +export * from './registry.mjs'; diff --git a/node_modules/openai/_shims/manual-types.d.ts b/node_modules/openai/_shims/manual-types.d.ts new file mode 100644 index 0000000..3d00fc2 --- /dev/null +++ b/node_modules/openai/_shims/manual-types.d.ts @@ -0,0 +1,12 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +/** + * Types will get added to this namespace when you import one of the following: + * + * import 'openai/shims/node' + * import 'openai/shims/web' + * + * Importing more than one will cause type and runtime errors. + */ +export namespace manual {} diff --git a/node_modules/openai/_shims/manual-types.js b/node_modules/openai/_shims/manual-types.js new file mode 100644 index 0000000..ddbdb79 --- /dev/null +++ b/node_modules/openai/_shims/manual-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/node_modules/openai/_shims/manual-types.mjs b/node_modules/openai/_shims/manual-types.mjs new file mode 100644 index 0000000..ddbdb79 --- /dev/null +++ b/node_modules/openai/_shims/manual-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/node_modules/openai/_shims/node-runtime.d.ts b/node_modules/openai/_shims/node-runtime.d.ts new file mode 100644 index 0000000..0c2b042 --- /dev/null +++ b/node_modules/openai/_shims/node-runtime.d.ts @@ -0,0 +1,3 @@ +import { type Shims } from "./registry.js"; +export declare function getRuntime(): Shims; +//# sourceMappingURL=node-runtime.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/node-runtime.d.ts.map b/node_modules/openai/_shims/node-runtime.d.ts.map new file mode 100644 index 0000000..8418455 --- /dev/null +++ b/node_modules/openai/_shims/node-runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"node-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/node-runtime.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AA+CxC,wBAAgB,UAAU,IAAI,KAAK,CAqBlC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/node-runtime.js b/node_modules/openai/_shims/node-runtime.js new file mode 100644 index 0000000..9bd175b --- /dev/null +++ b/node_modules/openai/_shims/node-runtime.js @@ -0,0 +1,90 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntime = void 0; +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +const nf = __importStar(require("node-fetch")); +const fd = __importStar(require("formdata-node")); +const agentkeepalive_1 = __importDefault(require("agentkeepalive")); +const abort_controller_1 = require("abort-controller"); +const node_fs_1 = require("node:fs"); +const form_data_encoder_1 = require("form-data-encoder"); +const node_stream_1 = require("node:stream"); +const MultipartBody_1 = require("./MultipartBody.js"); +// @ts-ignore (this package does not have proper export maps for this export) +const ponyfill_es2018_js_1 = require("web-streams-polyfill/dist/ponyfill.es2018.js"); +let fileFromPathWarned = false; +async function fileFromPath(path, ...args) { + // this import fails in environments that don't handle export maps correctly, like old versions of Jest + const { fileFromPath: _fileFromPath } = await Promise.resolve().then(() => __importStar(require('formdata-node/file-from-path'))); + if (!fileFromPathWarned) { + console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); + fileFromPathWarned = true; + } + // @ts-ignore + return await _fileFromPath(path, ...args); +} +const defaultHttpAgent = new agentkeepalive_1.default({ keepAlive: true, timeout: 5 * 60 * 1000 }); +const defaultHttpsAgent = new agentkeepalive_1.default.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +async function getMultipartRequestOptions(form, opts) { + const encoder = new form_data_encoder_1.FormDataEncoder(form); + const readable = node_stream_1.Readable.from(encoder); + const body = new MultipartBody_1.MultipartBody(readable); + const headers = { + ...opts.headers, + ...encoder.headers, + 'Content-Length': encoder.contentLength, + }; + return { ...opts, body: body, headers }; +} +function getRuntime() { + // Polyfill global object if needed. + if (typeof AbortController === 'undefined') { + // @ts-expect-error (the types are subtly different, but compatible in practice) + globalThis.AbortController = abort_controller_1.AbortController; + } + return { + kind: 'node', + fetch: nf.default, + Request: nf.Request, + Response: nf.Response, + Headers: nf.Headers, + FormData: fd.FormData, + Blob: fd.Blob, + File: fd.File, + ReadableStream: ponyfill_es2018_js_1.ReadableStream, + getMultipartRequestOptions, + getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent), + fileFromPath, + isFsReadStream: (value) => value instanceof node_fs_1.ReadStream, + }; +} +exports.getRuntime = getRuntime; +//# sourceMappingURL=node-runtime.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/node-runtime.js.map b/node_modules/openai/_shims/node-runtime.js.map new file mode 100644 index 0000000..d66bc7e --- /dev/null +++ b/node_modules/openai/_shims/node-runtime.js.map @@ -0,0 +1 @@ +{"version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AAC;IACzC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,CAAC,OAAO;QACf,GAAG,OAAO,CAAC,OAAO;QAClB,gBAAgB,EAAE,OAAO,CAAC,aAAa;KACxC,CAAC;IAEF,OAAO,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,IAAW,EAAE,OAAO,EAAE,CAAC;AACjD,CAAC;AAED,SAAgB,UAAU;IACxB,oCAAoC;IACpC,IAAI,OAAO,eAAe,KAAK,WAAW,EAAE;QAC1C,gFAAgF;QAChF,UAAU,CAAC,eAAe,GAAG,kCAAuB,CAAC;KACtD;IACD,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,EAAE,CAAC,OAAO;QACjB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,cAAc,EAAd,mCAAc;QACd,0BAA0B;QAC1B,eAAe,EAAE,CAAC,GAAW,EAAS,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,gBAAgB,CAAC;QACzG,YAAY;QACZ,cAAc,EAAE,CAAC,KAAU,EAAyB,EAAE,CAAC,KAAK,YAAY,oBAAY;KACrF,CAAC;AACJ,CAAC;AArBD,gCAqBC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/node-runtime.mjs b/node_modules/openai/_shims/node-runtime.mjs new file mode 100644 index 0000000..e6635d2 --- /dev/null +++ b/node_modules/openai/_shims/node-runtime.mjs @@ -0,0 +1,56 @@ +import * as nf from 'node-fetch'; +import * as fd from 'formdata-node'; +import KeepAliveAgent from 'agentkeepalive'; +import { AbortController as AbortControllerPolyfill } from 'abort-controller'; +import { ReadStream as FsReadStream } from 'node:fs'; +import { FormDataEncoder } from 'form-data-encoder'; +import { Readable } from 'node:stream'; +import { MultipartBody } from "./MultipartBody.mjs"; +import { ReadableStream } from 'web-streams-polyfill/dist/ponyfill.es2018.js'; +let fileFromPathWarned = false; +async function fileFromPath(path, ...args) { + // this import fails in environments that don't handle export maps correctly, like old versions of Jest + const { fileFromPath: _fileFromPath } = await import('formdata-node/file-from-path'); + if (!fileFromPathWarned) { + console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(path)}) instead`); + fileFromPathWarned = true; + } + // @ts-ignore + return await _fileFromPath(path, ...args); +} +const defaultHttpAgent = new KeepAliveAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +const defaultHttpsAgent = new KeepAliveAgent.HttpsAgent({ keepAlive: true, timeout: 5 * 60 * 1000 }); +async function getMultipartRequestOptions(form, opts) { + const encoder = new FormDataEncoder(form); + const readable = Readable.from(encoder); + const body = new MultipartBody(readable); + const headers = { + ...opts.headers, + ...encoder.headers, + 'Content-Length': encoder.contentLength, + }; + return { ...opts, body: body, headers }; +} +export function getRuntime() { + // Polyfill global object if needed. + if (typeof AbortController === 'undefined') { + // @ts-expect-error (the types are subtly different, but compatible in practice) + globalThis.AbortController = AbortControllerPolyfill; + } + return { + kind: 'node', + fetch: nf.default, + Request: nf.Request, + Response: nf.Response, + Headers: nf.Headers, + FormData: fd.FormData, + Blob: fd.Blob, + File: fd.File, + ReadableStream, + getMultipartRequestOptions, + getDefaultAgent: (url) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent), + fileFromPath, + isFsReadStream: (value) => value instanceof FsReadStream, + }; +} +//# sourceMappingURL=node-runtime.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/node-runtime.mjs.map b/node_modules/openai/_shims/node-runtime.mjs.map new file mode 100644 index 0000000..9cf561b --- /dev/null +++ b/node_modules/openai/_shims/node-runtime.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"node-runtime.mjs","source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AAM,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACxC,MAAM,IAAI,GAAG,IAAI,aAAa,CAAC,QAAQ,CAAC,CAAC;IACzC,MAAM,OAAO,GAAG;QACd,GAAG,IAAI,CAAC,OAAO;QACf,GAAG,OAAO,CAAC,OAAO;QAClB,gBAAgB,EAAE,OAAO,CAAC,aAAa;KACxC,CAAC;IAEF,OAAO,EAAE,GAAG,IAAI,EAAE,IAAI,EAAE,IAAW,EAAE,OAAO,EAAE,CAAC;AACjD,CAAC;AAED,MAAM,UAAU,UAAU;IACxB,oCAAoC;IACpC,IAAI,OAAO,eAAe,KAAK,WAAW,EAAE;QAC1C,gFAAgF;QAChF,UAAU,CAAC,eAAe,GAAG,uBAAuB,CAAC;KACtD;IACD,OAAO;QACL,IAAI,EAAE,MAAM;QACZ,KAAK,EAAE,EAAE,CAAC,OAAO;QACjB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,OAAO,EAAE,EAAE,CAAC,OAAO;QACnB,QAAQ,EAAE,EAAE,CAAC,QAAQ;QACrB,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,IAAI,EAAE,EAAE,CAAC,IAAI;QACb,cAAc;QACd,0BAA0B;QAC1B,eAAe,EAAE,CAAC,GAAW,EAAS,EAAE,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,gBAAgB,CAAC;QACzG,YAAY;QACZ,cAAc,EAAE,CAAC,KAAU,EAAyB,EAAE,CAAC,KAAK,YAAY,YAAY;KACrF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/node-types.d.ts b/node_modules/openai/_shims/node-types.d.ts new file mode 100644 index 0000000..b31698f --- /dev/null +++ b/node_modules/openai/_shims/node-types.d.ts @@ -0,0 +1,42 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import * as nf from 'node-fetch'; +import * as fd from 'formdata-node'; + +export { type Agent } from 'node:http'; +export { type Readable } from 'node:stream'; +export { type ReadStream as FsReadStream } from 'node:fs'; +export { ReadableStream } from 'web-streams-polyfill'; + +export const fetch: typeof nf.default; + +export type Request = nf.Request; +export type RequestInfo = nf.RequestInfo; +export type RequestInit = nf.RequestInit; + +export type Response = nf.Response; +export type ResponseInit = nf.ResponseInit; +export type ResponseType = nf.ResponseType; +export type BodyInit = nf.BodyInit; +export type Headers = nf.Headers; +export type HeadersInit = nf.HeadersInit; + +type EndingType = 'native' | 'transparent'; +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +export type FormData = fd.FormData; +export const FormData: typeof fd.FormData; +export type File = fd.File; +export const File: typeof fd.File; +export type Blob = fd.Blob; +export const Blob: typeof fd.Blob; diff --git a/node_modules/openai/_shims/node-types.js b/node_modules/openai/_shims/node-types.js new file mode 100644 index 0000000..ddbdb79 --- /dev/null +++ b/node_modules/openai/_shims/node-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/node_modules/openai/_shims/node-types.mjs b/node_modules/openai/_shims/node-types.mjs new file mode 100644 index 0000000..ddbdb79 --- /dev/null +++ b/node_modules/openai/_shims/node-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/node_modules/openai/_shims/registry.d.ts b/node_modules/openai/_shims/registry.d.ts new file mode 100644 index 0000000..c041fa2 --- /dev/null +++ b/node_modules/openai/_shims/registry.d.ts @@ -0,0 +1,37 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +import { type RequestOptions } from "../core.js"; +export interface Shims { + kind: string; + fetch: any; + Request: any; + Response: any; + Headers: any; + FormData: any; + Blob: any; + File: any; + ReadableStream: any; + getMultipartRequestOptions: >(form: Shims['FormData'], opts: RequestOptions) => Promise>; + getDefaultAgent: (url: string) => any; + fileFromPath: ((path: string, filename?: string, options?: {}) => Promise) | ((path: string, options?: {}) => Promise); + isFsReadStream: (value: any) => boolean; +} +export declare let auto: boolean; +export declare let kind: Shims['kind'] | undefined; +export declare let fetch: Shims['fetch'] | undefined; +export declare let Request: Shims['Request'] | undefined; +export declare let Response: Shims['Response'] | undefined; +export declare let Headers: Shims['Headers'] | undefined; +export declare let FormData: Shims['FormData'] | undefined; +export declare let Blob: Shims['Blob'] | undefined; +export declare let File: Shims['File'] | undefined; +export declare let ReadableStream: Shims['ReadableStream'] | undefined; +export declare let getMultipartRequestOptions: Shims['getMultipartRequestOptions'] | undefined; +export declare let getDefaultAgent: Shims['getDefaultAgent'] | undefined; +export declare let fileFromPath: Shims['fileFromPath'] | undefined; +export declare let isFsReadStream: Shims['isFsReadStream'] | undefined; +export declare function setShims(shims: Shims, options?: { + auto: boolean; +}): void; +//# sourceMappingURL=registry.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/registry.d.ts.map b/node_modules/openai/_shims/registry.d.ts.map new file mode 100644 index 0000000..036e7d4 --- /dev/null +++ b/node_modules/openai/_shims/registry.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,SAAS,CAAC;AAE9C,MAAM,WAAW,KAAK;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,GAAG,CAAC;IACX,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,GAAG,CAAC;IACd,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,GAAG,CAAC;IACV,IAAI,EAAE,GAAG,CAAC;IACV,cAAc,EAAE,GAAG,CAAC;IACpB,0BAA0B,EA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AAqB,CAAC;AACvD,eAAO,IAAI,cAAc,EAAE,KAAK,CAAC,gBAAgB,CAAC,GAAG,SAAqB,CAAC;AAC3E,eAAO,IAAI,0BAA0B,EAAE,KAAK,CAAC,4BAA4B,CAAC,GAAG,SAAqB,CAAC;AACnG,eAAO,IAAI,eAAe,EAAE,KAAK,CAAC,iBAAiB,CAAC,GAAG,SAAqB,CAAC;AAC7E,eAAO,IAAI,YAAY,EAAE,KAAK,CAAC,cAAc,CAAC,GAAG,SAAqB,CAAC;AACvE,eAAO,IAAI,cAAc,EAAE,KAAK,CAAC,gBAAgB,CAAC,GAAG,SAAqB,CAAC;AAE3E,wBAAgB,QAAQ,CAAC,KAAK,EAAE,KAAK,EAAE,OAAO,GAAE;IAAE,IAAI,EAAE,OAAO,CAAA;CAAoB,QAuBlF"} \ No newline at end of file diff --git a/node_modules/openai/_shims/registry.js b/node_modules/openai/_shims/registry.js new file mode 100644 index 0000000..824fbf6 --- /dev/null +++ b/node_modules/openai/_shims/registry.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setShims = exports.isFsReadStream = exports.fileFromPath = exports.getDefaultAgent = exports.getMultipartRequestOptions = exports.ReadableStream = exports.File = exports.Blob = exports.FormData = exports.Headers = exports.Response = exports.Request = exports.fetch = exports.kind = exports.auto = void 0; +exports.auto = false; +exports.kind = undefined; +exports.fetch = undefined; +exports.Request = undefined; +exports.Response = undefined; +exports.Headers = undefined; +exports.FormData = undefined; +exports.Blob = undefined; +exports.File = undefined; +exports.ReadableStream = undefined; +exports.getMultipartRequestOptions = undefined; +exports.getDefaultAgent = undefined; +exports.fileFromPath = undefined; +exports.isFsReadStream = undefined; +function setShims(shims, options = { auto: false }) { + if (exports.auto) { + throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`); + } + if (exports.kind) { + throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${exports.kind}'\``); + } + exports.auto = options.auto; + exports.kind = shims.kind; + exports.fetch = shims.fetch; + exports.Request = shims.Request; + exports.Response = shims.Response; + exports.Headers = shims.Headers; + exports.FormData = shims.FormData; + exports.Blob = shims.Blob; + exports.File = shims.File; + exports.ReadableStream = shims.ReadableStream; + exports.getMultipartRequestOptions = shims.getMultipartRequestOptions; + exports.getDefaultAgent = shims.getDefaultAgent; + exports.fileFromPath = shims.fileFromPath; + exports.isFsReadStream = shims.isFsReadStream; +} +exports.setShims = setShims; +//# sourceMappingURL=registry.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/registry.js.map b/node_modules/openai/_shims/registry.js.map new file mode 100644 index 0000000..4827a45 --- /dev/null +++ b/node_modules/openai/_shims/registry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":";;;AA0BW,QAAA,IAAI,GAAG,KAAK,CAAC;AACb,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,KAAK,GAA+B,SAAS,CAAC;AAC9C,QAAA,OAAO,GAAiC,SAAS,CAAC;AAClD,QAAA,QAAQ,GAAkC,SAAS,CAAC;AACpD,QAAA,OAAO,GAAiC,SAAS,CAAC;AAClD,QAAA,QAAQ,GAAkC,SAAS,CAAC;AACpD,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,IAAI,GAA8B,SAAS,CAAC;AAC5C,QAAA,cAAc,GAAwC,SAAS,CAAC;AAChE,QAAA,0BAA0B,GAAoD,SAAS,CAAC;AACxF,QAAA,eAAe,GAAyC,SAAS,CAAC;AAClE,QAAA,YAAY,GAAsC,SAAS,CAAC;AAC5D,QAAA,cAAc,GAAwC,SAAS,CAAC;AAE3E,SAAgB,QAAQ,CAAC,KAAY,EAAE,UAA6B,EAAE,IAAI,EAAE,KAAK,EAAE;IACjF,IAAI,YAAI,EAAE;QACR,MAAM,IAAI,KAAK,CACb,mCAAmC,KAAK,CAAC,IAAI,gDAAgD,CAC9F,CAAC;KACH;IACD,IAAI,YAAI,EAAE;QACR,MAAM,IAAI,KAAK,CAAC,gCAAgC,KAAK,CAAC,IAAI,oCAAoC,YAAI,KAAK,CAAC,CAAC;KAC1G;IACD,YAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IACpB,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,aAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IACpB,eAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,gBAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,eAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,gBAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,YAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,sBAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IACtC,kCAA0B,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAC9D,uBAAe,GAAG,KAAK,CAAC,eAAe,CAAC;IACxC,oBAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IAClC,sBAAc,GAAG,KAAK,CAAC,cAAc,CAAC;AACxC,CAAC;AAvBD,4BAuBC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/registry.mjs b/node_modules/openai/_shims/registry.mjs new file mode 100644 index 0000000..c757629 --- /dev/null +++ b/node_modules/openai/_shims/registry.mjs @@ -0,0 +1,37 @@ +export let auto = false; +export let kind = undefined; +export let fetch = undefined; +export let Request = undefined; +export let Response = undefined; +export let Headers = undefined; +export let FormData = undefined; +export let Blob = undefined; +export let File = undefined; +export let ReadableStream = undefined; +export let getMultipartRequestOptions = undefined; +export let getDefaultAgent = undefined; +export let fileFromPath = undefined; +export let isFsReadStream = undefined; +export function setShims(shims, options = { auto: false }) { + if (auto) { + throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`); + } + if (kind) { + throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``); + } + auto = options.auto; + kind = shims.kind; + fetch = shims.fetch; + Request = shims.Request; + Response = shims.Response; + Headers = shims.Headers; + FormData = shims.FormData; + Blob = shims.Blob; + File = shims.File; + ReadableStream = shims.ReadableStream; + getMultipartRequestOptions = shims.getMultipartRequestOptions; + getDefaultAgent = shims.getDefaultAgent; + fileFromPath = shims.fileFromPath; + isFsReadStream = shims.isFsReadStream; +} +//# sourceMappingURL=registry.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/registry.mjs.map b/node_modules/openai/_shims/registry.mjs.map new file mode 100644 index 0000000..92ec20a --- /dev/null +++ b/node_modules/openai/_shims/registry.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"registry.mjs","sourceRoot":"","sources":["../src/_shims/registry.ts"],"names":[],"mappings":"AA0BA,MAAM,CAAC,IAAI,IAAI,GAAG,KAAK,CAAC;AACxB,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,KAAK,GAA+B,SAAS,CAAC;AACzD,MAAM,CAAC,IAAI,OAAO,GAAiC,SAAS,CAAC;AAC7D,MAAM,CAAC,IAAI,QAAQ,GAAkC,SAAS,CAAC;AAC/D,MAAM,CAAC,IAAI,OAAO,GAAiC,SAAS,CAAC;AAC7D,MAAM,CAAC,IAAI,QAAQ,GAAkC,SAAS,CAAC;AAC/D,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,IAAI,GAA8B,SAAS,CAAC;AACvD,MAAM,CAAC,IAAI,cAAc,GAAwC,SAAS,CAAC;AAC3E,MAAM,CAAC,IAAI,0BAA0B,GAAoD,SAAS,CAAC;AACnG,MAAM,CAAC,IAAI,eAAe,GAAyC,SAAS,CAAC;AAC7E,MAAM,CAAC,IAAI,YAAY,GAAsC,SAAS,CAAC;AACvE,MAAM,CAAC,IAAI,cAAc,GAAwC,SAAS,CAAC;AAE3E,MAAM,UAAU,QAAQ,CAAC,KAAY,EAAE,UAA6B,EAAE,IAAI,EAAE,KAAK,EAAE;IACjF,IAAI,IAAI,EAAE;QACR,MAAM,IAAI,KAAK,CACb,mCAAmC,KAAK,CAAC,IAAI,gDAAgD,CAC9F,CAAC;KACH;IACD,IAAI,IAAI,EAAE;QACR,MAAM,IAAI,KAAK,CAAC,gCAAgC,KAAK,CAAC,IAAI,oCAAoC,IAAI,KAAK,CAAC,CAAC;KAC1G;IACD,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;IACpB,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IACpB,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC;IACxB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;IAC1B,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IAClB,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IACtC,0BAA0B,GAAG,KAAK,CAAC,0BAA0B,CAAC;IAC9D,eAAe,GAAG,KAAK,CAAC,eAAe,CAAC;IACxC,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC;IAClC,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;AACxC,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/web-runtime.d.ts b/node_modules/openai/_shims/web-runtime.d.ts new file mode 100644 index 0000000..4ae8077 --- /dev/null +++ b/node_modules/openai/_shims/web-runtime.d.ts @@ -0,0 +1,5 @@ +import { type Shims } from "./registry.js"; +export declare function getRuntime({ manuallyImported }?: { + manuallyImported?: boolean; +}): Shims; +//# sourceMappingURL=web-runtime.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/_shims/web-runtime.d.ts.map b/node_modules/openai/_shims/web-runtime.d.ts.map new file mode 100644 index 0000000..c6a1874 --- /dev/null +++ b/node_modules/openai/_shims/web-runtime.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"web-runtime.d.ts","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,YAAY,CAAC;AAExC,wBAAgB,UAAU,CAAC,EAAE,gBAAgB,EAAE,GAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,KAAK,CA+F3F"} \ No newline at end of file diff --git a/node_modules/openai/_shims/web-runtime.js b/node_modules/openai/_shims/web-runtime.js new file mode 100644 index 0000000..f2f3732 --- /dev/null +++ b/node_modules/openai/_shims/web-runtime.js @@ -0,0 +1,78 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRuntime = void 0; +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +const MultipartBody_1 = require("./MultipartBody.js"); +function getRuntime({ manuallyImported } = {}) { + const recommendation = manuallyImported ? + `You may need to use polyfills` + : `Add one of these imports before your first \`import … from 'openai'\`: +- \`import 'openai/shims/node'\` (if you're running on Node) +- \`import 'openai/shims/web'\` (otherwise) +`; + let _fetch, _Request, _Response, _Headers; + try { + // @ts-ignore + _fetch = fetch; + // @ts-ignore + _Request = Request; + // @ts-ignore + _Response = Response; + // @ts-ignore + _Headers = Headers; + } + catch (error) { + throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`); + } + return { + kind: 'web', + fetch: _fetch, + Request: _Request, + Response: _Response, + Headers: _Headers, + FormData: + // @ts-ignore + typeof FormData !== 'undefined' ? FormData : (class FormData { + // @ts-ignore + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`); + } + }), + Blob: typeof Blob !== 'undefined' ? Blob : (class Blob { + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`); + } + }), + File: + // @ts-ignore + typeof File !== 'undefined' ? File : (class File { + // @ts-ignore + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`); + } + }), + ReadableStream: + // @ts-ignore + typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream { + // @ts-ignore + constructor() { + throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`); + } + }), + getMultipartRequestOptions: async ( + // @ts-ignore + form, opts) => ({ + ...opts, + body: new MultipartBody_1.MultipartBody(form), + }), + getDefaultAgent: (url) => undefined, + fileFromPath: () => { + throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads'); + }, + isFsReadStream: (value) => false, + }; +} +exports.getRuntime = getRuntime; +//# sourceMappingURL=web-runtime.js.map \ No newline at end of file diff --git a/node_modules/openai/_shims/web-runtime.js.map b/node_modules/openai/_shims/web-runtime.js.map new file mode 100644 index 0000000..4aeb05f --- /dev/null +++ b/node_modules/openai/_shims/web-runtime.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web-runtime.js","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACH,sDAAgD;AAIhD,SAAgB,UAAU,CAAC,EAAE,gBAAgB,KAAqC,EAAE;IAClF,MAAM,cAAc,GAClB,gBAAgB,CAAC,CAAC;QAChB,+BAA+B;QACjC,CAAC,CAAC;;;CAGL,CAAC;IAEA,IAAI,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC;IAC1C,IAAI;QACF,aAAa;QACb,MAAM,GAAG,KAAK,CAAC;QACf,aAAa;QACb,QAAQ,GAAG,OAAO,CAAC;QACnB,aAAa;QACb,SAAS,GAAG,QAAQ,CAAC;QACrB,aAAa;QACb,QAAQ,GAAG,OAAO,CAAC;KACpB;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CACb,iEACG,KAAa,CAAC,OACjB,K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,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,gJAAgJ,CACjJ,CAAC;QACJ,CAAC;QACD,cAAc,EAAE,CAAC,KAAU,EAAE,EAAE,CAAC,KAAK;KACtC,CAAC;AACJ,CAAC;AA/FD,gCA+FC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/web-runtime.mjs b/node_modules/openai/_shims/web-runtime.mjs new file mode 100644 index 0000000..691d508 --- /dev/null +++ b/node_modules/openai/_shims/web-runtime.mjs @@ -0,0 +1,71 @@ +import { MultipartBody } from "./MultipartBody.mjs"; +export function getRuntime({ manuallyImported } = {}) { + const recommendation = manuallyImported ? + `You may need to use polyfills` + : `Add one of these imports before your first \`import … from 'openai'\`: +- \`import 'openai/shims/node'\` (if you're running on Node) +- \`import 'openai/shims/web'\` (otherwise) +`; + let _fetch, _Request, _Response, _Headers; + try { + // @ts-ignore + _fetch = fetch; + // @ts-ignore + _Request = Request; + // @ts-ignore + _Response = Response; + // @ts-ignore + _Headers = Headers; + } + catch (error) { + throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`); + } + return { + kind: 'web', + fetch: _fetch, + Request: _Request, + Response: _Response, + Headers: _Headers, + FormData: + // @ts-ignore + typeof FormData !== 'undefined' ? FormData : (class FormData { + // @ts-ignore + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`); + } + }), + Blob: typeof Blob !== 'undefined' ? Blob : (class Blob { + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`); + } + }), + File: + // @ts-ignore + typeof File !== 'undefined' ? File : (class File { + // @ts-ignore + constructor() { + throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`); + } + }), + ReadableStream: + // @ts-ignore + typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream { + // @ts-ignore + constructor() { + throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`); + } + }), + getMultipartRequestOptions: async ( + // @ts-ignore + form, opts) => ({ + ...opts, + body: new MultipartBody(form), + }), + getDefaultAgent: (url) => undefined, + fileFromPath: () => { + throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads'); + }, + isFsReadStream: (value) => false, + }; +} +//# sourceMappingURL=web-runtime.mjs.map \ No newline at end of file diff --git a/node_modules/openai/_shims/web-runtime.mjs.map b/node_modules/openai/_shims/web-runtime.mjs.map new file mode 100644 index 0000000..921ce6b --- /dev/null +++ b/node_modules/openai/_shims/web-runtime.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"web-runtime.mjs","sourceRoot":"","sources":["../src/_shims/web-runtime.ts"],"names":[],"mappings":"OAGO,EAAE,aAAa,EAAE;AAIxB,MAAM,UAAU,UAAU,CAAC,EAAE,gBAAgB,KAAqC,EAAE;IAClF,MAAM,cAAc,GAClB,gBAAgB,CAAC,CAAC;QAChB,+BAA+B;QACjC,CAAC,CAAC;;;CAGL,CAAC;IAEA,IAAI,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC;IAC1C,IAAI;QACF,aAAa;QACb,MAAM,GAAG,KAAK,CAAC;QACf,aAAa;QACb,QAAQ,GAAG,OAAO,CAAC;QACnB,aAAa;QACb,SAAS,GAAG,QAAQ,CAAC;QACrB,aAAa;QACb,QAAQ,GAAG,OAAO,CAAC;KACpB;IAAC,OAAO,KAAK,EAAE;QACd,MAAM,IAAI,KAAK,CACb,iEACG,KAAa,CAAC,OACjB,KAAK,cAAc,EAAE,CACtB,CAAC;KACH;IAED,OAAO;QACL,IAAI,EAAE,KAAK;QACX,KAAK,EAAE,MAAM;QACb,OAAO,EAAE,QAAQ;QACjB,QAAQ,EAAE,SAAS;QACnB,OAAO,EAAE,QAAQ;QACjB,QAAQ;QACN,aAAa;QACb,OAAO,QAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAC3C,MAAM,QAAQ;YACZ,aAAa;YACb;gBACE,MAAM,IAAI,KAAK,CACb,qFAAqF,cAAc,EAAE,CACtG,CAAC;YACJ,CAAC;SACF,CACF;QACH,IAAI,EACF,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CACnC,MAAM,IAAI;YACR;gBACE,MAAM,IAAI,KAAK,CACb,iFAAiF,cAAc,EAAE,CAClG,CAAC;YACJ,CAAC;SACF,CACF;QACH,IAAI;QACF,aAAa;QACb,OAAO,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CACnC,MAAM,IAAI;YACR,aAAa;YACb;gBACE,MAAM,IAAI,KAAK,CACb,iFAAiF,cAAc,EAAE,CAClG,CAAC;YACJ,CAAC;SACF,CACF;QACH,cAAc;QACZ,aAAa;QACb,OAAO,cAAc,KAAK,WAAW,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,CACvD,MAAM,cAAc;YAClB,aAAa;YACb;gBACE,MAAM,IAAI,KAAK,CACb,uFAAuF,cAAc,EAAE,CACxG,CAAC;YACJ,CAAC;SACF,CACF;QACH,0BAA0B,EAAE,KAAK;QAC/B,aAAa;QACb,IAAc,EACd,IAAuB,EACK,EAAE,CAAC,CAAC;YAChC,GAAG,IAAI;YACP,IAAI,EAAE,IAAI,aAAa,CAAC,IAAI,CAAQ;SACrC,CAAC;QACF,eAAe,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,SAAS;QAC3C,YAAY,EAAE,GAAG,EAAE;YACjB,MAAM,IAAI,KAAK,CACb,gJAAgJ,CACjJ,CAAC;QACJ,CAAC;QACD,cAAc,EAAE,CAAC,KAAU,EAAE,EAAE,CAAC,KAAK;KACtC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/_shims/web-types.d.ts b/node_modules/openai/_shims/web-types.d.ts new file mode 100644 index 0000000..4ff3513 --- /dev/null +++ b/node_modules/openai/_shims/web-types.d.ts @@ -0,0 +1,83 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ +export type Agent = any; + +declare const _fetch: typeof fetch; +export { _fetch as fetch }; + +type _Request = Request; +export { _Request as Request }; + +type _RequestInfo = RequestInfo; +export { type _RequestInfo as RequestInfo }; + +type _RequestInit = RequestInit; +export { type _RequestInit as RequestInit }; + +type _Response = Response; +export { _Response as Response }; + +type _ResponseInit = ResponseInit; +export { type _ResponseInit as ResponseInit }; + +type _ResponseType = ResponseType; +export { type _ResponseType as ResponseType }; + +type _BodyInit = BodyInit; +export { type _BodyInit as BodyInit }; + +type _Headers = Headers; +export { _Headers as Headers }; + +type _HeadersInit = HeadersInit; +export { type _HeadersInit as HeadersInit }; + +type EndingType = 'native' | 'transparent'; + +export interface BlobPropertyBag { + endings?: EndingType; + type?: string; +} + +export interface FilePropertyBag extends BlobPropertyBag { + lastModified?: number; +} + +export type FileFromPathOptions = Omit; + +type _FormData = FormData; +declare const _FormData: typeof FormData; +export { _FormData as FormData }; + +type _File = File; +declare const _File: typeof File; +export { _File as File }; + +type _Blob = Blob; +declare const _Blob: typeof Blob; +export { _Blob as Blob }; + +export declare class Readable { + readable: boolean; + readonly readableEnded: boolean; + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + readonly readableObjectMode: boolean; + destroyed: boolean; + read(size?: number): any; + pause(): this; + resume(): this; + isPaused(): boolean; + destroy(error?: Error): this; + [Symbol.asyncIterator](): AsyncIterableIterator; +} + +export declare class FsReadStream extends Readable { + path: {}; // node type is string | Buffer +} + +type _ReadableStream = ReadableStream; +declare const _ReadableStream: typeof ReadableStream; +export { _ReadableStream as ReadableStream }; diff --git a/node_modules/openai/_shims/web-types.js b/node_modules/openai/_shims/web-types.js new file mode 100644 index 0000000..ddbdb79 --- /dev/null +++ b/node_modules/openai/_shims/web-types.js @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/node_modules/openai/_shims/web-types.mjs b/node_modules/openai/_shims/web-types.mjs new file mode 100644 index 0000000..ddbdb79 --- /dev/null +++ b/node_modules/openai/_shims/web-types.mjs @@ -0,0 +1,3 @@ +/** + * Disclaimer: modules in _shims aren't intended to be imported by SDK users. + */ diff --git a/node_modules/openai/bin/cli b/node_modules/openai/bin/cli new file mode 100644 index 0000000..00275ac --- /dev/null +++ b/node_modules/openai/bin/cli @@ -0,0 +1,49 @@ +#!/usr/bin/env node + +const { spawnSync } = require('child_process'); + +const commands = { + migrate: { + description: 'Run migrations to update from openai v3 to v4', + fn: () => { + console.log('This automatic code migration is provided by grit.io'); + console.log('Visit https://app.grit.io/studio?preset=openai_v4 for more details.') + + const result = spawnSync( + 'npx', + ['-y', '@getgrit/launcher', 'apply', 'openai_v4', ...process.argv.slice(3)], + { stdio: 'inherit' }, + ); + if (result.status !== 0) { + process.exit(result.status); + } + } + } +} + +function exitWithHelp() { + console.log("Usage: $0 "); + console.log(); + console.log('Subcommands:'); + + for (const [name, info] of Object.entries(commands)) { + console.log(` ${name} ${info.description}`); + } + + console.log(); + process.exit(1); +} + +if (process.argv.length < 3) { + exitWithHelp(); +} + +const commandName = process.argv[2]; + +const command = commands[commandName]; +if (!command) { + console.log(`Unknown subcommand ${commandName}.`); + exitWithHelp(); +} + +command.fn(); diff --git a/node_modules/openai/core.d.ts b/node_modules/openai/core.d.ts new file mode 100644 index 0000000..cc1108c --- /dev/null +++ b/node_modules/openai/core.d.ts @@ -0,0 +1,239 @@ + + +import { Stream } from "./streaming.js"; +import { APIError } from "./error.js"; +import { type Readable, type Agent, type RequestInfo, type RequestInit, type Response, type HeadersInit } from "./_shims/index.js"; +export { type Response }; +export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, type Uploadable, } from "./uploads.js"; +export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise; +type PromiseOrValue = T | Promise; +type APIResponseProps = { + response: Response; + options: FinalRequestOptions; + controller: AbortController; +}; +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +export declare class APIPromise extends Promise { + private responsePromise; + private parseResponse; + private parsedPromise; + constructor(responsePromise: Promise, parseResponse?: (props: APIResponseProps) => PromiseOrValue); + _thenUnwrap(transform: (data: T) => U): APIPromise; + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + asResponse(): Promise; + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + withResponse(): Promise<{ + data: T; + response: Response; + }>; + private parse; + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): Promise; + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null): Promise; + finally(onfinally?: (() => void) | undefined | null): Promise; +} +export declare abstract class APIClient { + baseURL: string; + maxRetries: number; + timeout: number; + httpAgent: Agent | undefined; + private fetch; + protected idempotencyHeader?: string; + constructor({ baseURL, maxRetries, timeout, // 10 minutes + httpAgent, fetch: overridenFetch, }: { + baseURL: string; + maxRetries?: number | undefined; + timeout: number | undefined; + httpAgent: Agent | undefined; + fetch: Fetch | undefined; + }); + protected authHeaders(opts: FinalRequestOptions): Headers; + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + protected defaultHeaders(opts: FinalRequestOptions): Headers; + protected abstract defaultQuery(): DefaultQuery | undefined; + /** + * Override this to add your own headers validation: + */ + protected validateHeaders(headers: Headers, customHeaders: Headers): void; + protected defaultIdempotencyKey(): string; + get(path: string, opts?: PromiseOrValue>): APIPromise; + post(path: string, opts?: PromiseOrValue>): APIPromise; + patch(path: string, opts?: PromiseOrValue>): APIPromise; + put(path: string, opts?: PromiseOrValue>): APIPromise; + delete(path: string, opts?: PromiseOrValue>): APIPromise; + private methodRequest; + getAPIList = AbstractPage>(path: string, Page: new (...args: any[]) => PageClass, opts?: RequestOptions): PagePromise; + private calculateContentLength; + buildRequest(options: FinalRequestOptions): { + req: RequestInit; + url: string; + timeout: number; + }; + private buildHeaders; + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + protected prepareOptions(options: FinalRequestOptions): Promise; + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + protected prepareRequest(request: RequestInit, { url, options }: { + url: string; + options: FinalRequestOptions; + }): Promise; + protected parseHeaders(headers: HeadersInit | null | undefined): Record; + protected makeStatusError(status: number | undefined, error: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError; + request(options: PromiseOrValue>, remainingRetries?: number | null): APIPromise; + private makeRequest; + requestAPIList = AbstractPage>(Page: new (...args: ConstructorParameters) => PageClass, options: FinalRequestOptions): PagePromise; + buildURL(path: string, query: Req | null | undefined): string; + protected stringifyQuery(query: Record): string; + fetchWithTimeout(url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController): Promise; + protected getRequestClient(): RequestClient; + private shouldRetry; + private retryRequest; + private calculateDefaultRetryTimeoutMillis; + private getUserAgent; +} +export type PageInfo = { + url: URL; +} | { + params: Record | null; +}; +export declare abstract class AbstractPage implements AsyncIterable { + #private; + protected options: FinalRequestOptions; + protected response: Response; + protected body: unknown; + constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions); + /** + * @deprecated Use nextPageInfo instead + */ + abstract nextPageParams(): Partial> | null; + abstract nextPageInfo(): PageInfo | null; + abstract getPaginatedItems(): Item[]; + hasNextPage(): boolean; + getNextPage(): Promise; + iterPages(): AsyncGenerator, void, unknown>; + [Symbol.asyncIterator](): AsyncGenerator, void, unknown>; +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +export declare class PagePromise, Item = ReturnType[number]> extends APIPromise implements AsyncIterable { + constructor(client: APIClient, request: Promise, Page: new (...args: ConstructorParameters) => PageClass); + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + [Symbol.asyncIterator](): AsyncGenerator, void, unknown>; +} +export declare const createResponseHeaders: (headers: Awaited>['headers']) => Record; +type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete'; +export type RequestClient = { + fetch: Fetch; +}; +export type Headers = Record; +export type DefaultQuery = Record; +export type KeysEnum = { + [P in keyof Required]: true; +}; +export type RequestOptions | Readable> = { + method?: HTTPMethod; + path?: string; + query?: Req | undefined; + body?: Req | null | undefined; + headers?: Headers | undefined; + maxRetries?: number; + stream?: boolean | undefined; + timeout?: number; + httpAgent?: Agent; + signal?: AbortSignal | undefined | null; + idempotencyKey?: string; + __binaryResponse?: boolean | undefined; + __streamClass?: typeof Stream; +}; +export declare const isRequestOptions: (obj: unknown) => obj is RequestOptions; +export type FinalRequestOptions | Readable> = RequestOptions & { + method: HTTPMethod; + path: string; +}; +export declare const safeJSON: (text: string) => any; +export declare const sleep: (ms: number) => Promise; +export declare const castToError: (err: any) => Error; +export declare const ensurePresent: (value: T | null | undefined) => T; +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export declare const readEnv: (env: string) => string | undefined; +export declare const coerceInteger: (value: unknown) => number; +export declare const coerceFloat: (value: unknown) => number; +export declare const coerceBoolean: (value: unknown) => boolean; +export declare const maybeCoerceInteger: (value: unknown) => number | undefined; +export declare const maybeCoerceFloat: (value: unknown) => number | undefined; +export declare const maybeCoerceBoolean: (value: unknown) => boolean | undefined; +export declare function isEmptyObj(obj: Object | null | undefined): boolean; +export declare function hasOwn(obj: Object, key: string): boolean; +export declare function debug(action: string, ...args: any[]): void; +export declare const isRunningInBrowser: () => boolean; +export interface HeadersProtocol { + get: (header: string) => string | null | undefined; +} +export type HeadersLike = Record | HeadersProtocol; +export declare const isHeadersProtocol: (headers: any) => headers is HeadersProtocol; +export declare const getRequiredHeader: (headers: HeadersLike, header: string) => string; +/** + * Encodes a string to Base64 format. + */ +export declare const toBase64: (str: string | null | undefined) => string; +export declare function isObj(obj: unknown): obj is Record; +//# sourceMappingURL=core.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/core.d.ts.map b/node_modules/openai/core.d.ts.map new file mode 100644 index 0000000..17f1b4d --- /dev/null +++ b/node_modules/openai/core.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["src/core.ts"],"names":[],"mappings":";;AACA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAEL,QAAQ,EAIT,MAAM,SAAS,CAAC;AACjB,OAAO,EAEL,KAAK,QAAQ,EAEb,KAAK,KAAK,EAEV,KAAK,WAAW,EAChB,KAAK,WAAW,EAChB,KAAK,QAAQ,EACb,KAAK,WAAW,EACjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,KAAK,QAAQ,EAAE,CAAC;AAEzB,OAAO,EACL,gCAAgC,EAChC,2BAA2B,EAC3B,UAAU,EACV,KAAK,UAAU,GAChB,MAAM,WAAW,CAAC;AAEnB,MAAM,MAAM,KAAK,GAAG,CAAC,GAAG,EAAE,WAAW,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAEhF,KAAK,cAAc,CAAC,CAAC,IAAI,CAAC,GAA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O,KAAG,OAAO,GAAG,SAK7D,CAAC;AAGF,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAIlE;AAGD,wBAAgB,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAExD;AAwBD,wBAAgB,KAAK,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,QAInD;AAaD,eAAO,MAAM,kBAAkB,eAS9B,CAAC;AAEF,MAAM,WAAW,eAAe;IAC9B,GAAG,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;CACpD;AACD,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,GAAG,eAAe,CAAC;AAE1F,eAAO,MAAM,iBAAiB,YAAa,GAAG,+BAE7C,CAAC;AAEF,eAAO,MAAM,iBAAiB,YAAa,WAAW,UAAU,MAAM,KAAG,MA2BxE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,QAAQ,QAAS,MAAM,GAAG,IAAI,GAAG,SAAS,KAAG,MAWzD,CAAC;AAEF,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAElE"} \ No newline at end of file diff --git a/node_modules/openai/core.js b/node_modules/openai/core.js new file mode 100644 index 0000000..487f223 --- /dev/null +++ b/node_modules/openai/core.js @@ -0,0 +1,878 @@ +"use strict"; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractPage_client; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isObj = exports.toBase64 = exports.getRequiredHeader = exports.isHeadersProtocol = exports.isRunningInBrowser = exports.debug = exports.hasOwn = exports.isEmptyObj = exports.maybeCoerceBoolean = exports.maybeCoerceFloat = exports.maybeCoerceInteger = exports.coerceBoolean = exports.coerceFloat = exports.coerceInteger = exports.readEnv = exports.ensurePresent = exports.castToError = exports.sleep = exports.safeJSON = exports.isRequestOptions = exports.createResponseHeaders = exports.PagePromise = exports.AbstractPage = exports.APIClient = exports.APIPromise = exports.createForm = exports.multipartFormRequestOptions = exports.maybeMultipartFormRequestOptions = void 0; +const version_1 = require("./version.js"); +const streaming_1 = require("./streaming.js"); +const error_1 = require("./error.js"); +const index_1 = require("./_shims/index.js"); +const uploads_1 = require("./uploads.js"); +var uploads_2 = require("./uploads.js"); +Object.defineProperty(exports, "maybeMultipartFormRequestOptions", { enumerable: true, get: function () { return uploads_2.maybeMultipartFormRequestOptions; } }); +Object.defineProperty(exports, "multipartFormRequestOptions", { enumerable: true, get: function () { return uploads_2.multipartFormRequestOptions; } }); +Object.defineProperty(exports, "createForm", { enumerable: true, get: function () { return uploads_2.createForm; } }); +async function defaultParseResponse(props) { + const { response } = props; + if (props.options.stream) { + debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return streaming_1.Stream.fromSSEResponse(response, props.controller); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + if (contentType?.includes('application/json')) { + const json = await response.json(); + debug('response', response.status, response.url, response.headers, json); + return json; + } + const text = await response.text(); + debug('response', response.status, response.url, response.headers, text); + // TODO handle blob, arraybuffer, other content types, etc. + return text; +} +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +class APIPromise extends Promise { + constructor(responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + } + _thenUnwrap(transform) { + return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then(this.parseResponse); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +exports.APIPromise = APIPromise; +class APIClient { + constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes + httpAgent, fetch: overridenFetch, }) { + this.baseURL = baseURL; + this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); + this.timeout = validatePositiveInteger('timeout', timeout); + this.httpAgent = httpAgent; + this.fetch = overridenFetch ?? index_1.fetch; + } + authHeaders(opts) { + return {}; + } + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + defaultHeaders(opts) { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': this.getUserAgent(), + ...getPlatformHeaders(), + ...this.authHeaders(opts), + }; + } + /** + * Override this to add your own headers validation: + */ + validateHeaders(headers, customHeaders) { } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts }))); + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + calculateContentLength(body) { + if (typeof body === 'string') { + if (typeof Buffer !== 'undefined') { + return Buffer.byteLength(body, 'utf8').toString(); + } + if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder(); + const encoded = encoder.encode(body); + return encoded.length.toString(); + } + } + return null; + } + buildRequest(options) { + const { method, path, query, headers: headers = {} } = options; + const body = (0, uploads_1.isMultipartBody)(options.body) ? options.body.body + : options.body ? JSON.stringify(options.body, null, 2) + : null; + const contentLength = this.calculateContentLength(body); + const url = this.buildURL(path, query); + if ('timeout' in options) + validatePositiveInteger('timeout', options.timeout); + const timeout = options.timeout ?? this.timeout; + const httpAgent = options.httpAgent ?? this.httpAgent ?? (0, index_1.getDefaultAgent)(url); + const minAgentTimeout = timeout + 1000; + if (typeof httpAgent?.options?.timeout === 'number' && + minAgentTimeout > (httpAgent.options.timeout ?? 0)) { + // Allow any given request to bump our agent active socket timeout. + // This may seem strange, but leaking active sockets should be rare and not particularly problematic, + // and without mutating agent we would need to create more of them. + // This tradeoff optimizes for performance. + httpAgent.options.timeout = minAgentTimeout; + } + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + headers[this.idempotencyHeader] = options.idempotencyKey; + } + const reqHeaders = this.buildHeaders({ options, headers, contentLength }); + const req = { + method, + ...(body && { body: body }), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + // @ts-ignore node-fetch uses a custom AbortSignal type that is + // not compatible with standard web types + signal: options.signal ?? null, + }; + return { req, url, timeout }; + } + buildHeaders({ options, headers, contentLength, }) { + const reqHeaders = {}; + if (contentLength) { + reqHeaders['content-length'] = contentLength; + } + const defaultHeaders = this.defaultHeaders(options); + applyHeadersMut(reqHeaders, defaultHeaders); + applyHeadersMut(reqHeaders, headers); + // let builtin fetch set the Content-Type for multipart bodies + if ((0, uploads_1.isMultipartBody)(options.body) && index_1.kind !== 'node') { + delete reqHeaders['content-type']; + } + this.validateHeaders(reqHeaders, headers); + return reqHeaders; + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } + parseHeaders(headers) { + return (!headers ? {} + : Symbol.iterator in headers ? + Object.fromEntries(Array.from(headers).map((header) => [...header])) + : { ...headers }); + } + makeStatusError(status, error, message, headers) { + return error_1.APIError.generate(status, error, message, headers); + } + request(options, remainingRetries = null) { + return new APIPromise(this.makeRequest(options, remainingRetries)); + } + async makeRequest(optionsInput, retriesRemaining) { + const options = await optionsInput; + if (retriesRemaining == null) { + retriesRemaining = options.maxRetries ?? this.maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = this.buildRequest(options); + await this.prepareRequest(req, { url, options }); + debug('request', url, options, req.headers); + if (options.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(exports.castToError); + if (response instanceof Error) { + if (options.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + if (retriesRemaining) { + return this.retryRequest(options, retriesRemaining); + } + if (response.name === 'AbortError') { + throw new error_1.APIConnectionTimeoutError(); + } + throw new error_1.APIConnectionError({ cause: response }); + } + const responseHeaders = (0, exports.createResponseHeaders)(response.headers); + if (!response.ok) { + if (retriesRemaining && this.shouldRetry(response)) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders); + return this.retryRequest(options, retriesRemaining, responseHeaders); + } + const errText = await response.text().catch((e) => (0, exports.castToError)(e).message); + const errJSON = (0, exports.safeJSON)(errText); + const errMessage = errJSON ? undefined : errText; + const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); + const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); + throw err; + } + return { response, options, controller }; + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null); + return new PagePromise(this, request, Page); + } + buildURL(path, query) { + const url = isAbsoluteURL(path) ? + new URL(path) + : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new error_1.OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); + }) + .join('&'); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + return (this.getRequestClient() + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + .fetch.call(undefined, url, { signal: controller.signal, ...options }) + .finally(() => { + clearTimeout(timeout); + })); + } + getRequestClient() { + return { fetch: this.fetch }; + } + shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.['retry-after']; + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await (0, exports.sleep)(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + getUserAgent() { + return `${this.constructor.name}/JS ${version_1.VERSION}`; + } +} +exports.APIClient = APIClient; +class AbstractPage { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageInfo() != null; + } + async getNextPage() { + const nextInfo = this.nextPageInfo(); + if (!nextInfo) { + throw new error_1.OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); + } + const nextOptions = { ...this.options }; + if ('params' in nextInfo && typeof nextOptions.query === 'object') { + nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; + } + else if ('url' in nextInfo) { + const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; + for (const [key, value] of params) { + nextInfo.url.searchParams.set(key, value); + } + nextOptions.query = undefined; + nextOptions.path = nextInfo.url.toString(); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} +exports.AbstractPage = AbstractPage; +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +class PagePromise extends APIPromise { + constructor(client, request, Page) { + super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} +exports.PagePromise = PagePromise; +const createResponseHeaders = (headers) => { + return new Proxy(Object.fromEntries( + // @ts-ignore + headers.entries()), { + get(target, name) { + const key = name.toString(); + return target[key.toLowerCase()] || target[key]; + }, + }); +}; +exports.createResponseHeaders = createResponseHeaders; +// This is required so that we can determine if a given object matches the RequestOptions +// type at runtime. While this requires duplication, it is enforced by the TypeScript +// compiler such that any missing / extraneous keys will cause an error. +const requestOptionsKeys = { + method: true, + path: true, + query: true, + body: true, + headers: true, + maxRetries: true, + stream: true, + timeout: true, + httpAgent: true, + signal: true, + idempotencyKey: true, + __binaryResponse: true, + __streamClass: true, +}; +const isRequestOptions = (obj) => { + return (typeof obj === 'object' && + obj !== null && + !isEmptyObj(obj) && + Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))); +}; +exports.isRequestOptions = isRequestOptions; +const getPlatformProperties = () => { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': Deno.version, + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': process.version, + }; + } + // Check if Node.js + if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': normalizePlatform(process.platform), + 'X-Stainless-Arch': normalizeArch(process.arch), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': process.version, + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_1.VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +const getPlatformHeaders = () => { + return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); +}; +const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +exports.safeJSON = safeJSON; +// https://stackoverflow.com/a/19709846 +const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i'); +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +exports.sleep = sleep; +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new error_1.OpenAIError(`${name} must be an integer`); + } + if (n < 0) { + throw new error_1.OpenAIError(`${name} must be a positive integer`); + } + return n; +}; +const castToError = (err) => { + if (err instanceof Error) + return err; + return new Error(err); +}; +exports.castToError = castToError; +const ensurePresent = (value) => { + if (value == null) + throw new error_1.OpenAIError(`Expected a value to be given but received ${value} instead.`); + return value; +}; +exports.ensurePresent = ensurePresent; +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const readEnv = (env) => { + if (typeof process !== 'undefined') { + return process.env?.[env]?.trim() ?? undefined; + } + if (typeof Deno !== 'undefined') { + return Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +exports.readEnv = readEnv; +const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new error_1.OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +exports.coerceInteger = coerceInteger; +const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new error_1.OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +exports.coerceFloat = coerceFloat; +const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +exports.coerceBoolean = coerceBoolean; +const maybeCoerceInteger = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceInteger)(value); +}; +exports.maybeCoerceInteger = maybeCoerceInteger; +const maybeCoerceFloat = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceFloat)(value); +}; +exports.maybeCoerceFloat = maybeCoerceFloat; +const maybeCoerceBoolean = (value) => { + if (value === undefined) { + return undefined; + } + return (0, exports.coerceBoolean)(value); +}; +exports.maybeCoerceBoolean = maybeCoerceBoolean; +// https://stackoverflow.com/a/34491287 +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +exports.isEmptyObj = isEmptyObj; +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +exports.hasOwn = hasOwn; +/** + * Copies headers from "newHeaders" onto "targetHeaders", + * using lower-case for all properties, + * ignoring any keys with undefined values, + * and deleting any keys with null values. + */ +function applyHeadersMut(targetHeaders, newHeaders) { + for (const k in newHeaders) { + if (!hasOwn(newHeaders, k)) + continue; + const lowerKey = k.toLowerCase(); + if (!lowerKey) + continue; + const val = newHeaders[k]; + if (val === null) { + delete targetHeaders[lowerKey]; + } + else if (val !== undefined) { + targetHeaders[lowerKey] = val; + } + } +} +function debug(action, ...args) { + if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') { + console.log(`OpenAI:DEBUG:${action}`, ...args); + } +} +exports.debug = debug; +/** + * https://stackoverflow.com/a/2117523 + */ +const uuid4 = () => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +}; +const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +exports.isRunningInBrowser = isRunningInBrowser; +const isHeadersProtocol = (headers) => { + return typeof headers?.get === 'function'; +}; +exports.isHeadersProtocol = isHeadersProtocol; +const getRequiredHeader = (headers, header) => { + const lowerCasedHeader = header.toLowerCase(); + if ((0, exports.isHeadersProtocol)(headers)) { + // to deal with the case where the header looks like Stainless-Event-Id + const intercapsHeader = header[0]?.toUpperCase() + + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase()); + for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) { + const value = headers.get(key); + if (value) { + return value; + } + } + } + for (const [key, value] of Object.entries(headers)) { + if (key.toLowerCase() === lowerCasedHeader) { + if (Array.isArray(value)) { + if (value.length <= 1) + return value[0]; + console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`); + return value[0]; + } + return value; + } + } + throw new Error(`Could not find ${header} header`); +}; +exports.getRequiredHeader = getRequiredHeader; +/** + * Encodes a string to Base64 format. + */ +const toBase64 = (str) => { + if (!str) + return ''; + if (typeof Buffer !== 'undefined') { + return Buffer.from(str).toString('base64'); + } + if (typeof btoa !== 'undefined') { + return btoa(str); + } + throw new error_1.OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); +}; +exports.toBase64 = toBase64; +function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +exports.isObj = isObj; +//# sourceMappingURL=core.js.map \ No newline at end of file diff --git a/node_modules/openai/core.js.map b/node_modules/openai/core.js.map new file mode 100644 index 0000000..ea98e69 --- /dev/null +++ b/node_modules/openai/core.js.map @@ -0,0 +1 @@ +{"version":3,"file":"core.js","sourceRoot":"","sources":["src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,0CAAoC;AACpC,8CAAqC;AACrC,sCAMiB;AACjB,6CAUwB;AAExB,0CAA4C;AAC5C,wCAKmB;AAJjB,2HAAA,gCAAgC,OAAA;AAChC,sHAAA,2BAA2B,OAAA;AAC3B,qGAAA,UAAU,OAAA;AAcZ,KAAK,UAAU,oBAAoB,CAAI,KAAuB;IAC5D,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IAC3B,IAAI,K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EAAE;QAClD,IAAI,GAAG,CAAC,WAAW,EAAE,KAAK,gBAAgB,EAAE;YAC1C,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBACxB,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC;oBAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;gBACvC,OAAO,CAAC,IAAI,CAAC,YAAY,KAAK,CAAC,MAAM,oBAAoB,MAAM,iCAAiC,CAAC,CAAC;gBAClG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;aACjB;YACD,OAAO,KAAK,CAAC;SACd;KACF;IAED,MAAM,IAAI,KAAK,CAAC,kBAAkB,MAAM,SAAS,CAAC,CAAC;AACrD,CAAC,CAAC;AA3BW,QAAA,iBAAiB,qBA2B5B;AAEF;;GAEG;AACI,MAAM,QAAQ,GAAG,CAAC,GAA8B,EAAU,EAAE;IACjE,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IACpB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACjC,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAED,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QAC/B,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;KAClB;IAED,MAAM,IAAI,mBAAW,CAAC,uEAAuE,CAAC,CAAC;AACjG,CAAC,CAAC;AAXW,QAAA,QAAQ,YAWnB;AAEF,SAAgB,KAAK,CAAC,GAAY;IAChC,OAAO,GAAG,IAAI,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AACvE,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/node_modules/openai/core.mjs b/node_modules/openai/core.mjs new file mode 100644 index 0000000..a34f096 --- /dev/null +++ b/node_modules/openai/core.mjs @@ -0,0 +1,847 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractPage_client; +import { VERSION } from "./version.mjs"; +import { Stream } from "./streaming.mjs"; +import { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, } from "./error.mjs"; +import { kind as shimsKind, getDefaultAgent, fetch, } from "./_shims/index.mjs"; +import { isMultipartBody } from "./uploads.mjs"; +export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from "./uploads.mjs"; +async function defaultParseResponse(props) { + const { response } = props; + if (props.options.stream) { + debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return Stream.fromSSEResponse(response, props.controller); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + if (contentType?.includes('application/json')) { + const json = await response.json(); + debug('response', response.status, response.url, response.headers, json); + return json; + } + const text = await response.text(); + debug('response', response.status, response.url, response.headers, text); + // TODO handle blob, arraybuffer, other content types, etc. + return text; +} +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +export class APIPromise extends Promise { + constructor(responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + } + _thenUnwrap(transform) { + return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data and the raw `Response` instance. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` if you can, + * or add one of these imports before your first `import … from 'openai'`: + * - `import 'openai/shims/node'` (if you're running on Node) + * - `import 'openai/shims/web'` (otherwise) + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then(this.parseResponse); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +export class APIClient { + constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes + httpAgent, fetch: overridenFetch, }) { + this.baseURL = baseURL; + this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); + this.timeout = validatePositiveInteger('timeout', timeout); + this.httpAgent = httpAgent; + this.fetch = overridenFetch ?? fetch; + } + authHeaders(opts) { + return {}; + } + /** + * Override this to add your own default headers, for example: + * + * { + * ...super.defaultHeaders(), + * Authorization: 'Bearer 123', + * } + */ + defaultHeaders(opts) { + return { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'User-Agent': this.getUserAgent(), + ...getPlatformHeaders(), + ...this.authHeaders(opts), + }; + } + /** + * Override this to add your own headers validation: + */ + validateHeaders(headers, customHeaders) { } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid4()}`; + } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => ({ method, path, ...opts }))); + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + calculateContentLength(body) { + if (typeof body === 'string') { + if (typeof Buffer !== 'undefined') { + return Buffer.byteLength(body, 'utf8').toString(); + } + if (typeof TextEncoder !== 'undefined') { + const encoder = new TextEncoder(); + const encoded = encoder.encode(body); + return encoded.length.toString(); + } + } + return null; + } + buildRequest(options) { + const { method, path, query, headers: headers = {} } = options; + const body = isMultipartBody(options.body) ? options.body.body + : options.body ? JSON.stringify(options.body, null, 2) + : null; + const contentLength = this.calculateContentLength(body); + const url = this.buildURL(path, query); + if ('timeout' in options) + validatePositiveInteger('timeout', options.timeout); + const timeout = options.timeout ?? this.timeout; + const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url); + const minAgentTimeout = timeout + 1000; + if (typeof httpAgent?.options?.timeout === 'number' && + minAgentTimeout > (httpAgent.options.timeout ?? 0)) { + // Allow any given request to bump our agent active socket timeout. + // This may seem strange, but leaking active sockets should be rare and not particularly problematic, + // and without mutating agent we would need to create more of them. + // This tradeoff optimizes for performance. + httpAgent.options.timeout = minAgentTimeout; + } + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + headers[this.idempotencyHeader] = options.idempotencyKey; + } + const reqHeaders = this.buildHeaders({ options, headers, contentLength }); + const req = { + method, + ...(body && { body: body }), + headers: reqHeaders, + ...(httpAgent && { agent: httpAgent }), + // @ts-ignore node-fetch uses a custom AbortSignal type that is + // not compatible with standard web types + signal: options.signal ?? null, + }; + return { req, url, timeout }; + } + buildHeaders({ options, headers, contentLength, }) { + const reqHeaders = {}; + if (contentLength) { + reqHeaders['content-length'] = contentLength; + } + const defaultHeaders = this.defaultHeaders(options); + applyHeadersMut(reqHeaders, defaultHeaders); + applyHeadersMut(reqHeaders, headers); + // let builtin fetch set the Content-Type for multipart bodies + if (isMultipartBody(options.body) && shimsKind !== 'node') { + delete reqHeaders['content-type']; + } + this.validateHeaders(reqHeaders, headers); + return reqHeaders; + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } + parseHeaders(headers) { + return (!headers ? {} + : Symbol.iterator in headers ? + Object.fromEntries(Array.from(headers).map((header) => [...header])) + : { ...headers }); + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + request(options, remainingRetries = null) { + return new APIPromise(this.makeRequest(options, remainingRetries)); + } + async makeRequest(optionsInput, retriesRemaining) { + const options = await optionsInput; + if (retriesRemaining == null) { + retriesRemaining = options.maxRetries ?? this.maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = this.buildRequest(options); + await this.prepareRequest(req, { url, options }); + debug('request', url, options, req.headers); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + if (response instanceof Error) { + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + if (retriesRemaining) { + return this.retryRequest(options, retriesRemaining); + } + if (response.name === 'AbortError') { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const responseHeaders = createResponseHeaders(response.headers); + if (!response.ok) { + if (retriesRemaining && this.shouldRetry(response)) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders); + return this.retryRequest(options, retriesRemaining, responseHeaders); + } + const errText = await response.text().catch((e) => castToError(e).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; + debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); + const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); + throw err; + } + return { response, options, controller }; + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null); + return new PagePromise(this, request, Page); + } + buildURL(path, query) { + const url = isAbsoluteURL(path) ? + new URL(path) + : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); + }) + .join('&'); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + return (this.getRequestClient() + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + .fetch.call(undefined, url, { signal: controller.signal, ...options }) + .finally(() => { + clearTimeout(timeout); + })); + } + getRequestClient() { + return { fetch: this.fetch }; + } + shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.['retry-after']; + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } +} +export class AbstractPage { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageInfo() != null; + } + async getNextPage() { + const nextInfo = this.nextPageInfo(); + if (!nextInfo) { + throw new OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); + } + const nextOptions = { ...this.options }; + if ('params' in nextInfo && typeof nextOptions.query === 'object') { + nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; + } + else if ('url' in nextInfo) { + const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; + for (const [key, value] of params) { + nextInfo.url.searchParams.set(key, value); + } + nextOptions.query = undefined; + nextOptions.path = nextInfo.url.toString(); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +export class PagePromise extends APIPromise { + constructor(client, request, Page) { + super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} +export const createResponseHeaders = (headers) => { + return new Proxy(Object.fromEntries( + // @ts-ignore + headers.entries()), { + get(target, name) { + const key = name.toString(); + return target[key.toLowerCase()] || target[key]; + }, + }); +}; +// This is required so that we can determine if a given object matches the RequestOptions +// type at runtime. While this requires duplication, it is enforced by the TypeScript +// compiler such that any missing / extraneous keys will cause an error. +const requestOptionsKeys = { + method: true, + path: true, + query: true, + body: true, + headers: true, + maxRetries: true, + stream: true, + timeout: true, + httpAgent: true, + signal: true, + idempotencyKey: true, + __binaryResponse: true, + __streamClass: true, +}; +export const isRequestOptions = (obj) => { + return (typeof obj === 'object' && + obj !== null && + !isEmptyObj(obj) && + Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))); +}; +const getPlatformProperties = () => { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': Deno.version, + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': process.version, + }; + } + // Check if Node.js + if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(process.platform), + 'X-Stainless-Arch': normalizeArch(process.arch), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': process.version, + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +const getPlatformHeaders = () => { + return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); +}; +export const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +// https://stackoverflow.com/a/19709846 +const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i'); +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new OpenAIError(`${name} must be an integer`); + } + if (n < 0) { + throw new OpenAIError(`${name} must be a positive integer`); + } + return n; +}; +export const castToError = (err) => { + if (err instanceof Error) + return err; + return new Error(err); +}; +export const ensurePresent = (value) => { + if (value == null) + throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); + return value; +}; +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +export const readEnv = (env) => { + if (typeof process !== 'undefined') { + return process.env?.[env]?.trim() ?? undefined; + } + if (typeof Deno !== 'undefined') { + return Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +export const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +export const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +export const maybeCoerceInteger = (value) => { + if (value === undefined) { + return undefined; + } + return coerceInteger(value); +}; +export const maybeCoerceFloat = (value) => { + if (value === undefined) { + return undefined; + } + return coerceFloat(value); +}; +export const maybeCoerceBoolean = (value) => { + if (value === undefined) { + return undefined; + } + return coerceBoolean(value); +}; +// https://stackoverflow.com/a/34491287 +export function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +export function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +/** + * Copies headers from "newHeaders" onto "targetHeaders", + * using lower-case for all properties, + * ignoring any keys with undefined values, + * and deleting any keys with null values. + */ +function applyHeadersMut(targetHeaders, newHeaders) { + for (const k in newHeaders) { + if (!hasOwn(newHeaders, k)) + continue; + const lowerKey = k.toLowerCase(); + if (!lowerKey) + continue; + const val = newHeaders[k]; + if (val === null) { + delete targetHeaders[lowerKey]; + } + else if (val !== undefined) { + targetHeaders[lowerKey] = val; + } + } +} +export function debug(action, ...args) { + if (typeof process !== 'undefined' && process.env['DEBUG'] === 'true') { + console.log(`OpenAI:DEBUG:${action}`, ...args); + } +} +/** + * https://stackoverflow.com/a/2117523 + */ +const uuid4 = () => { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { + const r = (Math.random() * 16) | 0; + const v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +}; +export const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +export const isHeadersProtocol = (headers) => { + return typeof headers?.get === 'function'; +}; +export const getRequiredHeader = (headers, header) => { + const lowerCasedHeader = header.toLowerCase(); + if (isHeadersProtocol(headers)) { + // to deal with the case where the header looks like Stainless-Event-Id + const intercapsHeader = header[0]?.toUpperCase() + + header.substring(1).replace(/([^\w])(\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase()); + for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) { + const value = headers.get(key); + if (value) { + return value; + } + } + } + for (const [key, value] of Object.entries(headers)) { + if (key.toLowerCase() === lowerCasedHeader) { + if (Array.isArray(value)) { + if (value.length <= 1) + return value[0]; + console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`); + return value[0]; + } + return value; + } + } + throw new Error(`Could not find ${header} header`); +}; +/** + * Encodes a string to Base64 format. + */ +export const toBase64 = (str) => { + if (!str) + return ''; + if (typeof Buffer !== 'undefined') { + return Buffer.from(str).toString('base64'); + } + if (typeof btoa !== 'undefined') { + return btoa(str); + } + throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined'); +}; +export function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +//# sourceMappingURL=core.mjs.map \ No newline at end of file diff --git a/node_modules/openai/core.mjs.map b/node_modules/openai/core.mjs.map new file mode 100644 index 0000000..9ce1644 --- /dev/null +++ b/node_modules/openai/core.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"core.mjs","sourceRoot":"","sources":["src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;OAAO,EAAE,OAAO,EAAE;OACX,EAAE,MAAM,EAAE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K,gBAAgB,EAAE;YAC1C,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;gBACxB,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC;oBAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;gBACvC,OAAO,CAAC,IAAI,CAAC,YAAY,KAAK,CAAC,MAAM,oBAAoB,MAAM,iCAAiC,CAAC,CAAC;gBAClG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC;aACjB;YACD,OAAO,KAAK,CAAC;SACd;KACF;IAED,MAAM,IAAI,KAAK,CAAC,kBAAkB,MAAM,SAAS,CAAC,CAAC;AACrD,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAA8B,EAAU,EAAE;IACjE,IAAI,CAAC,GAAG;QAAE,OAAO,EAAE,CAAC;IACpB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACjC,OAAO,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;KAC5C;IAED,IAAI,OAAO,IAAI,KAAK,WAAW,EAAE;QAC/B,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC;KAClB;IAED,MAAM,IAAI,WAAW,CAAC,uEAAuE,CAAC,CAAC;AACjG,CAAC,CAAC;AAEF,MAAM,UAAU,KAAK,CAAC,GAAY;IAChC,OAAO,GAAG,IAAI,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AACvE,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/error.d.ts b/node_modules/openai/error.d.ts new file mode 100644 index 0000000..668386a --- /dev/null +++ b/node_modules/openai/error.d.ts @@ -0,0 +1,56 @@ +import { Headers } from "./core.js"; +export declare class OpenAIError extends Error { +} +export declare class APIError extends OpenAIError { + readonly status: number | undefined; + readonly headers: Headers | undefined; + readonly error: Object | undefined; + readonly code: string | null | undefined; + readonly param: string | null | undefined; + readonly type: string | undefined; + constructor(status: number | undefined, error: Object | undefined, message: string | undefined, headers: Headers | undefined); + private static makeMessage; + static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError; +} +export declare class APIUserAbortError extends APIError { + readonly status: undefined; + constructor({ message }?: { + message?: string; + }); +} +export declare class APIConnectionError extends APIError { + readonly status: undefined; + constructor({ message, cause }: { + message?: string; + cause?: Error | undefined; + }); +} +export declare class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message }?: { + message?: string; + }); +} +export declare class BadRequestError extends APIError { + readonly status: 400; +} +export declare class AuthenticationError extends APIError { + readonly status: 401; +} +export declare class PermissionDeniedError extends APIError { + readonly status: 403; +} +export declare class NotFoundError extends APIError { + readonly status: 404; +} +export declare class ConflictError extends APIError { + readonly status: 409; +} +export declare class UnprocessableEntityError extends APIError { + readonly status: 422; +} +export declare class RateLimitError extends APIError { + readonly status: 429; +} +export declare class InternalServerError extends APIError { +} +//# sourceMappingURL=error.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/error.d.ts.map b/node_modules/openai/error.d.ts.map new file mode 100644 index 0000000..f672987 --- /dev/null +++ b/node_modules/openai/error.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":"AAEA,OAAO,EAAe,OAAO,EAAE,MAAM,QAAQ,CAAC;AAE9C,qBAAa,WAAY,SAAQ,KAAK;CAAG;AAEzC,qBAAa,QAAS,SAAQ,WAAW;IACvC,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IACpC,QAAQ,CAAC,OAAO,EAAE,OAAO,GAAG,SAAS,CAAC;IACtC,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;IAEnC,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACzC,QAAQ,CAAC,KAAK,EAAE,M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M,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,aAAc,SAAQ,QAAQ;IACzC,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,wBAAyB,SAAQ,QAAQ;IACpD,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,cAAe,SAAQ,QAAQ;IAC1C,SAAkB,MAAM,EAAE,GAAG,CAAO;CACrC;AAED,qBAAa,mBAAoB,SAAQ,QAAQ;CAAG"} \ No newline at end of file diff --git a/node_modules/openai/error.js b/node_modules/openai/error.js new file mode 100644 index 0000000..176a237 --- /dev/null +++ b/node_modules/openai/error.js @@ -0,0 +1,147 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalServerError = exports.RateLimitError = exports.UnprocessableEntityError = exports.ConflictError = exports.NotFoundError = exports.PermissionDeniedError = exports.AuthenticationError = exports.BadRequestError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIUserAbortError = exports.APIError = exports.OpenAIError = void 0; +const core_1 = require("./core.js"); +class OpenAIError extends Error { +} +exports.OpenAIError = OpenAIError; +class APIError extends OpenAIError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + const data = error; + this.error = data; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; + } + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; + } + static generate(status, errorResponse, message, headers) { + if (!status) { + return new APIConnectionError({ cause: (0, core_1.castToError)(errorResponse) }); + } + const error = errorResponse?.['error']; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new APIError(status, error, message, headers); + } +} +exports.APIError = APIError; +class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + this.status = undefined; + } +} +exports.APIUserAbortError = APIUserAbortError; +class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + this.status = undefined; + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } +} +exports.APIConnectionError = APIConnectionError; +class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} +exports.APIConnectionTimeoutError = APIConnectionTimeoutError; +class BadRequestError extends APIError { + constructor() { + super(...arguments); + this.status = 400; + } +} +exports.BadRequestError = BadRequestError; +class AuthenticationError extends APIError { + constructor() { + super(...arguments); + this.status = 401; + } +} +exports.AuthenticationError = AuthenticationError; +class PermissionDeniedError extends APIError { + constructor() { + super(...arguments); + this.status = 403; + } +} +exports.PermissionDeniedError = PermissionDeniedError; +class NotFoundError extends APIError { + constructor() { + super(...arguments); + this.status = 404; + } +} +exports.NotFoundError = NotFoundError; +class ConflictError extends APIError { + constructor() { + super(...arguments); + this.status = 409; + } +} +exports.ConflictError = ConflictError; +class UnprocessableEntityError extends APIError { + constructor() { + super(...arguments); + this.status = 422; + } +} +exports.UnprocessableEntityError = UnprocessableEntityError; +class RateLimitError extends APIError { + constructor() { + super(...arguments); + this.status = 429; + } +} +exports.RateLimitError = RateLimitError; +class InternalServerError extends APIError { +} +exports.InternalServerError = InternalServerError; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/node_modules/openai/error.js.map b/node_modules/openai/error.js.map new file mode 100644 index 0000000..c5d004b --- /dev/null +++ b/node_modules/openai/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":";AAAA,qDAAqD;;;AAErD,oCAA8C;AAE9C,MAAa,WAAY,SAAQ,KAAK;CAAG;AAAzC,kCAAyC;AAEzC,MAAa,QAAS,SAAQ,WAAW;IASvC,YACE,MAA0B,EAC1B,KAAyB,EACzB,OAA2B,EAC3B,OAA4B;QAE5B,KAAK,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,MAAM,EAAE,KAAK,EAAE,OAAO,CAAC,EAAE,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QAEvB,MAAM,IAAI,GAAG,KAA4B,CAAC;QAC1C,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,IAAI,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC;QAC3B,IAAI,CAAC,KAAK,GAAG,IAAI,EAAE,CAAC,OAAO,CAAC,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,CAAC;IAC7B,CAAC;IAEO,MAAM,CAAC,WAAW,CAAC,MAA0B,EAAE,KAAU,EAAE,OAA2B;QAC5F,MAAM,GAAG,GACP,KAAK,EAAE,OAAO,CAAC,CAAC;YACd,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC;gBACjC,KAAK,CAAC,OAAO;gBACf,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC;YACjC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC;gBAC/B,CAAC,CAAC,OAAO,CAAC;QAEZ,IAAI,MAAM,IAAI,GAAG,EAAE;YACjB,OAAO,GAAG,MAAM,I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AAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAFD,kDAEC;AAED,MAAa,qBAAsB,SAAQ,QAAQ;IAAnD;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAFD,sDAEC;AAED,MAAa,aAAc,SAAQ,QAAQ;IAA3C;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAFD,sCAEC;AAED,MAAa,aAAc,SAAQ,QAAQ;IAA3C;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAFD,sCAEC;AAED,MAAa,wBAAyB,SAAQ,QAAQ;IAAtD;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAFD,4DAEC;AAED,MAAa,cAAe,SAAQ,QAAQ;IAA5C;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAFD,wCAEC;AAED,MAAa,mBAAoB,SAAQ,QAAQ;CAAG;AAApD,kDAAoD"} \ No newline at end of file diff --git a/node_modules/openai/error.mjs b/node_modules/openai/error.mjs new file mode 100644 index 0000000..5714f2b --- /dev/null +++ b/node_modules/openai/error.mjs @@ -0,0 +1,131 @@ +// File generated from our OpenAPI spec by Stainless. +import { castToError } from "./core.mjs"; +export class OpenAIError extends Error { +} +export class APIError extends OpenAIError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + const data = error; + this.error = data; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; + } + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; + } + static generate(status, errorResponse, message, headers) { + if (!status) { + return new APIConnectionError({ cause: castToError(errorResponse) }); + } + const error = errorResponse?.['error']; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new APIError(status, error, message, headers); + } +} +export class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + this.status = undefined; + } +} +export class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + this.status = undefined; + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } +} +export class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} +export class BadRequestError extends APIError { + constructor() { + super(...arguments); + this.status = 400; + } +} +export class AuthenticationError extends APIError { + constructor() { + super(...arguments); + this.status = 401; + } +} +export class PermissionDeniedError extends APIError { + constructor() { + super(...arguments); + this.status = 403; + } +} +export class NotFoundError extends APIError { + constructor() { + super(...arguments); + this.status = 404; + } +} +export class ConflictError extends APIError { + constructor() { + super(...arguments); + this.status = 409; + } +} +export class UnprocessableEntityError extends APIError { + constructor() { + super(...arguments); + this.status = 422; + } +} +export class RateLimitError extends APIError { + constructor() { + super(...arguments); + this.status = 429; + } +} +export class InternalServerError extends APIError { +} +//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/node_modules/openai/error.mjs.map b/node_modules/openai/error.mjs.map new file mode 100644 index 0000000..80bd4fe --- /dev/null +++ b/node_modules/openai/error.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"error.mjs","sourceRoot":"","sources":["src/error.ts"],"names":[],"mappings":"AAAA,qDAAqD;OAE9C,EAAE,WAAW,EAAW;AAE/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,CAAC;CAAA;AAED,MAAM,OAAO,aAAc,SAAQ,QAAQ;IAA3C;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAED,MAAM,OAAO,wBAAyB,SAAQ,QAAQ;IAAtD;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAED,MAAM,OAAO,cAAe,SAAQ,QAAQ;IAA5C;;QACoB,WAAM,GAAQ,GAAG,CAAC;IACtC,CAAC;CAAA;AAED,MAAM,OAAO,mBAAoB,SAAQ,QAAQ;CAAG"} \ No newline at end of file diff --git a/node_modules/openai/index.d.mts b/node_modules/openai/index.d.mts new file mode 100644 index 0000000..1a8a826 --- /dev/null +++ b/node_modules/openai/index.d.mts @@ -0,0 +1,193 @@ +import * as Core from "./core.js"; +import * as Pagination from "./pagination.js"; +import * as Errors from "./error.js"; +import { type Agent } from "./_shims/index.js"; +import * as Uploads from "./uploads.js"; +import * as API from 'openai/resources/index'; +export interface ClientOptions { + /** + * Defaults to process.env['OPENAI_API_KEY']. + */ + apiKey?: string | undefined; + /** + * Defaults to process.env['OPENAI_ORG_ID']. + */ + organization?: string | null | undefined; + /** + * Override the default base URL for the API, e.g., "https://api.example.com/v2/" + * + * Defaults to process.env['OPENAI_BASE_URL']. + */ + baseURL?: string | null | undefined; + /** + * The maximum amount of time (in milliseconds) that the client should wait for a response + * from the server before timing out a single request. + * + * Note that request timeouts are retried by default, so in a worst-case scenario you may wait + * much longer than this timeout before the promise succeeds or fails. + */ + timeout?: number; + /** + * An HTTP agent used to manage HTTP(S) connections. + * + * If not provided, an agent will be constructed by default in the Node.js environment, + * otherwise no agent is used. + */ + httpAgent?: Agent; + /** + * Specify a custom `fetch` function implementation. + * + * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is + * defined globally. + */ + fetch?: Core.Fetch | undefined; + /** + * The maximum number of times that the client will retry a request in case of a + * temporary failure, like a network error or a 5XX error from the server. + * + * @default 2 + */ + maxRetries?: number; + /** + * Default headers to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * header to `undefined` or `null` in request options. + */ + defaultHeaders?: Core.Headers; + /** + * Default query parameters to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * param to `undefined` in request options. + */ + defaultQuery?: Core.DefaultQuery; + /** + * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * Only set this option to `true` if you understand the risks and have appropriate mitigations in place. + */ + dangerouslyAllowBrowser?: boolean; +} +/** API Client for interfacing with the OpenAI API. */ +export declare class OpenAI extends Core.APIClient { + apiKey: string; + organization: string | null; + private _options; + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL, apiKey, organization, ...opts }?: ClientOptions); + completions: API.Completions; + chat: API.Chat; + embeddings: API.Embeddings; + files: API.Files; + images: API.Images; + audio: API.Audio; + moderations: API.Moderations; + models: API.Models; + fineTuning: API.FineTuning; + beta: API.Beta; + protected defaultQuery(): Core.DefaultQuery | undefined; + protected defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers; + protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers; + static OpenAI: typeof OpenAI; + static OpenAIError: typeof Errors.OpenAIError; + static APIError: typeof Errors.APIError; + static APIConnectionError: typeof Errors.APIConnectionError; + static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError; + static APIUserAbortError: typeof Errors.APIUserAbortError; + static NotFoundError: typeof Errors.NotFoundError; + static ConflictError: typeof Errors.ConflictError; + static RateLimitError: typeof Errors.RateLimitError; + static BadRequestError: typeof Errors.BadRequestError; + static AuthenticationError: typeof Errors.AuthenticationError; + static InternalServerError: typeof Errors.InternalServerError; + static PermissionDeniedError: typeof Errors.PermissionDeniedError; + static UnprocessableEntityError: typeof Errors.UnprocessableEntityError; +} +export declare const OpenAIError: typeof Errors.OpenAIError, APIError: typeof Errors.APIError, APIConnectionError: typeof Errors.APIConnectionError, APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError, APIUserAbortError: typeof Errors.APIUserAbortError, NotFoundError: typeof Errors.NotFoundError, ConflictError: typeof Errors.ConflictError, RateLimitError: typeof Errors.RateLimitError, BadRequestError: typeof Errors.BadRequestError, AuthenticationError: typeof Errors.AuthenticationError, InternalServerError: typeof Errors.InternalServerError, PermissionDeniedError: typeof Errors.PermissionDeniedError, UnprocessableEntityError: typeof Errors.UnprocessableEntityError; +export import toFile = Uploads.toFile; +export import fileFromPath = Uploads.fileFromPath; +export declare namespace OpenAI { + export import toFile = Uploads.toFile; + export import fileFromPath = Uploads.fileFromPath; + export import RequestOptions = Core.RequestOptions; + export import Page = Pagination.Page; + export import PageResponse = Pagination.PageResponse; + export import CursorPage = Pagination.CursorPage; + export import CursorPageParams = Pagination.CursorPageParams; + export import CursorPageResponse = Pagination.CursorPageResponse; + export import Completions = API.Completions; + export import Completion = API.Completion; + export import CompletionChoice = API.CompletionChoice; + export import CompletionUsage = API.CompletionUsage; + export import CompletionCreateParams = API.CompletionCreateParams; + export import CompletionCreateParamsNonStreaming = API.CompletionCreateParamsNonStreaming; + export import CompletionCreateParamsStreaming = API.CompletionCreateParamsStreaming; + export import Chat = API.Chat; + export import ChatCompletion = API.ChatCompletion; + export import ChatCompletionAssistantMessageParam = API.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = API.ChatCompletionChunk; + export import ChatCompletionContentPart = API.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = API.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = API.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = API.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = API.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = API.ChatCompletionMessage; + export import ChatCompletionMessageParam = API.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = API.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = API.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = API.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = API.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = API.ChatCompletionTokenLogprob; + export import ChatCompletionTool = API.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = API.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = API.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = API.ChatCompletionUserMessageParam; + export import ChatCompletionCreateParams = API.ChatCompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = API.ChatCompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = API.ChatCompletionCreateParamsStreaming; + export import Embeddings = API.Embeddings; + export import CreateEmbeddingResponse = API.CreateEmbeddingResponse; + export import Embedding = API.Embedding; + export import EmbeddingCreateParams = API.EmbeddingCreateParams; + export import Files = API.Files; + export import FileContent = API.FileContent; + export import FileDeleted = API.FileDeleted; + export import FileObject = API.FileObject; + export import FileObjectsPage = API.FileObjectsPage; + export import FileCreateParams = API.FileCreateParams; + export import FileListParams = API.FileListParams; + export import Images = API.Images; + export import Image = API.Image; + export import ImagesResponse = API.ImagesResponse; + export import ImageCreateVariationParams = API.ImageCreateVariationParams; + export import ImageEditParams = API.ImageEditParams; + export import ImageGenerateParams = API.ImageGenerateParams; + export import Audio = API.Audio; + export import Moderations = API.Moderations; + export import Moderation = API.Moderation; + export import ModerationCreateResponse = API.ModerationCreateResponse; + export import ModerationCreateParams = API.ModerationCreateParams; + export import Models = API.Models; + export import Model = API.Model; + export import ModelDeleted = API.ModelDeleted; + export import ModelsPage = API.ModelsPage; + export import FineTuning = API.FineTuning; + export import Beta = API.Beta; + export import FunctionDefinition = API.FunctionDefinition; + export import FunctionParameters = API.FunctionParameters; +} +export default OpenAI; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/index.d.ts b/node_modules/openai/index.d.ts new file mode 100644 index 0000000..1a8a826 --- /dev/null +++ b/node_modules/openai/index.d.ts @@ -0,0 +1,193 @@ +import * as Core from "./core.js"; +import * as Pagination from "./pagination.js"; +import * as Errors from "./error.js"; +import { type Agent } from "./_shims/index.js"; +import * as Uploads from "./uploads.js"; +import * as API from 'openai/resources/index'; +export interface ClientOptions { + /** + * Defaults to process.env['OPENAI_API_KEY']. + */ + apiKey?: string | undefined; + /** + * Defaults to process.env['OPENAI_ORG_ID']. + */ + organization?: string | null | undefined; + /** + * Override the default base URL for the API, e.g., "https://api.example.com/v2/" + * + * Defaults to process.env['OPENAI_BASE_URL']. + */ + baseURL?: string | null | undefined; + /** + * The maximum amount of time (in milliseconds) that the client should wait for a response + * from the server before timing out a single request. + * + * Note that request timeouts are retried by default, so in a worst-case scenario you may wait + * much longer than this timeout before the promise succeeds or fails. + */ + timeout?: number; + /** + * An HTTP agent used to manage HTTP(S) connections. + * + * If not provided, an agent will be constructed by default in the Node.js environment, + * otherwise no agent is used. + */ + httpAgent?: Agent; + /** + * Specify a custom `fetch` function implementation. + * + * If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is + * defined globally. + */ + fetch?: Core.Fetch | undefined; + /** + * The maximum number of times that the client will retry a request in case of a + * temporary failure, like a network error or a 5XX error from the server. + * + * @default 2 + */ + maxRetries?: number; + /** + * Default headers to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * header to `undefined` or `null` in request options. + */ + defaultHeaders?: Core.Headers; + /** + * Default query parameters to include with every request to the API. + * + * These can be removed in individual requests by explicitly setting the + * param to `undefined` in request options. + */ + defaultQuery?: Core.DefaultQuery; + /** + * By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + * Only set this option to `true` if you understand the risks and have appropriate mitigations in place. + */ + dangerouslyAllowBrowser?: boolean; +} +/** API Client for interfacing with the OpenAI API. */ +export declare class OpenAI extends Core.APIClient { + apiKey: string; + organization: string | null; + private _options; + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL, apiKey, organization, ...opts }?: ClientOptions); + completions: API.Completions; + chat: API.Chat; + embeddings: API.Embeddings; + files: API.Files; + images: API.Images; + audio: API.Audio; + moderations: API.Moderations; + models: API.Models; + fineTuning: API.FineTuning; + beta: API.Beta; + protected defaultQuery(): Core.DefaultQuery | undefined; + protected defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers; + protected authHeaders(opts: Core.FinalRequestOptions): Core.Headers; + static OpenAI: typeof OpenAI; + static OpenAIError: typeof Errors.OpenAIError; + static APIError: typeof Errors.APIError; + static APIConnectionError: typeof Errors.APIConnectionError; + static APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError; + static APIUserAbortError: typeof Errors.APIUserAbortError; + static NotFoundError: typeof Errors.NotFoundError; + static ConflictError: typeof Errors.ConflictError; + static RateLimitError: typeof Errors.RateLimitError; + static BadRequestError: typeof Errors.BadRequestError; + static AuthenticationError: typeof Errors.AuthenticationError; + static InternalServerError: typeof Errors.InternalServerError; + static PermissionDeniedError: typeof Errors.PermissionDeniedError; + static UnprocessableEntityError: typeof Errors.UnprocessableEntityError; +} +export declare const OpenAIError: typeof Errors.OpenAIError, APIError: typeof Errors.APIError, APIConnectionError: typeof Errors.APIConnectionError, APIConnectionTimeoutError: typeof Errors.APIConnectionTimeoutError, APIUserAbortError: typeof Errors.APIUserAbortError, NotFoundError: typeof Errors.NotFoundError, ConflictError: typeof Errors.ConflictError, RateLimitError: typeof Errors.RateLimitError, BadRequestError: typeof Errors.BadRequestError, AuthenticationError: typeof Errors.AuthenticationError, InternalServerError: typeof Errors.InternalServerError, PermissionDeniedError: typeof Errors.PermissionDeniedError, UnprocessableEntityError: typeof Errors.UnprocessableEntityError; +export import toFile = Uploads.toFile; +export import fileFromPath = Uploads.fileFromPath; +export declare namespace OpenAI { + export import toFile = Uploads.toFile; + export import fileFromPath = Uploads.fileFromPath; + export import RequestOptions = Core.RequestOptions; + export import Page = Pagination.Page; + export import PageResponse = Pagination.PageResponse; + export import CursorPage = Pagination.CursorPage; + export import CursorPageParams = Pagination.CursorPageParams; + export import CursorPageResponse = Pagination.CursorPageResponse; + export import Completions = API.Completions; + export import Completion = API.Completion; + export import CompletionChoice = API.CompletionChoice; + export import CompletionUsage = API.CompletionUsage; + export import CompletionCreateParams = API.CompletionCreateParams; + export import CompletionCreateParamsNonStreaming = API.CompletionCreateParamsNonStreaming; + export import CompletionCreateParamsStreaming = API.CompletionCreateParamsStreaming; + export import Chat = API.Chat; + export import ChatCompletion = API.ChatCompletion; + export import ChatCompletionAssistantMessageParam = API.ChatCompletionAssistantMessageParam; + export import ChatCompletionChunk = API.ChatCompletionChunk; + export import ChatCompletionContentPart = API.ChatCompletionContentPart; + export import ChatCompletionContentPartImage = API.ChatCompletionContentPartImage; + export import ChatCompletionContentPartText = API.ChatCompletionContentPartText; + export import ChatCompletionFunctionCallOption = API.ChatCompletionFunctionCallOption; + export import ChatCompletionFunctionMessageParam = API.ChatCompletionFunctionMessageParam; + export import ChatCompletionMessage = API.ChatCompletionMessage; + export import ChatCompletionMessageParam = API.ChatCompletionMessageParam; + export import ChatCompletionMessageToolCall = API.ChatCompletionMessageToolCall; + export import ChatCompletionNamedToolChoice = API.ChatCompletionNamedToolChoice; + export import ChatCompletionRole = API.ChatCompletionRole; + export import ChatCompletionSystemMessageParam = API.ChatCompletionSystemMessageParam; + export import ChatCompletionTokenLogprob = API.ChatCompletionTokenLogprob; + export import ChatCompletionTool = API.ChatCompletionTool; + export import ChatCompletionToolChoiceOption = API.ChatCompletionToolChoiceOption; + export import ChatCompletionToolMessageParam = API.ChatCompletionToolMessageParam; + export import ChatCompletionUserMessageParam = API.ChatCompletionUserMessageParam; + export import ChatCompletionCreateParams = API.ChatCompletionCreateParams; + export import ChatCompletionCreateParamsNonStreaming = API.ChatCompletionCreateParamsNonStreaming; + export import ChatCompletionCreateParamsStreaming = API.ChatCompletionCreateParamsStreaming; + export import Embeddings = API.Embeddings; + export import CreateEmbeddingResponse = API.CreateEmbeddingResponse; + export import Embedding = API.Embedding; + export import EmbeddingCreateParams = API.EmbeddingCreateParams; + export import Files = API.Files; + export import FileContent = API.FileContent; + export import FileDeleted = API.FileDeleted; + export import FileObject = API.FileObject; + export import FileObjectsPage = API.FileObjectsPage; + export import FileCreateParams = API.FileCreateParams; + export import FileListParams = API.FileListParams; + export import Images = API.Images; + export import Image = API.Image; + export import ImagesResponse = API.ImagesResponse; + export import ImageCreateVariationParams = API.ImageCreateVariationParams; + export import ImageEditParams = API.ImageEditParams; + export import ImageGenerateParams = API.ImageGenerateParams; + export import Audio = API.Audio; + export import Moderations = API.Moderations; + export import Moderation = API.Moderation; + export import ModerationCreateResponse = API.ModerationCreateResponse; + export import ModerationCreateParams = API.ModerationCreateParams; + export import Models = API.Models; + export import Model = API.Model; + export import ModelDeleted = API.ModelDeleted; + export import ModelsPage = API.ModelsPage; + export import FineTuning = API.FineTuning; + export import Beta = API.Beta; + export import FunctionDefinition = API.FunctionDefinition; + export import FunctionParameters = API.FunctionParameters; +} +export default OpenAI; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/index.d.ts.map b/node_modules/openai/index.d.ts.map new file mode 100644 index 0000000..f5965f1 --- /dev/null +++ b/node_modules/openai/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,UAAU,MAAM,cAAc,CAAC;AAC3C,OAAO,KAAK,MAAM,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC;AACrC,OAAO,KAAK,GAAG,MAAM,wBAAwB,CAAC;AAE9C,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE5B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAEzC;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAEpC;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;;OAKG;IACH,SAAS,CAAC,EAAE,KAAK,CAAC;IAElB;;;;;OAKG;I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AAM,QAAQ,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAClC,MAAM,QAAQ,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAChC,MAAM,QAAQ,cAAc,GAAG,GAAG,CAAC,cAAc,CAAC;IAClD,MAAM,QAAQ,0BAA0B,GAAG,GAAG,CAAC,0BAA0B,CAAC;IAC1E,MAAM,QAAQ,eAAe,GAAG,GAAG,CAAC,eAAe,CAAC;IACpD,MAAM,QAAQ,mBAAmB,GAAG,GAAG,CAAC,mBAAmB,CAAC;IAE5D,MAAM,QAAQ,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAEhC,MAAM,QAAQ,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAC5C,MAAM,QAAQ,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAC1C,MAAM,QAAQ,wBAAwB,GAAG,GAAG,CAAC,wBAAwB,CAAC;IACtE,MAAM,QAAQ,sBAAsB,GAAG,GAAG,CAAC,sBAAsB,CAAC;IAElE,MAAM,QAAQ,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAClC,MAAM,QAAQ,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAChC,MAAM,QAAQ,YAAY,GAAG,GAAG,CAAC,YAAY,CAAC;IAC9C,MAAM,QAAQ,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE1C,MAAM,QAAQ,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE1C,MAAM,QAAQ,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IAE9B,MAAM,QAAQ,kBAAkB,GAAG,GAAG,CAAC,kBAAkB,CAAC;IAC1D,MAAM,QAAQ,kBAAkB,GAAG,GAAG,CAAC,kBAAkB,CAAC;CAC3D;AAED,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/index.js b/node_modules/openai/index.js new file mode 100644 index 0000000..a5f96bf --- /dev/null +++ b/node_modules/openai/index.js @@ -0,0 +1,138 @@ +"use strict"; +// File generated from our OpenAPI spec by Stainless. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fileFromPath = exports.toFile = exports.UnprocessableEntityError = exports.PermissionDeniedError = exports.InternalServerError = exports.AuthenticationError = exports.BadRequestError = exports.RateLimitError = exports.ConflictError = exports.NotFoundError = exports.APIUserAbortError = exports.APIConnectionTimeoutError = exports.APIConnectionError = exports.APIError = exports.OpenAIError = exports.OpenAI = void 0; +const Core = __importStar(require("./core.js")); +const Pagination = __importStar(require("./pagination.js")); +const Errors = __importStar(require("./error.js")); +const Uploads = __importStar(require("./uploads.js")); +const API = __importStar(require("openai/resources/index")); +/** API Client for interfacing with the OpenAI API. */ +class OpenAI extends Core.APIClient { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, ...opts } = {}) { + if (apiKey === undefined) { + throw new Errors.OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); + } + const options = { + apiKey, + organization, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1`, + }; + if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { + throw new Errors.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); + } + super({ + baseURL: options.baseURL, + timeout: options.timeout ?? 600000 /* 10 minutes */, + httpAgent: options.httpAgent, + maxRetries: options.maxRetries, + fetch: options.fetch, + }); + this.completions = new API.Completions(this); + this.chat = new API.Chat(this); + this.embeddings = new API.Embeddings(this); + this.files = new API.Files(this); + this.images = new API.Images(this); + this.audio = new API.Audio(this); + this.moderations = new API.Moderations(this); + this.models = new API.Models(this); + this.fineTuning = new API.FineTuning(this); + this.beta = new API.Beta(this); + this._options = options; + this.apiKey = apiKey; + this.organization = organization; + } + defaultQuery() { + return this._options.defaultQuery; + } + defaultHeaders(opts) { + return { + ...super.defaultHeaders(opts), + 'OpenAI-Organization': this.organization, + ...this._options.defaultHeaders, + }; + } + authHeaders(opts) { + return { Authorization: `Bearer ${this.apiKey}` }; + } +} +exports.OpenAI = OpenAI; +_a = OpenAI; +OpenAI.OpenAI = _a; +OpenAI.OpenAIError = Errors.OpenAIError; +OpenAI.APIError = Errors.APIError; +OpenAI.APIConnectionError = Errors.APIConnectionError; +OpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError; +OpenAI.APIUserAbortError = Errors.APIUserAbortError; +OpenAI.NotFoundError = Errors.NotFoundError; +OpenAI.ConflictError = Errors.ConflictError; +OpenAI.RateLimitError = Errors.RateLimitError; +OpenAI.BadRequestError = Errors.BadRequestError; +OpenAI.AuthenticationError = Errors.AuthenticationError; +OpenAI.InternalServerError = Errors.InternalServerError; +OpenAI.PermissionDeniedError = Errors.PermissionDeniedError; +OpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError; +exports.OpenAIError = Errors.OpenAIError, exports.APIError = Errors.APIError, exports.APIConnectionError = Errors.APIConnectionError, exports.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError, exports.APIUserAbortError = Errors.APIUserAbortError, exports.NotFoundError = Errors.NotFoundError, exports.ConflictError = Errors.ConflictError, exports.RateLimitError = Errors.RateLimitError, exports.BadRequestError = Errors.BadRequestError, exports.AuthenticationError = Errors.AuthenticationError, exports.InternalServerError = Errors.InternalServerError, exports.PermissionDeniedError = Errors.PermissionDeniedError, exports.UnprocessableEntityError = Errors.UnprocessableEntityError; +exports.toFile = Uploads.toFile; +exports.fileFromPath = Uploads.fileFromPath; +(function (OpenAI) { + // Helper functions + OpenAI.toFile = Uploads.toFile; + OpenAI.fileFromPath = Uploads.fileFromPath; + OpenAI.Page = Pagination.Page; + OpenAI.CursorPage = Pagination.CursorPage; + OpenAI.Completions = API.Completions; + OpenAI.Chat = API.Chat; + OpenAI.Embeddings = API.Embeddings; + OpenAI.Files = API.Files; + OpenAI.FileObjectsPage = API.FileObjectsPage; + OpenAI.Images = API.Images; + OpenAI.Audio = API.Audio; + OpenAI.Moderations = API.Moderations; + OpenAI.Models = API.Models; + OpenAI.ModelsPage = API.ModelsPage; + OpenAI.FineTuning = API.FineTuning; + OpenAI.Beta = API.Beta; +})(OpenAI = exports.OpenAI || (exports.OpenAI = {})); +exports = module.exports = OpenAI; +exports.default = OpenAI; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/openai/index.js.map b/node_modules/openai/index.js.map new file mode 100644 index 0000000..e441254 --- /dev/null +++ b/node_modules/openai/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":";AAAA,qDAAqD;;;;;;;;;;;;;;;;;;;;;;;;;;;AAErD,gDAA+B;AAC/B,4DAA2C;AAC3C,mDAAkC;AAElC,sDAAqC;AACrC,4DAA8C;AA4E9C,sDAAsD;AACtD,MAAa,MAAO,SAAQ,IAAI,CAAC,SAAS;IAMxC;;;;;;;;;;;;;OAaG;IACH,YAAY,EACV,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,EACzC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,EACvC,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,IAAI,EACpD,GAAG,IAAI,KACU,EAAE;QACnB,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,MAAM,IAAI,MAAM,CAAC,WAAW,CAC1B,oLAAoL,CACrL,CAAC;SACH;QAED,MAAM,OAAO,GAAkB;YAC7B,MAAM;YACN,YAAY;YACZ,GAAG,IAAI;YACP,OAAO,EAAE,OAAO,IAAI,2BAA2B;SAChD,CAAC;QAEF,IAAI,CAAC,OAAO,CAAC,uBAAuB,IAAI,IAAI,CAAC,kBAAkB,EAAE,EAAE;YACjE,MAAM,IAAI,MAAM,CAAC,W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M,0BAAC;AAEG,QAAA,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;AACxB,QAAA,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;AAElD,WAAiB,MAAM;IACrB,mBAAmB;IACL,aAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IACxB,mBAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAIpC,WAAI,GAAG,UAAU,CAAC,IAAI,CAAC;IAGvB,iBAAU,GAAG,UAAU,CAAC,UAAU,CAAC;IAInC,kBAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAQ9B,WAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IAwBhB,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAK5B,YAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAIlB,sBAAe,GAAG,GAAG,CAAC,eAAe,CAAC;IAItC,aAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAOpB,YAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAElB,kBAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAK9B,aAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAGpB,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE5B,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE5B,WAAI,GAAG,GAAG,CAAC,IAAI,CAAC;AAIhC,CAAC,EApFgB,MAAM,GAAN,cAAM,KAAN,cAAM,QAoFtB;AAED,kBAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/index.mjs b/node_modules/openai/index.mjs new file mode 100644 index 0000000..bbc5c42 --- /dev/null +++ b/node_modules/openai/index.mjs @@ -0,0 +1,110 @@ +// File generated from our OpenAPI spec by Stainless. +var _a; +import * as Core from "./core.mjs"; +import * as Pagination from "./pagination.mjs"; +import * as Errors from "./error.mjs"; +import * as Uploads from "./uploads.mjs"; +import * as API from 'openai/resources/index'; +/** API Client for interfacing with the OpenAI API. */ +export class OpenAI extends Core.APIClient { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, ...opts } = {}) { + if (apiKey === undefined) { + throw new Errors.OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); + } + const options = { + apiKey, + organization, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1`, + }; + if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) { + throw new Errors.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); + } + super({ + baseURL: options.baseURL, + timeout: options.timeout ?? 600000 /* 10 minutes */, + httpAgent: options.httpAgent, + maxRetries: options.maxRetries, + fetch: options.fetch, + }); + this.completions = new API.Completions(this); + this.chat = new API.Chat(this); + this.embeddings = new API.Embeddings(this); + this.files = new API.Files(this); + this.images = new API.Images(this); + this.audio = new API.Audio(this); + this.moderations = new API.Moderations(this); + this.models = new API.Models(this); + this.fineTuning = new API.FineTuning(this); + this.beta = new API.Beta(this); + this._options = options; + this.apiKey = apiKey; + this.organization = organization; + } + defaultQuery() { + return this._options.defaultQuery; + } + defaultHeaders(opts) { + return { + ...super.defaultHeaders(opts), + 'OpenAI-Organization': this.organization, + ...this._options.defaultHeaders, + }; + } + authHeaders(opts) { + return { Authorization: `Bearer ${this.apiKey}` }; + } +} +_a = OpenAI; +OpenAI.OpenAI = _a; +OpenAI.OpenAIError = Errors.OpenAIError; +OpenAI.APIError = Errors.APIError; +OpenAI.APIConnectionError = Errors.APIConnectionError; +OpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError; +OpenAI.APIUserAbortError = Errors.APIUserAbortError; +OpenAI.NotFoundError = Errors.NotFoundError; +OpenAI.ConflictError = Errors.ConflictError; +OpenAI.RateLimitError = Errors.RateLimitError; +OpenAI.BadRequestError = Errors.BadRequestError; +OpenAI.AuthenticationError = Errors.AuthenticationError; +OpenAI.InternalServerError = Errors.InternalServerError; +OpenAI.PermissionDeniedError = Errors.PermissionDeniedError; +OpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError; +export const { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } = Errors; +export var toFile = Uploads.toFile; +export var fileFromPath = Uploads.fileFromPath; +(function (OpenAI) { + // Helper functions + OpenAI.toFile = Uploads.toFile; + OpenAI.fileFromPath = Uploads.fileFromPath; + OpenAI.Page = Pagination.Page; + OpenAI.CursorPage = Pagination.CursorPage; + OpenAI.Completions = API.Completions; + OpenAI.Chat = API.Chat; + OpenAI.Embeddings = API.Embeddings; + OpenAI.Files = API.Files; + OpenAI.FileObjectsPage = API.FileObjectsPage; + OpenAI.Images = API.Images; + OpenAI.Audio = API.Audio; + OpenAI.Moderations = API.Moderations; + OpenAI.Models = API.Models; + OpenAI.ModelsPage = API.ModelsPage; + OpenAI.FineTuning = API.FineTuning; + OpenAI.Beta = API.Beta; +})(OpenAI || (OpenAI = {})); +export default OpenAI; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/openai/index.mjs.map b/node_modules/openai/index.mjs.map new file mode 100644 index 0000000..94b2746 --- /dev/null +++ b/node_modules/openai/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA,qDAAqD;;OAE9C,KAAK,IAAI;OACT,KAAK,UAAU;OACf,KAAK,MAAM;OAEX,KAAK,OAAO;OACZ,KAAK,GAAG,MAAM,wBAAwB;AA4E7C,sDAAsD;AACtD,MAAM,OAAO,MAAO,SAAQ,IAAI,CAAC,SAAS;IAMxC;;;;;;;;;;;;;OAaG;IACH,YAAY,EACV,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,EACzC,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,EACvC,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,IAAI,IAAI,EACpD,GAAG,IAAI,KACU,EAAE;QACnB,IAAI,MAAM,KAAK,SAAS,EAAE;YACxB,MAAM,IAAI,MAAM,CAAC,WAAW,CAC1B,oLAAoL,CACrL,CAAC;SACH;QAED,MAAM,OAAO,GAAkB;YAC7B,MAAM;YACN,YAAY;YACZ,GAAG,IAAI;YACP,OAAO,EAAE,OAAO,IAAI,2BAA2B;SAChD,CAAC;QAEF,IAAI,CAAC,OAAO,CAAC,uBAAuB,IAAI,IAAI,CAAC,kBAAkB,EAAE,EAAE;YACjE,MAAM,IAAI,MAAM,CAAC,WAAW,CAC1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,OAAO,CAAC,MAAM,CAAC;IACxB,mBAAY,GAAG,OAAO,CAAC,YAAY,CAAC;IAIpC,WAAI,GAAG,UAAU,CAAC,IAAI,CAAC;IAGvB,iBAAU,GAAG,UAAU,CAAC,UAAU,CAAC;IAInC,kBAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAQ9B,WAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IAwBhB,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAK5B,YAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAIlB,sBAAe,GAAG,GAAG,CAAC,eAAe,CAAC;IAItC,aAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAOpB,YAAK,GAAG,GAAG,CAAC,KAAK,CAAC;IAElB,kBAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IAK9B,aAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAGpB,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE5B,iBAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IAE5B,WAAI,GAAG,GAAG,CAAC,IAAI,CAAC;AAIhC,CAAC,EApFgB,MAAM,KAAN,MAAM,QAoFtB;AAED,eAAe,MAAM,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts b/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts new file mode 100644 index 0000000..c05aa95 --- /dev/null +++ b/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts @@ -0,0 +1,114 @@ + +import * as Core from 'openai/core'; +import { type CompletionUsage } from 'openai/resources/completions'; +import { type Completions, type ChatCompletion, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionCreateParams } from 'openai/resources/chat/completions'; +import { APIUserAbortError, OpenAIError } from 'openai/error'; +import { type BaseFunctionsArgs } from "./RunnableFunction.js"; +import { ChatCompletionFunctionRunnerParams, ChatCompletionToolRunnerParams } from "./ChatCompletionRunner.js"; +import { ChatCompletionStreamingFunctionRunnerParams, ChatCompletionStreamingToolRunnerParams } from "./ChatCompletionStreamingRunner.js"; +export interface RunnerOptions extends Core.RequestOptions { + /** How many requests to make before canceling. Default 10. */ + maxChatCompletions?: number; +} +export declare abstract class AbstractChatCompletionRunner = AbstractChatCompletionRunnerEvents> { + #private; + controller: AbortController; + protected _chatCompletions: ChatCompletion[]; + messages: ChatCompletionMessageParam[]; + constructor(); + protected _run(executor: () => Promise): void; + protected _addChatCompletion(chatCompletion: ChatCompletion): ChatCompletion; + protected _addMessage(message: ChatCompletionMessageParam, emit?: boolean): void; + protected _connected(): void; + get ended(): boolean; + get errored(): boolean; + get aborted(): boolean; + abort(): void; + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event: Event, listener: ListenerForEvent): this; + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event: Event, listener: ListenerForEvent): this; + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event: Event, listener: ListenerForEvent): this; + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event: Event): Promise extends [infer Param] ? Param : EventParameters extends [] ? void : EventParameters>; + done(): Promise; + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + finalChatCompletion(): Promise; + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + finalContent(): Promise; + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + finalMessage(): Promise; + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + finalFunctionCall(): Promise; + finalFunctionCallResult(): Promise; + totalUsage(): Promise; + allChatCompletions(): ChatCompletion[]; + protected _emit(event: Event, ...args: EventParameters): void; + protected _emitFinal(): void; + protected _createChatCompletion(completions: Completions, params: ChatCompletionCreateParams, options?: Core.RequestOptions): Promise; + protected _runChatCompletion(completions: Completions, params: ChatCompletionCreateParams, options?: Core.RequestOptions): Promise; + protected _runFunctions(completions: Completions, params: ChatCompletionFunctionRunnerParams | ChatCompletionStreamingFunctionRunnerParams, options?: RunnerOptions): Promise; + protected _runTools(completions: Completions, params: ChatCompletionToolRunnerParams | ChatCompletionStreamingToolRunnerParams, options?: RunnerOptions): Promise; +} +type CustomEvents = { + [k in Event]: k extends keyof AbstractChatCompletionRunnerEvents ? AbstractChatCompletionRunnerEvents[k] : (...args: any[]) => void; +}; +type ListenerForEvent, Event extends keyof Events> = Event extends (keyof AbstractChatCompletionRunnerEvents) ? AbstractChatCompletionRunnerEvents[Event] : Events[Event]; +type EventParameters, Event extends keyof Events> = Parameters>; +export interface AbstractChatCompletionRunnerEvents { + connect: () => void; + functionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void; + message: (message: ChatCompletionMessageParam) => void; + chatCompletion: (completion: ChatCompletion) => void; + finalContent: (contentSnapshot: string) => void; + finalMessage: (message: ChatCompletionMessageParam) => void; + finalChatCompletion: (completion: ChatCompletion) => void; + finalFunctionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void; + functionCallResult: (content: string) => void; + finalFunctionCallResult: (content: string) => void; + error: (error: OpenAIError) => void; + abort: (error: APIUserAbortError) => void; + end: () => void; + totalUsage: (usage: CompletionUsage) => void; +} +export {}; +//# sourceMappingURL=AbstractChatCompletionRunner.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts.map b/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts.map new file mode 100644 index 0000000..551b705 --- /dev/null +++ b/node_modules/openai/lib/AbstractChatCompletionRunner.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractChatCompletionRunner.d.ts","sourceRoot":"","sources":["../src/lib/AbstractChatCompletionRunner.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AACpC,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,cAAc,EACnB,KAAK,qBAAqB,EAC1B,KAAK,0BAA0B,EAC/B,KAAK,0BAA0B,EAEhC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC9D,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,kCAAkC,EAAE,8BAA8B,EAAE,MAAM,wBAAwB,CAAC;AAC5G,OAAO,EACL,2CAA2C,EAC3C,uCAAuC,EACxC,MAAM,iCAAiC,CAAC;AAIzC,MAAM,WAAW,aAAc,SAAQ,IAAI,CAAC,cAAc;IACxD,8DAA8D;IAC9D,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC7B;AAED,8BAAsB,4BAA4B,CAChD,MAAM,SAAS,YAAY,CAAC,GAAG,CAAC,GAAG,kCAAkC;;IAErE,UAAU,EAAE,eAAe,CAAyB;IAYpD,SAAS,CAAC,gBAAgB,EAAE,cAAc,EAAE,CAAM;IAClD,QAAQ,EAAE,0BAA0B,EAAE,CAAM;;IA0B5C,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,GAAG,CAA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C,KAAK,EAAE,eAAe,KAAK,IAAI,CAAC;CAC9C"} \ No newline at end of file diff --git a/node_modules/openai/lib/AbstractChatCompletionRunner.js b/node_modules/openai/lib/AbstractChatCompletionRunner.js new file mode 100644 index 0000000..3ff28ce --- /dev/null +++ b/node_modules/openai/lib/AbstractChatCompletionRunner.js @@ -0,0 +1,519 @@ +"use strict"; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_connectedPromise, _AbstractChatCompletionRunner_resolveConnectedPromise, _AbstractChatCompletionRunner_rejectConnectedPromise, _AbstractChatCompletionRunner_endPromise, _AbstractChatCompletionRunner_resolveEndPromise, _AbstractChatCompletionRunner_rejectEndPromise, _AbstractChatCompletionRunner_listeners, _AbstractChatCompletionRunner_ended, _AbstractChatCompletionRunner_errored, _AbstractChatCompletionRunner_aborted, _AbstractChatCompletionRunner_catchingPromiseCreated, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_handleError, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AbstractChatCompletionRunner = void 0; +const error_1 = require("openai/error"); +const RunnableFunction_1 = require("./RunnableFunction.js"); +const chatCompletionUtils_1 = require("./chatCompletionUtils.js"); +const DEFAULT_MAX_CHAT_COMPLETIONS = 10; +class AbstractChatCompletionRunner { + constructor() { + _AbstractChatCompletionRunner_instances.add(this); + this.controller = new AbortController(); + _AbstractChatCompletionRunner_connectedPromise.set(this, void 0); + _AbstractChatCompletionRunner_resolveConnectedPromise.set(this, () => { }); + _AbstractChatCompletionRunner_rejectConnectedPromise.set(this, () => { }); + _AbstractChatCompletionRunner_endPromise.set(this, void 0); + _AbstractChatCompletionRunner_resolveEndPromise.set(this, () => { }); + _AbstractChatCompletionRunner_rejectEndPromise.set(this, () => { }); + _AbstractChatCompletionRunner_listeners.set(this, {}); + this._chatCompletions = []; + this.messages = []; + _AbstractChatCompletionRunner_ended.set(this, false); + _AbstractChatCompletionRunner_errored.set(this, false); + _AbstractChatCompletionRunner_aborted.set(this, false); + _AbstractChatCompletionRunner_catchingPromiseCreated.set(this, false); + _AbstractChatCompletionRunner_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_errored, true, "f"); + if (error instanceof Error && error.name === 'AbortError') { + error = new error_1.APIUserAbortError(); + } + if (error instanceof error_1.APIUserAbortError) { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof error_1.OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError = new error_1.OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new error_1.OpenAIError(String(error))); + }); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_endPromise, "f").catch(() => { }); + } + _run(executor) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _AbstractChatCompletionRunner_handleError, "f")); + }, 0); + } + _addChatCompletion(chatCompletion) { + this._chatCompletions.push(chatCompletion); + this._emit('chatCompletion', chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) + this._addMessage(message); + return chatCompletion; + } + _addMessage(message, emit = true) { + if (!('content' in message)) + message.content = null; + this.messages.push(message); + if (emit) { + this._emit('message', message); + if (((0, chatCompletionUtils_1.isFunctionMessage)(message) || (0, chatCompletionUtils_1.isToolMessage)(message)) && message.content) { + // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. + this._emit('functionCallResult', message.content); + } + else if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message.function_call) { + this._emit('functionCall', message.function_call); + } + else if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === 'function') { + this._emit('functionCall', tool_call.function); + } + } + } + } + } + _connected() { + if (this.ended) + return; + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_resolveConnectedPromise, "f").call(this); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _AbstractChatCompletionRunner_endPromise, "f"); + } + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + async finalChatCompletion() { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) + throw new error_1.OpenAIError('stream ended without producing a ChatCompletion'); + return completion; + } + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + } + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionCall() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + } + async finalFunctionCallResult() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + } + async totalUsage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + } + allChatCompletions() { + return [...this._chatCompletions]; + } + _emit(event, ...args) { + // make sure we don't emit any events after end + if (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_ended, "f")) { + return; + } + if (event === 'end') { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_ended, true, "f"); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) + this._emit('finalChatCompletion', completion); + const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + if (finalMessage) + this._emit('finalMessage', finalMessage); + const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + if (finalContent) + this._emit('finalContent', finalContent); + const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + if (finalFunctionCall) + this._emit('finalFunctionCall', finalFunctionCall); + const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + if (finalFunctionCallResult != null) + this._emit('finalFunctionCallResult', finalFunctionCallResult); + if (this._chatCompletions.some((c) => c.usage)) { + this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + } + } + async _createChatCompletion(completions, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + const chatCompletion = await completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addChatCompletion(chatCompletion); + } + async _runChatCompletion(completions, params, options) { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(completions, params, options); + } + async _runFunctions(completions, params, options) { + const role = 'function'; + const { function_call = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const functionsByName = {}; + for (const f of params.functions) { + functionsByName[f.name || f.function.name] = f; + } + const functions = params.functions.map((f) => ({ + name: f.name || f.function.name, + parameters: f.parameters, + description: f.description, + })); + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(completions, { + ...restParams, + function_call, + functions, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new error_1.OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.function_call) + return; + const { name, arguments: args } = message.function_call; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions + .map((f) => JSON.stringify(f.name)) + .join(', ')}. Please try again`; + this._addMessage({ role, name, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, name, content }); + continue; + } + let parsed; + try { + parsed = (0, RunnableFunction_1.isRunnableFunctionWithParse)(fn) ? await fn.parse(args) : args; + } + catch (error) { + this._addMessage({ + role, + name, + content: error instanceof Error ? error.message : String(error), + }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, name, content }); + if (singleFunctionToCall) + return; + } + } + async _runTools(completions, params, options) { + const role = 'tool'; + const { tool_choice = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const functionsByName = {}; + for (const f of params.tools) { + if (f.type === 'function') { + functionsByName[f.function.name || f.function.function.name] = f.function; + } + } + const tools = 'tools' in params ? + params.tools.map((t) => t.type === 'function' ? + { + type: 'function', + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters, + description: t.function.description, + }, + } + : t) + : undefined; + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(completions, { + ...restParams, + tool_choice, + tools, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new error_1.OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls) { + return; + } + for (const tool_call of message.tool_calls) { + if (tool_call.type !== 'function') + continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${tools + .map((f) => JSON.stringify(f.function.name)) + .join(', ')}. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + let parsed; + try { + parsed = (0, RunnableFunction_1.isRunnableFunctionWithParse)(fn) ? await fn.parse(args) : args; + } + catch (error) { + const content = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, tool_call_id, content }); + if (singleFunctionToCall) { + return; + } + } + } + return; + } +} +exports.AbstractChatCompletionRunner = AbstractChatCompletionRunner; +_AbstractChatCompletionRunner_connectedPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_endPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveEndPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectEndPromise = new WeakMap(), _AbstractChatCompletionRunner_listeners = new WeakMap(), _AbstractChatCompletionRunner_ended = new WeakMap(), _AbstractChatCompletionRunner_errored = new WeakMap(), _AbstractChatCompletionRunner_aborted = new WeakMap(), _AbstractChatCompletionRunner_catchingPromiseCreated = new WeakMap(), _AbstractChatCompletionRunner_handleError = new WeakMap(), _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; +}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if ((0, chatCompletionUtils_1.isAssistantMessage)(message)) { + return { ...message, content: message.content ?? null }; + } + } + throw new error_1.OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); +}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message?.function_call) { + return message.function_call; + } + if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message?.tool_calls?.length) { + return message.tool_calls.at(-1)?.function; + } + } + return; +}, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if ((0, chatCompletionUtils_1.isFunctionMessage)(message) && message.content != null) { + return message.content; + } + if ((0, chatCompletionUtils_1.isToolMessage)(message) && + message.content != null && + this.messages.some((x) => x.role === 'assistant' && + x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { + return message.content; + } + } + return; +}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { + const total = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } + } + return total; +}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { + if (params.n != null && params.n > 1) { + throw new error_1.OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); + } +}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { + return (typeof rawContent === 'string' ? rawContent + : rawContent === undefined ? 'undefined' + : JSON.stringify(rawContent)); +}; +//# sourceMappingURL=AbstractChatCompletionRunner.js.map \ No newline at end of file diff --git a/node_modules/openai/lib/AbstractChatCompletionRunner.js.map b/node_modules/openai/lib/AbstractChatCompletionRunner.js.map new file mode 100644 index 0000000..6adf79b --- /dev/null +++ b/node_modules/openai/lib/AbstractChatCompletionRunner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractChatCompletionRunner.js","sourceRoot":"","sources":["../src/lib/AbstractChatCompletionRunner.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAUA,wCAA8D;AAC9D,4DAI4B;AAM5B,kEAA6F;AAE7F,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAMxC,MAAsB,4BAA4B;IAuBhD;;QApBA,eAAU,GAAoB,IAAI,eAAe,EAAE,CAAC;QAEpD,iEAAiC;QACjC,gEAAuC,GAAG,EAAE,GAAE,CAAC,EAAC;QAChD,+DAAwD,GAAG,EAAE,GAAE,CAAC,EAAC;QAEjE,2DAA2B;QAC3B,0DAAiC,GAAG,EAAE,GAAE,CAAC,EAAC;QAC1C,yDAAkD,GAAG,EAAE,GAAE,CAAC,EAAC;QAE3D,kDAA6E,EAAE,EAAC;QAEtE,qBAAgB,GAAqB,EAAE,CAAC;QAClD,aAAQ,GAAiC,EAAE,CAAC;QAE5C,8CAAS,KAAK,EAAC;QACf,gDAAW,KAAK,EAAC;QACjB,gDAAW,KAAK,EAAC;QACjB,+DAA0B,KAAK,EAAC;QAkRhC,oDAAe,CAAC,KAAc,EAAE,EAAE;YAChC,uBAAA,IAAI,yCAAY,IAAI,MAAA,CAAC;YACrB,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE;gBACzD,KAAK,GAAG,IAAI,yBAAiB,EAAE,CAAC;aACjC;YACD,IAAI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,CAAC,CAAC,UAAU,KAAK,SAAS,CAAC,CAAC,CAAC,WAAW;YACxC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,CAC7B,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/lib/AbstractChatCompletionRunner.mjs b/node_modules/openai/lib/AbstractChatCompletionRunner.mjs new file mode 100644 index 0000000..d22a912 --- /dev/null +++ b/node_modules/openai/lib/AbstractChatCompletionRunner.mjs @@ -0,0 +1,515 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_connectedPromise, _AbstractChatCompletionRunner_resolveConnectedPromise, _AbstractChatCompletionRunner_rejectConnectedPromise, _AbstractChatCompletionRunner_endPromise, _AbstractChatCompletionRunner_resolveEndPromise, _AbstractChatCompletionRunner_rejectEndPromise, _AbstractChatCompletionRunner_listeners, _AbstractChatCompletionRunner_ended, _AbstractChatCompletionRunner_errored, _AbstractChatCompletionRunner_aborted, _AbstractChatCompletionRunner_catchingPromiseCreated, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_handleError, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; +import { APIUserAbortError, OpenAIError } from 'openai/error'; +import { isRunnableFunctionWithParse, } from "./RunnableFunction.mjs"; +import { isAssistantMessage, isFunctionMessage, isToolMessage } from "./chatCompletionUtils.mjs"; +const DEFAULT_MAX_CHAT_COMPLETIONS = 10; +export class AbstractChatCompletionRunner { + constructor() { + _AbstractChatCompletionRunner_instances.add(this); + this.controller = new AbortController(); + _AbstractChatCompletionRunner_connectedPromise.set(this, void 0); + _AbstractChatCompletionRunner_resolveConnectedPromise.set(this, () => { }); + _AbstractChatCompletionRunner_rejectConnectedPromise.set(this, () => { }); + _AbstractChatCompletionRunner_endPromise.set(this, void 0); + _AbstractChatCompletionRunner_resolveEndPromise.set(this, () => { }); + _AbstractChatCompletionRunner_rejectEndPromise.set(this, () => { }); + _AbstractChatCompletionRunner_listeners.set(this, {}); + this._chatCompletions = []; + this.messages = []; + _AbstractChatCompletionRunner_ended.set(this, false); + _AbstractChatCompletionRunner_errored.set(this, false); + _AbstractChatCompletionRunner_aborted.set(this, false); + _AbstractChatCompletionRunner_catchingPromiseCreated.set(this, false); + _AbstractChatCompletionRunner_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_errored, true, "f"); + if (error instanceof Error && error.name === 'AbortError') { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError = new OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new OpenAIError(String(error))); + }); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_endPromise, "f").catch(() => { }); + } + _run(executor) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _AbstractChatCompletionRunner_handleError, "f")); + }, 0); + } + _addChatCompletion(chatCompletion) { + this._chatCompletions.push(chatCompletion); + this._emit('chatCompletion', chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) + this._addMessage(message); + return chatCompletion; + } + _addMessage(message, emit = true) { + if (!('content' in message)) + message.content = null; + this.messages.push(message); + if (emit) { + this._emit('message', message); + if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) { + // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. + this._emit('functionCallResult', message.content); + } + else if (isAssistantMessage(message) && message.function_call) { + this._emit('functionCall', message.function_call); + } + else if (isAssistantMessage(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === 'function') { + this._emit('functionCall', tool_call.function); + } + } + } + } + } + _connected() { + if (this.ended) + return; + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_resolveConnectedPromise, "f").call(this); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _AbstractChatCompletionRunner_endPromise, "f"); + } + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + async finalChatCompletion() { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) + throw new OpenAIError('stream ended without producing a ChatCompletion'); + return completion; + } + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + } + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionCall() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + } + async finalFunctionCallResult() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + } + async totalUsage() { + await this.done(); + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + } + allChatCompletions() { + return [...this._chatCompletions]; + } + _emit(event, ...args) { + // make sure we don't emit any events after end + if (__classPrivateFieldGet(this, _AbstractChatCompletionRunner_ended, "f")) { + return; + } + if (event === 'end') { + __classPrivateFieldSet(this, _AbstractChatCompletionRunner_ended, true, "f"); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) + this._emit('finalChatCompletion', completion); + const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + if (finalMessage) + this._emit('finalMessage', finalMessage); + const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + if (finalContent) + this._emit('finalContent', finalContent); + const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); + if (finalFunctionCall) + this._emit('finalFunctionCall', finalFunctionCall); + const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); + if (finalFunctionCallResult != null) + this._emit('finalFunctionCallResult', finalFunctionCallResult); + if (this._chatCompletions.some((c) => c.usage)) { + this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + } + } + async _createChatCompletion(completions, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + const chatCompletion = await completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addChatCompletion(chatCompletion); + } + async _runChatCompletion(completions, params, options) { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(completions, params, options); + } + async _runFunctions(completions, params, options) { + const role = 'function'; + const { function_call = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const functionsByName = {}; + for (const f of params.functions) { + functionsByName[f.name || f.function.name] = f; + } + const functions = params.functions.map((f) => ({ + name: f.name || f.function.name, + parameters: f.parameters, + description: f.description, + })); + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(completions, { + ...restParams, + function_call, + functions, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.function_call) + return; + const { name, arguments: args } = message.function_call; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions + .map((f) => JSON.stringify(f.name)) + .join(', ')}. Please try again`; + this._addMessage({ role, name, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, name, content }); + continue; + } + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } + catch (error) { + this._addMessage({ + role, + name, + content: error instanceof Error ? error.message : String(error), + }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, name, content }); + if (singleFunctionToCall) + return; + } + } + async _runTools(completions, params, options) { + const role = 'tool'; + const { tool_choice = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + const functionsByName = {}; + for (const f of params.tools) { + if (f.type === 'function') { + functionsByName[f.function.name || f.function.function.name] = f.function; + } + } + const tools = 'tools' in params ? + params.tools.map((t) => t.type === 'function' ? + { + type: 'function', + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters, + description: t.function.description, + }, + } + : t) + : undefined; + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(completions, { + ...restParams, + tool_choice, + tools, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls) { + return; + } + for (const tool_call of message.tool_calls) { + if (tool_call.type !== 'function') + continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${tools + .map((f) => JSON.stringify(f.function.name)) + .join(', ')}. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } + catch (error) { + const content = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, tool_call_id, content }); + if (singleFunctionToCall) { + return; + } + } + } + return; + } +} +_AbstractChatCompletionRunner_connectedPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectConnectedPromise = new WeakMap(), _AbstractChatCompletionRunner_endPromise = new WeakMap(), _AbstractChatCompletionRunner_resolveEndPromise = new WeakMap(), _AbstractChatCompletionRunner_rejectEndPromise = new WeakMap(), _AbstractChatCompletionRunner_listeners = new WeakMap(), _AbstractChatCompletionRunner_ended = new WeakMap(), _AbstractChatCompletionRunner_errored = new WeakMap(), _AbstractChatCompletionRunner_aborted = new WeakMap(), _AbstractChatCompletionRunner_catchingPromiseCreated = new WeakMap(), _AbstractChatCompletionRunner_handleError = new WeakMap(), _AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { + return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; +}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if (isAssistantMessage(message)) { + return { ...message, content: message.content ?? null }; + } + } + throw new OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); +}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isAssistantMessage(message) && message?.function_call) { + return message.function_call; + } + if (isAssistantMessage(message) && message?.tool_calls?.length) { + return message.tool_calls.at(-1)?.function; + } + } + return; +}, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isFunctionMessage(message) && message.content != null) { + return message.content; + } + if (isToolMessage(message) && + message.content != null && + this.messages.some((x) => x.role === 'assistant' && + x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { + return message.content; + } + } + return; +}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { + const total = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } + } + return total; +}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { + if (params.n != null && params.n > 1) { + throw new OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); + } +}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { + return (typeof rawContent === 'string' ? rawContent + : rawContent === undefined ? 'undefined' + : JSON.stringify(rawContent)); +}; +//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map \ No newline at end of file diff --git a/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map b/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map new file mode 100644 index 0000000..b156397 --- /dev/null +++ b/node_modules/openai/lib/AbstractChatCompletionRunner.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"AbstractChatCompletionRunner.mjs","sourceRoot":"","sources":["../src/lib/AbstractChatCompletionRunner.ts"],"names":[],"mappings":";;;;;;;;;;;;OAUO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,cAAc;OACtD,EAEL,2BAA2B,GAE5B;OAMM,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,aAAa,EAAE;AAE/D,MAAM,4BAA4B,GAAG,EAAE,CAAC;AAMxC,MAAM,OAAgB,4BAA4B;IAuBhD;;QApBA,eAAU,GAAoB,IAAI,eAAe,EAAE,CAAC;QAEpD,iEAAiC;QACjC,gEAAuC,GAAG,EAAE,GAAE,CAAC,EAAC;QAChD,+DAAwD,GAAG,EAAE,GAAE,CAAC,EAAC;QAEjE,2DAA2B;QAC3B,0DAAiC,GAAG,EAAE,GAAE,CAAC,EAAC;QAC1C,yDAAkD,GAAG,EAAE,GAAE,CAAC,EAAC;QAE3D,kDAA6E,EAAE,EAAC;QAEtE,qBAAgB,GAAqB,EAAE,CAAC;QAClD,aAAQ,GAAiC,EAAE,CAAC;QAE5C,8CAAS,KAAK,EAAC;QACf,gDAAW,KAAK,EAAC;QACjB,gDAAW,KAAK,EAAC;QACjB,+DAA0B,KAAK,EAAC;QAkRhC,oDAAe,CAAC,KAAc,EAAE,EAAE;YAChC,uBAAA,IAAI,yCAAY,IAAI,MAAA,CAAC;YACrB,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,YAAY,EAAE;gBACzD,KAAK,GAAG,IAAI,iBAAiB,EAAE,CAAC;aACjC;YACD,IAAI,KAAK,YAAY,iBAAiB,EAAE;gBACtC,uBAAA,IAAI,yCAAY,IAAI,MAAA,CAAC;gBACrB,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,EAA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unFunctions.test.d.ts new file mode 100644 index 0000000..fb36c76 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=ChatCompletionRunFunctions.test.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts.map b/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts.map new file mode 100644 index 0000000..6841ba8 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunFunctions.test.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunFunctions.test.d.ts","sourceRoot":"","sources":["../src/lib/ChatCompletionRunFunctions.test.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunFunctions.test.js b/node_modules/openai/lib/ChatCompletionRunFunctions.test.js new file mode 100644 index 0000000..8c71bc6 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunFunctions.test.js @@ -0,0 +1,2142 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const openai_1 = __importDefault(require("openai")); +const stream_1 = require("stream"); +const completions_1 = require("openai/resources/beta/chat/completions"); +const node_fetch_1 = require("node-fetch"); +const chatCompletionUtils_1 = require("./chatCompletionUtils.js"); +/** + * Creates a mock `fetch` function and a `handleRequest` function for intercepting `fetch` calls. + * + * You call `handleRequest` with a callback function that handles the next `fetch` call. + * It returns a Promise that: + * - waits for the next call to `fetch` + * - calls the callback with the `fetch` arguments + * - resolves `fetch` with the callback output + */ +function mockFetch() { + const fetchQueue = []; + const handlerQueue = []; + const enqueueHandler = () => { + handlerQueue.push(new Promise((resolve) => { + fetchQueue.push((handle) => { + enqueueHandler(); + resolve(handle); + }); + })); + }; + enqueueHandler(); + async function fetch(req, init) { + const handler = await handlerQueue.shift(); + if (!handler) + throw new Error('expected handler to be defined'); + const signal = init?.signal; + if (!signal) + return await handler(req, init); + return await Promise.race([ + handler(req, init), + new Promise((resolve, reject) => { + if (signal.aborted) { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + return; + } + signal.addEventListener('abort', (e) => { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + }); + }), + ]); + } + function handleRequest(handle) { + return new Promise((resolve, reject) => { + fetchQueue.shift()?.(async (req, init) => { + try { + return await handle(req, init); + } + catch (err) { + reject(err); + return err; + } + finally { + resolve(); + } + }); + }); + } + return { fetch, handleRequest }; +} +// mockChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// chat completion request/responses. +function mockChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + function handleRequest(handler) { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') + throw new Error(`expected init.body to be a string`); + const body = JSON.parse(rawBody); + return new node_fetch_1.Response(JSON.stringify(await handler(body)), { + headers: { 'Content-Type': 'application/json' }, + }); + }); + } + return { fetch, handleRequest }; +} +// mockStreamingChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// streaming chat completion request/responses. +function mockStreamingChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + function handleRequest(handler) { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') + throw new Error(`expected init.body to be a string`); + const body = JSON.parse(rawBody); + const stream = new stream_1.PassThrough(); + (async () => { + for await (const chunk of handler(body)) { + stream.write(`data: ${JSON.stringify(chunk)}\n\n`); + } + stream.end(`data: [DONE]\n\n`); + })(); + return new node_fetch_1.Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Transfer-Encoding': 'chunked', + }, + }); + }); + } + return { fetch, handleRequest }; +} +// contentChoiceDeltas returns an async iterator which mocks a delta stream of a by splitting the +// argument into chunks separated by whitespace. +function* contentChoiceDeltas(content, { index = 0, role = 'assistant', } = {}) { + const deltas = content.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'stop' : null, + logprobs: null, + delta: { + role, + content: deltas[i] ? `${deltas[i]}${i === deltas.length - 1 ? '' : ' '}` : null, + }, + }; + } +} +// functionCallDeltas returns an async iterator which mocks a delta stream of a functionCall by splitting +// the argument into chunks separated by whitespace. +function* functionCallDeltas(args, { index = 0, id = '123', name, role = 'assistant', }) { + const deltas = args.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'function_call' : null, + delta: { + role, + tool_calls: [ + { + type: 'function', + index: 0, + id, + function: { + arguments: `${deltas[i] || ''}${i === deltas.length - 1 ? '' : ' '}`, + ...(i === deltas.length - 1 ? { name } : null), + }, + }, + ], + }, + }; + } +} +class RunnerListener { + constructor(runner) { + this.runner = runner; + this.contents = []; + this.messages = []; + this.chatCompletions = []; + this.functionCalls = []; + this.functionCallResults = []; + this.finalContent = null; + this.gotConnect = false; + this.gotAbort = false; + this.gotEnd = false; + this.onceMessageCallCount = 0; + runner + .on('connect', () => (this.gotConnect = true)) + .on('content', (content) => this.contents.push(content)) + .on('message', (message) => this.messages.push(message)) + .on('chatCompletion', (completion) => this.chatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.functionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.functionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('totalUsage', (usage) => (this.totalUsage = usage)) + .on('error', (error) => (this.error = error)) + .on('abort', (error) => ((this.error = error), (this.gotAbort = true))) + .on('end', () => (this.gotEnd = true)) + .once('message', () => this.onceMessageCallCount++); + } + async sanityCheck({ error } = {}) { + expect(this.onceMessageCallCount).toBeLessThanOrEqual(1); + expect(this.gotAbort).toEqual(this.runner.aborted); + if (this.runner.aborted) + expect(this.runner.errored).toBe(true); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.totalUsage()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + if (!this.gotConnect) { + expect(this.contents).toEqual([]); + expect(this.messages).toEqual([]); + expect(this.chatCompletions).toEqual([]); + expect(this.functionCalls).toEqual([]); + expect(this.functionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.totalUsage).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + if (error) + return; + const expectedContents = this.messages + .filter(chatCompletionUtils_1.isAssistantMessage) + .map((m) => m.content) + .filter(Boolean); + expect(this.contents).toEqual(expectedContents); + expect(this.finalMessage).toEqual([...this.messages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(expectedContents[expectedContents.length - 1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.chatCompletions[this.chatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.functionCalls[this.functionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual(this.functionCallResults[this.functionCallResults.length - 1]); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.chatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.messages).toEqual(this.runner.messages.slice(-this.messages.length)); + if (this.chatCompletions.some((c) => c.usage)) { + const totalUsage = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this.chatCompletions) { + if (usage) { + totalUsage.completion_tokens += usage.completion_tokens; + totalUsage.prompt_tokens += usage.prompt_tokens; + totalUsage.total_tokens += usage.total_tokens; + } + } + expect(this.totalUsage).toEqual(totalUsage); + expect(await this.runner.totalUsage()).toEqual(totalUsage); + } + expect(this.gotEnd).toBe(true); + } +} +class StreamingRunnerListener { + constructor(runner) { + this.runner = runner; + this.eventChunks = []; + this.eventContents = []; + this.eventMessages = []; + this.eventChatCompletions = []; + this.eventFunctionCalls = []; + this.eventFunctionCallResults = []; + this.finalContent = null; + this.gotConnect = false; + this.gotEnd = false; + runner + .on('connect', () => (this.gotConnect = true)) + .on('chunk', (chunk) => this.eventChunks.push(chunk)) + .on('content', (delta, snapshot) => this.eventContents.push([delta, snapshot])) + .on('message', (message) => this.eventMessages.push(message)) + .on('chatCompletion', (completion) => this.eventChatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.eventFunctionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.eventFunctionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('error', (error) => (this.error = error)) + .on('abort', (abort) => (this.error = abort)) + .on('end', () => (this.gotEnd = true)); + } + async sanityCheck({ error } = {}) { + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + if (!this.gotConnect) { + expect(this.eventContents).toEqual([]); + expect(this.eventMessages).toEqual([]); + expect(this.eventChatCompletions).toEqual([]); + expect(this.eventFunctionCalls).toEqual([]); + expect(this.eventFunctionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + if (error) + return; + if (this.eventContents.length) + expect(this.eventChunks.length).toBeGreaterThan(0); + expect(this.finalMessage).toEqual([...this.eventMessages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(this.eventContents[this.eventContents.length - 1]?.[1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.eventChatCompletions[this.eventChatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.eventFunctionCalls[this.eventFunctionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual(this.eventFunctionCallResults[this.eventFunctionCallResults.length - 1]); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.eventChatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.eventMessages).toEqual(this.runner.messages.slice(-this.eventMessages.length)); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + expect(this.gotEnd).toBe(true); + } +} +function _typeTests() { + const openai = new openai_1.default(); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + function: (str) => String(str.length), + parameters: { type: 'string' }, + description: 'gets the length of a string', + }, + }, + { + type: 'function', + // @ts-expect-error function must accept string if parse is omitted + function: { + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + // @ts-expect-error parse and function don't match + parse: (str) => str, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new completions_1.ParsingToolFunction({ + name: 'keys', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new completions_1.ParsingToolFunction({ + name: 'len2', + // @ts-expect-error parse and function don't match + parse: (str) => str, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + // @ts-ignore error occurs here in TS 4 + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'keys', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'len2', + parse: (str) => str, + // @ts-ignore error occurs here in TS 5 + // function input doesn't match parse output + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); +} +describe('resource completions', () => { + describe('runTools with stream: false', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + await runner.done(); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, { signal: controller.signal }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + controller.abort(); + await runner.done().catch(() => { }); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 5, + prompt_tokens: 20, + total_tokens: 25, + }, + }; + }); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 10, + prompt_tokens: 25, + total_tokens: 35, + }, + }; + }); + await runner.done(); + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '123', function: { name: 'get_weather', arguments: '' } }], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '1234', function: { name: 'getWeather', arguments: '' } }], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + describe('runTools with stream: true', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, { signal: controller.signal }); + runner.on('functionCallResult', () => controller.abort()); + const listener = new StreamingRunnerListener(runner); + await handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }); + await runner.done().catch(() => { }); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + index: 0, + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new completions_1.ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + for (const choice of functionCallDeltas('[{"a": 1, "b": 2, "c": 3}]', { + name: 'numProperties', + id: '123', + })) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + for (const choice of functionCallDeltas('{"a": 1, "b": 2, "c": 3}', { + name: 'numProperties', + id: '1234', + })) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', tool_call_id: '123', content: `it's raining` }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + yield { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + describe('stream', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + test('toReadableStream and fromReadableStream', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new openai_1.default({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + const proxied = completions_1.ChatCompletionStreamingRunner.fromReadableStream(runner.toReadableStream()); + const listener = new StreamingRunnerListener(proxied); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + proxied.done(), + ]); + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + }); +}); +//# sourceMappingURL=ChatCompletionRunFunctions.test.js.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunFunctions.test.js.map b/node_modules/openai/lib/ChatCompletionRunFunctions.test.js.map new file mode 100644 index 0000000..f01aecc --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunFunctions.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunFunctions.test.js","sourceRoot":"","sources":["../src/lib/ChatCompletionRunFunctions.test.ts"],"names":[],"mappings":";;;;;AAAA,oDAA4B;AAE5B,mCAAqC;AACrC,wEAMgD;AAIhD,2CAAsC;AACtC,kEAA2D;AAI3D;;;;;;;;GAQG;AACH,SAAS,SAAS;IAChB,MAAM,UAAU,GAAwC,EAAE,CAAC;IAC3D,MAAM,YAAY,GAA4B,EAAE,CAAC;IAEjD,MAAM,cAAc,GAAG,GAAG,EAAE;QAC1B,YAAY,CAAC,IAAI,CACf,IAAI,OAAO,CAAe,CAAC,OAAO,EAAE,EAAE;YACpC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAoB,EAAE,EAAE;gBACvC,cAAc,EAAE,CAAC;gBACjB,OAAO,CAAC,MAAM,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;IACF,cAAc,EAAE,CAAC;IAEjB,KAAK,UAAU,KAAK,CAAC,GAAyB,EAAE,IAAkB;QAChE,MAAM,OAAO,GAAG,MAAM,YAAY,CAAC,KAAK,EAAE,CAAC;QAC3C,IAAI,CAAC,OAAO;YAAE,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;QAChE,MAAM,MAAM,GAAG,IAAI,EAAE,MAAM,CAAC;QAC5B,IAAI,CAAC,MAAM;YAAE,OAAO,MAAM,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAC7C,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC;YACxB,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC;YAClB,IAAI,OAAO,CAAW,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;gBACxC,IAAI,MAAM,CAAC,OAAO,EAAE;oBAClB,gCAAgC;oBAChC,MAAM,CAAC,IAAI,YAAY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I,EAAE,MAAM,EAAE,OAAO,EAAE,kCAAkC,EAAE,CAAC;gBACzE,KAAK,EAAE,eAAe;aACvB,CAAC,CAAC;YAEH,MAAM,OAAO,GAAG,2CAA6B,CAAC,kBAAkB,CAAC,MAAM,CAAC,gBAAgB,EAAE,CAAC,CAAC;YAC5F,MAAM,QAAQ,GAAG,IAAI,uBAAuB,CAAC,OAAO,CAAC,CAAC;YAEtD,MAAM,OAAO,CAAC,GAAG,CAAC;gBAChB,aAAa,CAAC,KAAK,SAAS,CAAC,EAAE,OAAO;oBACpC,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,kCAAkC,EAAE,CAAC,CAAC,CAAC;oBAClG,KAAK,MAAM,MAAM,IAAI,mBAAmB,CAAC,6BAA6B,CAAC,EAAE;wBACvE,MAAM;4BACJ,EAAE,EAAE,GAAG;4BACP,OAAO,EAAE,CAAC,MAAM,CAAC;4BACjB,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC;4BACtC,KAAK,EAAE,eAAe;4BACtB,MAAM,EAAE,uBAAuB;yBAChC,CAAC;qBACH;gBACH,CAAC,CAAC;gBACF,OAAO,CAAC,IAAI,EAAE;aACf,CAAC,CAAC;YAEH,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,6BAA6B,EAAE,CAAC,CAAC;YACrG,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs b/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs new file mode 100644 index 0000000..090ba45 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs @@ -0,0 +1,2137 @@ +import OpenAI from 'openai'; +import { PassThrough } from 'stream'; +import { ParsingToolFunction, ChatCompletionStreamingRunner, } from 'openai/resources/beta/chat/completions'; +import { Response } from 'node-fetch'; +import { isAssistantMessage } from "./chatCompletionUtils.mjs"; +/** + * Creates a mock `fetch` function and a `handleRequest` function for intercepting `fetch` calls. + * + * You call `handleRequest` with a callback function that handles the next `fetch` call. + * It returns a Promise that: + * - waits for the next call to `fetch` + * - calls the callback with the `fetch` arguments + * - resolves `fetch` with the callback output + */ +function mockFetch() { + const fetchQueue = []; + const handlerQueue = []; + const enqueueHandler = () => { + handlerQueue.push(new Promise((resolve) => { + fetchQueue.push((handle) => { + enqueueHandler(); + resolve(handle); + }); + })); + }; + enqueueHandler(); + async function fetch(req, init) { + const handler = await handlerQueue.shift(); + if (!handler) + throw new Error('expected handler to be defined'); + const signal = init?.signal; + if (!signal) + return await handler(req, init); + return await Promise.race([ + handler(req, init), + new Promise((resolve, reject) => { + if (signal.aborted) { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + return; + } + signal.addEventListener('abort', (e) => { + // @ts-ignore does exist in Node + reject(new DOMException('The user aborted a request.', 'AbortError')); + }); + }), + ]); + } + function handleRequest(handle) { + return new Promise((resolve, reject) => { + fetchQueue.shift()?.(async (req, init) => { + try { + return await handle(req, init); + } + catch (err) { + reject(err); + return err; + } + finally { + resolve(); + } + }); + }); + } + return { fetch, handleRequest }; +} +// mockChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// chat completion request/responses. +function mockChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + function handleRequest(handler) { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') + throw new Error(`expected init.body to be a string`); + const body = JSON.parse(rawBody); + return new Response(JSON.stringify(await handler(body)), { + headers: { 'Content-Type': 'application/json' }, + }); + }); + } + return { fetch, handleRequest }; +} +// mockStreamingChatCompletionFetch is like mockFetch, but with better a more convenient handleRequest to mock +// streaming chat completion request/responses. +function mockStreamingChatCompletionFetch() { + const { fetch, handleRequest: handleRawRequest } = mockFetch(); + function handleRequest(handler) { + return handleRawRequest(async (req, init) => { + const rawBody = init?.body; + if (typeof rawBody !== 'string') + throw new Error(`expected init.body to be a string`); + const body = JSON.parse(rawBody); + const stream = new PassThrough(); + (async () => { + for await (const chunk of handler(body)) { + stream.write(`data: ${JSON.stringify(chunk)}\n\n`); + } + stream.end(`data: [DONE]\n\n`); + })(); + return new Response(stream, { + headers: { + 'Content-Type': 'text/event-stream', + 'Transfer-Encoding': 'chunked', + }, + }); + }); + } + return { fetch, handleRequest }; +} +// contentChoiceDeltas returns an async iterator which mocks a delta stream of a by splitting the +// argument into chunks separated by whitespace. +function* contentChoiceDeltas(content, { index = 0, role = 'assistant', } = {}) { + const deltas = content.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'stop' : null, + logprobs: null, + delta: { + role, + content: deltas[i] ? `${deltas[i]}${i === deltas.length - 1 ? '' : ' '}` : null, + }, + }; + } +} +// functionCallDeltas returns an async iterator which mocks a delta stream of a functionCall by splitting +// the argument into chunks separated by whitespace. +function* functionCallDeltas(args, { index = 0, id = '123', name, role = 'assistant', }) { + const deltas = args.split(/\s+/g); + for (let i = 0; i < deltas.length; i++) { + yield { + index, + finish_reason: i === deltas.length - 1 ? 'function_call' : null, + delta: { + role, + tool_calls: [ + { + type: 'function', + index: 0, + id, + function: { + arguments: `${deltas[i] || ''}${i === deltas.length - 1 ? '' : ' '}`, + ...(i === deltas.length - 1 ? { name } : null), + }, + }, + ], + }, + }; + } +} +class RunnerListener { + constructor(runner) { + this.runner = runner; + this.contents = []; + this.messages = []; + this.chatCompletions = []; + this.functionCalls = []; + this.functionCallResults = []; + this.finalContent = null; + this.gotConnect = false; + this.gotAbort = false; + this.gotEnd = false; + this.onceMessageCallCount = 0; + runner + .on('connect', () => (this.gotConnect = true)) + .on('content', (content) => this.contents.push(content)) + .on('message', (message) => this.messages.push(message)) + .on('chatCompletion', (completion) => this.chatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.functionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.functionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('totalUsage', (usage) => (this.totalUsage = usage)) + .on('error', (error) => (this.error = error)) + .on('abort', (error) => ((this.error = error), (this.gotAbort = true))) + .on('end', () => (this.gotEnd = true)) + .once('message', () => this.onceMessageCallCount++); + } + async sanityCheck({ error } = {}) { + expect(this.onceMessageCallCount).toBeLessThanOrEqual(1); + expect(this.gotAbort).toEqual(this.runner.aborted); + if (this.runner.aborted) + expect(this.runner.errored).toBe(true); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.totalUsage()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + if (!this.gotConnect) { + expect(this.contents).toEqual([]); + expect(this.messages).toEqual([]); + expect(this.chatCompletions).toEqual([]); + expect(this.functionCalls).toEqual([]); + expect(this.functionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.totalUsage).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + if (error) + return; + const expectedContents = this.messages + .filter(isAssistantMessage) + .map((m) => m.content) + .filter(Boolean); + expect(this.contents).toEqual(expectedContents); + expect(this.finalMessage).toEqual([...this.messages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(expectedContents[expectedContents.length - 1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.chatCompletions[this.chatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.functionCalls[this.functionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual(this.functionCallResults[this.functionCallResults.length - 1]); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.chatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.messages).toEqual(this.runner.messages.slice(-this.messages.length)); + if (this.chatCompletions.some((c) => c.usage)) { + const totalUsage = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this.chatCompletions) { + if (usage) { + totalUsage.completion_tokens += usage.completion_tokens; + totalUsage.prompt_tokens += usage.prompt_tokens; + totalUsage.total_tokens += usage.total_tokens; + } + } + expect(this.totalUsage).toEqual(totalUsage); + expect(await this.runner.totalUsage()).toEqual(totalUsage); + } + expect(this.gotEnd).toBe(true); + } +} +class StreamingRunnerListener { + constructor(runner) { + this.runner = runner; + this.eventChunks = []; + this.eventContents = []; + this.eventMessages = []; + this.eventChatCompletions = []; + this.eventFunctionCalls = []; + this.eventFunctionCallResults = []; + this.finalContent = null; + this.gotConnect = false; + this.gotEnd = false; + runner + .on('connect', () => (this.gotConnect = true)) + .on('chunk', (chunk) => this.eventChunks.push(chunk)) + .on('content', (delta, snapshot) => this.eventContents.push([delta, snapshot])) + .on('message', (message) => this.eventMessages.push(message)) + .on('chatCompletion', (completion) => this.eventChatCompletions.push(completion)) + .on('functionCall', (functionCall) => this.eventFunctionCalls.push(functionCall)) + .on('functionCallResult', (result) => this.eventFunctionCallResults.push(result)) + .on('finalContent', (content) => (this.finalContent = content)) + .on('finalMessage', (message) => (this.finalMessage = message)) + .on('finalChatCompletion', (completion) => (this.finalChatCompletion = completion)) + .on('finalFunctionCall', (functionCall) => (this.finalFunctionCall = functionCall)) + .on('finalFunctionCallResult', (result) => (this.finalFunctionCallResult = result)) + .on('error', (error) => (this.error = error)) + .on('abort', (abort) => (this.error = abort)) + .on('end', () => (this.gotEnd = true)); + } + async sanityCheck({ error } = {}) { + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + await expect(this.runner.finalChatCompletion()).rejects.toThrow(error); + await expect(this.runner.finalMessage()).rejects.toThrow(error); + await expect(this.runner.finalContent()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCall()).rejects.toThrow(error); + await expect(this.runner.finalFunctionCallResult()).rejects.toThrow(error); + await expect(this.runner.done()).rejects.toThrow(error); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + if (!this.gotConnect) { + expect(this.eventContents).toEqual([]); + expect(this.eventMessages).toEqual([]); + expect(this.eventChatCompletions).toEqual([]); + expect(this.eventFunctionCalls).toEqual([]); + expect(this.eventFunctionCallResults).toEqual([]); + expect(this.finalContent).toBeUndefined(); + expect(this.finalMessage).toBeUndefined(); + expect(this.finalChatCompletion).toBeUndefined(); + expect(this.finalFunctionCall).toBeUndefined(); + expect(this.finalFunctionCallResult).toBeUndefined(); + expect(this.gotEnd).toBe(true); + return; + } + if (error) + return; + if (this.eventContents.length) + expect(this.eventChunks.length).toBeGreaterThan(0); + expect(this.finalMessage).toEqual([...this.eventMessages].reverse().find((x) => x.role === 'assistant')); + expect(await this.runner.finalMessage()).toEqual(this.finalMessage); + expect(this.finalContent).toEqual(this.eventContents[this.eventContents.length - 1]?.[1] ?? null); + expect(await this.runner.finalContent()).toEqual(this.finalContent); + expect(this.finalChatCompletion).toEqual(this.eventChatCompletions[this.eventChatCompletions.length - 1]); + expect(await this.runner.finalChatCompletion()).toEqual(this.finalChatCompletion); + expect(this.finalFunctionCall).toEqual(this.eventFunctionCalls[this.eventFunctionCalls.length - 1]); + expect(await this.runner.finalFunctionCall()).toEqual(this.finalFunctionCall); + expect(this.finalFunctionCallResult).toEqual(this.eventFunctionCallResults[this.eventFunctionCallResults.length - 1]); + expect(await this.runner.finalFunctionCallResult()).toEqual(this.finalFunctionCallResult); + expect(this.eventChatCompletions).toEqual(this.runner.allChatCompletions()); + expect(this.eventMessages).toEqual(this.runner.messages.slice(-this.eventMessages.length)); + if (error) { + expect(this.error?.message).toEqual(error); + expect(this.runner.errored).toBe(true); + } + else { + expect(this.error).toBeUndefined(); + expect(this.runner.errored).toBe(false); + } + expect(this.gotEnd).toBe(true); + } +} +function _typeTests() { + const openai = new OpenAI(); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + function: (str) => String(str.length), + parameters: { type: 'string' }, + description: 'gets the length of a string', + }, + }, + { + type: 'function', + // @ts-expect-error function must accept string if parse is omitted + function: { + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + // @ts-expect-error parse and function don't match + parse: (str) => str, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new ParsingToolFunction({ + name: 'keys', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + new ParsingToolFunction({ + name: 'len2', + // @ts-expect-error parse and function don't match + parse: (str) => str, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }), + ], + }); + openai.beta.chat.completions.runTools({ + messages: [ + { role: 'user', content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}' }, + ], + model: 'gpt-3.5-turbo', + // @ts-ignore error occurs here in TS 4 + tools: [ + { + type: 'function', + function: { + name: 'numProperties', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'keys', + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object)) { + throw new Error('must be an Object'); + } + return result; + }, + function: (obj) => Object.keys(obj).join(', '), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + { + type: 'function', + function: { + name: 'len2', + parse: (str) => str, + // @ts-ignore error occurs here in TS 5 + // function input doesn't match parse output + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + description: 'gets the number of properties on an object', + }, + }, + ], + }); +} +describe('resource completions', () => { + describe('runTools with stream: false', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + await runner.done(); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, { signal: controller.signal }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }); + controller.abort(); + await runner.done().catch(() => { }); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 5, + prompt_tokens: 20, + total_tokens: 25, + }, + }; + }); + await handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + usage: { + completion_tokens: 10, + prompt_tokens: 25, + total_tokens: 35, + }, + }; + }); + await runner.done(); + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `there are 3 properties in {"a": 1, "b": 2, "c": 3}`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.functionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.functionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new RunnerListener(runner); + await Promise.all([ + handleRequest(async (request) => { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + return { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + return { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + message: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + handleRequest(async (request) => { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + return { + id: '3', + choices: [ + { + index: 0, + finish_reason: 'stop', + logprobs: null, + message: { + role: 'assistant', + content: `it's raining`, + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion', + }; + }), + runner.done(), + ]); + expect(listener.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '123', function: { name: 'get_weather', arguments: '' } }], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [{ type: 'function', id: '1234', function: { name: 'getWeather', arguments: '' } }], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.functionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + describe('runTools with stream: true', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('flow with abort', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const controller = new AbortController(); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }, { signal: controller.signal }); + runner.on('functionCallResult', () => controller.abort()); + const listener = new StreamingRunnerListener(runner); + await handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }); + await runner.done().catch(() => { }); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '123' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck({ error: 'Request was aborted.' }); + expect(runner.aborted).toBe(true); + }); + test('successful flow with parse', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + index: 0, + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '123', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '123' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual(['3']); + await listener.sanityCheck(); + }); + test('flow with parse error', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ], + model: 'gpt-3.5-turbo', + tools: [ + new ParsingToolFunction({ + name: 'numProperties', + function: (obj) => String(Object.keys(obj).length), + parameters: { type: 'object' }, + parse: (str) => { + const result = JSON.parse(str); + if (!(result instanceof Object) || Array.isArray(result)) { + throw new Error('must be an object'); + } + return result; + }, + description: 'gets the number of properties on an object', + }), + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + ]); + for (const choice of functionCallDeltas('[{"a": 1, "b": 2, "c": 3}]', { + name: 'numProperties', + id: '123', + })) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + ]); + for (const choice of functionCallDeltas('{"a": 1, "b": 2, "c": 3}', { + name: 'numProperties', + id: '1234', + })) { + yield { + id: '2', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { + role: 'user', + content: 'can you tell me how many properties are in {"a": 1, "b": 2, "c": 3}', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '[{"a": 1, "b": 2, "c": 3}]', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: `must be an object`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '{"a": 1, "b": 2, "c": 3}', + name: 'numProperties', + }, + }, + ], + }, + { + role: 'tool', + content: '3', + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`there are 3 properties in {"a": 1, "b": 2, "c": 3}`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { name: 'numProperties', arguments: '[{"a": 1, "b": 2, "c": 3}]' }, + }, + ], + }, + { role: 'tool', content: `must be an object`, tool_call_id: '123' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { name: 'numProperties', arguments: '{"a": 1, "b": 2, "c": 3}' }, + }, + ], + }, + { role: 'tool', content: '3', tool_call_id: '1234' }, + { role: 'assistant', content: 'there are 3 properties in {"a": 1, "b": 2, "c": 3}' }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`must be an object`, '3']); + await listener.sanityCheck(); + }); + test('single function call', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tool_choice: { + type: 'function', + function: { + name: 'getWeather', + }, + }, + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', tool_call_id: '123', content: `it's raining` }, + ]); + expect(listener.eventFunctionCallResults).toEqual([`it's raining`]); + await listener.sanityCheck(); + }); + test('wrong function name', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.runTools({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + tools: [ + { + type: 'function', + function: { + function: function getWeather() { + return `it's raining`; + }, + parameters: {}, + description: 'gets the weather', + }, + }, + ], + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + yield { + id: '1', + choices: [ + { + index: 0, + finish_reason: 'function_call', + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + ]); + yield { + id: '2', + choices: [ + { + index: 0, + finish_reason: 'function_call', + logprobs: null, + delta: { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + index: 0, + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + }, + ], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + }), + handleRequest(async function* (request) { + expect(request.messages).toEqual([ + { role: 'user', content: 'tell me what the weather is like' }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { + role: 'tool', + content: `it's raining`, + tool_call_id: '1234', + }, + ]); + for (const choice of contentChoiceDeltas(`it's raining`)) { + yield { + id: '3', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.eventMessages).toEqual([ + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '123', + function: { + arguments: '', + name: 'get_weather', + }, + }, + ], + }, + { + role: 'tool', + content: `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + tool_call_id: '123', + }, + { + role: 'assistant', + content: null, + tool_calls: [ + { + type: 'function', + id: '1234', + function: { + arguments: '', + name: 'getWeather', + }, + }, + ], + }, + { role: 'tool', content: `it's raining`, tool_call_id: '1234' }, + { role: 'assistant', content: "it's raining" }, + ]); + expect(listener.eventFunctionCallResults).toEqual([ + `Invalid tool_call: "get_weather". Available options are: "getWeather". Please try again`, + `it's raining`, + ]); + await listener.sanityCheck(); + }); + }); + describe('stream', () => { + test('successful flow', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + const listener = new StreamingRunnerListener(runner); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + runner.done(), + ]); + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + test('toReadableStream and fromReadableStream', async () => { + const { fetch, handleRequest } = mockStreamingChatCompletionFetch(); + const openai = new OpenAI({ apiKey: 'something1234', baseURL: 'http://127.0.0.1:4010', fetch }); + const runner = openai.beta.chat.completions.stream({ + stream: true, + messages: [{ role: 'user', content: 'tell me what the weather is like' }], + model: 'gpt-3.5-turbo', + }); + const proxied = ChatCompletionStreamingRunner.fromReadableStream(runner.toReadableStream()); + const listener = new StreamingRunnerListener(proxied); + await Promise.all([ + handleRequest(async function* (request) { + expect(request.messages).toEqual([{ role: 'user', content: 'tell me what the weather is like' }]); + for (const choice of contentChoiceDeltas(`The weather is great today!`)) { + yield { + id: '1', + choices: [choice], + created: Math.floor(Date.now() / 1000), + model: 'gpt-3.5-turbo', + object: 'chat.completion.chunk', + }; + } + }), + proxied.done(), + ]); + expect(listener.finalMessage).toEqual({ role: 'assistant', content: 'The weather is great today!' }); + await listener.sanityCheck(); + }); + }); +}); +//# sourceMappingURL=ChatCompletionRunFunctions.test.mjs.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs.map b/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs.map new file mode 100644 index 0000000..1c116b3 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunFunctions.test.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunFunctions.test.mjs","sourceRoot":"","sources":["../src/lib/ChatCompletionRunFunctions.test.ts"],"names":[],"mappings":"OAAO,MAAM,MAAM,QAAQ;OAEpB,EAAE,WAAW,EAAE,MAAM,QAAQ;OAC7B,EACL,mBAAmB,EAGnB,6BAA6B,GAE9B,MAAM,wCAAwC;OAIxC,EAAE,QAAQ,EAAE,MAAM,YAAY;OAC9B,EAAE,kBAAkB,EAAE;AAI7B;;;;;;;;GAQG;AACH,SAAS,SAAS;IAChB,MAAM,UAAU,GAAwC,EAAE,CAAC;IAC3D,MAAM,YAAY,GAA4B,EAAE,CAAC;IAEjD,MAAM,cAAc,GAAG,GAAG,EAAE;QAC1B,YAAY,CAAC,IAAI,CACf,IAAI,OAAO,CAAe,CAAC,OAAO,EAAE,EAAE;YACpC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAoB,EAAE,EAAE;gBACvC,cAAc,EAAE,CAAC;gBACjB,OAAO,CAAC,MAAM,CAAC,CAAC;YAClB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CACH,CAAC;IACJ,CAAC,CAAC;IACF,cAA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,GAAG,IAAI,CAAC;4BACtC,KAAK,EAAE,eAAe;4BACtB,MAAM,EAAE,uBAAuB;yBAChC,CAAC;qBACH;gBACH,CAAC,CAAC;gBACF,OAAO,CAAC,IAAI,EAAE;aACf,CAAC,CAAC;YAEH,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,6BAA6B,EAAE,CAAC,CAAC;YACrG,MAAM,QAAQ,CAAC,WAAW,EAAE,CAAC;QAC/B,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunner.d.ts b/node_modules/openai/lib/ChatCompletionRunner.d.ts new file mode 100644 index 0000000..73a44a9 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunner.d.ts @@ -0,0 +1,19 @@ +import { type Completions, type ChatCompletionMessageParam, type ChatCompletionCreateParamsNonStreaming } from 'openai/resources/chat/completions'; +import { type RunnableFunctions, type BaseFunctionsArgs, RunnableTools } from "./RunnableFunction.js"; +import { AbstractChatCompletionRunner, AbstractChatCompletionRunnerEvents, RunnerOptions } from "./AbstractChatCompletionRunner.js"; +export interface ChatCompletionRunnerEvents extends AbstractChatCompletionRunnerEvents { + content: (content: string) => void; +} +export type ChatCompletionFunctionRunnerParams = Omit & { + functions: RunnableFunctions; +}; +export type ChatCompletionToolRunnerParams = Omit & { + tools: RunnableTools; +}; +export declare class ChatCompletionRunner extends AbstractChatCompletionRunner { + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions: Completions, params: ChatCompletionFunctionRunnerParams, options?: RunnerOptions): ChatCompletionRunner; + static runTools(completions: Completions, params: ChatCompletionToolRunnerParams, options?: RunnerOptions): ChatCompletionRunner; + _addMessage(message: ChatCompletionMessageParam): void; +} +//# sourceMappingURL=ChatCompletionRunner.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunner.d.ts.map b/node_modules/openai/lib/ChatCompletionRunner.d.ts.map new file mode 100644 index 0000000..3ca4c2d --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunner.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunner.d.ts","sourceRoot":"","sources":["../src/lib/ChatCompletionRunner.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,WAAW,EAChB,KAAK,0BAA0B,EAC/B,KAAK,sCAAsC,EAC5C,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,KAAK,iBAAiB,EAAE,KAAK,iBAAiB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnG,OAAO,EACL,4BAA4B,EAC5B,kCAAkC,EAClC,aAAa,EACd,MAAM,gCAAgC,CAAC;AAGxC,MAAM,WAAW,0BAA2B,SAAQ,kCAAkC;IACpF,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CACpC;AAED,MAAM,MAAM,kCAAkC,CAAC,aAAa,SAAS,iBAAiB,IAAI,IAAI,CAC5F,sCAAsC,EACtC,WAAW,CACZ,GAAG;IACF,SAAS,EAAE,iBAAiB,CAAC,aAAa,CAAC,CAAC;CAC7C,CAAC;AAEF,MAAM,MAAM,8BAA8B,CAAC,aAAa,SAAS,iBAAiB,IAAI,IAAI,CACxF,sCAAsC,EACtC,OAAO,CACR,GAAG;IACF,KAAK,EAAE,aAAa,CAAC,aAAa,CAAC,CAAC;CACrC,CAAC;AAEF,qBAAa,oBAAqB,SAAQ,4BAA4B,CAAC,0BAA0B,CAAC;IAChG,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAW,EAAE,WAAW,EACxB,MAAM,EAAE,kCAAkC,CAAC,GAAG,EAAE,CAAC,EACjD,OAAO,CAAC,EAAE,aAAa,GACtB,oBAAoB;IAUvB,MAAM,CAAC,QAAQ,CACb,WAAW,EAAE,WAAW,EACxB,MAAM,EAAE,8BAA8B,CAAC,GAAG,EAAE,CAAC,EAC7C,OAAO,CAAC,EAAE,aAAa,GACtB,oBAAoB;IAUd,WAAW,CAAC,OAAO,EAAE,0BAA0B;CAMzD"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunner.js b/node_modules/openai/lib/ChatCompletionRunner.js new file mode 100644 index 0000000..c85a1dd --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunner.js @@ -0,0 +1,34 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChatCompletionRunner = void 0; +const AbstractChatCompletionRunner_1 = require("./AbstractChatCompletionRunner.js"); +const chatCompletionUtils_1 = require("./chatCompletionUtils.js"); +class ChatCompletionRunner extends AbstractChatCompletionRunner_1.AbstractChatCompletionRunner { + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + static runTools(completions, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } + _addMessage(message) { + super._addMessage(message); + if ((0, chatCompletionUtils_1.isAssistantMessage)(message) && message.content) { + this._emit('content', message.content); + } + } +} +exports.ChatCompletionRunner = ChatCompletionRunner; +//# sourceMappingURL=ChatCompletionRunner.js.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunner.js.map b/node_modules/openai/lib/ChatCompletionRunner.js.map new file mode 100644 index 0000000..24ec3e0 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunner.js","sourceRoot":"","sources":["../src/lib/ChatCompletionRunner.ts"],"names":[],"mappings":";;;AAMA,oFAIwC;AACxC,kEAA2D;AAoB3D,MAAa,oBAAqB,SAAQ,2DAAwD;IAChG,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAwB,EACxB,MAAiD,EACjD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,cAAc,EAAE;SAC9E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,WAAwB,EACxB,MAA6C,EAC7C,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE;SAC1E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC;IAChB,CAAC;IAEQ,WAAW,CAAC,OAAmC;QACtD,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC3B,IAAI,IAAA,wCAAkB,EAAC,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE;YAClD,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,OAAiB,CAAC,CAAC;SAClD;IACH,CAAC;CACF;AApCD,oDAoCC"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunner.mjs b/node_modules/openai/lib/ChatCompletionRunner.mjs new file mode 100644 index 0000000..354355c --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunner.mjs @@ -0,0 +1,30 @@ +import { AbstractChatCompletionRunner, } from "./AbstractChatCompletionRunner.mjs"; +import { isAssistantMessage } from "./chatCompletionUtils.mjs"; +export class ChatCompletionRunner extends AbstractChatCompletionRunner { + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + static runTools(completions, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } + _addMessage(message) { + super._addMessage(message); + if (isAssistantMessage(message) && message.content) { + this._emit('content', message.content); + } + } +} +//# sourceMappingURL=ChatCompletionRunner.mjs.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionRunner.mjs.map b/node_modules/openai/lib/ChatCompletionRunner.mjs.map new file mode 100644 index 0000000..144b8e7 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionRunner.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionRunner.mjs","sourceRoot":"","sources":["../src/lib/ChatCompletionRunner.ts"],"names":[],"mappings":"OAMO,EACL,4BAA4B,GAG7B;OACM,EAAE,kBAAkB,EAAE;AAoB7B,MAAM,OAAO,oBAAqB,SAAQ,4BAAwD;IAChG,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAwB,EACxB,MAAiD,EACjD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,cAAc,EAAE;SAC9E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,WAAwB,EACxB,MAA6C,EAC7C,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE;SAC1E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC;IAChB,CAAC;IAEQ,WAAW,CAAC,OAAmC;QACtD,KAAK,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAC3B,IAAI,kBAAkB,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE;YAClD,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,OAAiB,CAAC,CAAC;SAClD;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStream.d.ts b/node_modules/openai/lib/ChatCompletionStream.d.ts new file mode 100644 index 0000000..3402c38 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStream.d.ts @@ -0,0 +1,149 @@ +import * as Core from 'openai/core'; +import { Completions, type ChatCompletion, type ChatCompletionChunk, type ChatCompletionCreateParams, type ChatCompletionCreateParamsBase } from 'openai/resources/chat/completions'; +import { AbstractChatCompletionRunner, type AbstractChatCompletionRunnerEvents } from "./AbstractChatCompletionRunner.js"; +import { type ReadableStream } from 'openai/_shims/index'; +export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { + content: (contentDelta: string, contentSnapshot: string) => void; + chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; +} +export type ChatCompletionStreamParams = Omit & { + stream?: true; +}; +export declare class ChatCompletionStream extends AbstractChatCompletionRunner implements AsyncIterable { + #private; + get currentChatCompletionSnapshot(): ChatCompletionSnapshot | undefined; + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream: ReadableStream): ChatCompletionStream; + static createChatCompletion(completions: Completions, params: ChatCompletionStreamParams, options?: Core.RequestOptions): ChatCompletionStream; + protected _createChatCompletion(completions: Completions, params: ChatCompletionCreateParams, options?: Core.RequestOptions): Promise; + protected _fromReadableStream(readableStream: ReadableStream, options?: Core.RequestOptions): Promise; + [Symbol.asyncIterator](): AsyncIterator; + toReadableStream(): ReadableStream; +} +/** + * Represents a streamed chunk of a chat completion response returned by model, + * based on the provided input. + */ +export interface ChatCompletionSnapshot { + /** + * A unique identifier for the chat completion. + */ + id: string; + /** + * A list of chat completion choices. Can be more than one if `n` is greater + * than 1. + */ + choices: Array; + /** + * The Unix timestamp (in seconds) of when the chat completion was created. + */ + created: number; + /** + * The model to generate the completion. + */ + model: string; + /** + * This fingerprint represents the backend configuration that the model runs with. + * + * Can be used in conjunction with the `seed` request parameter to understand when + * backend changes have been made that might impact determinism. + */ + system_fingerprint?: string; +} +export declare namespace ChatCompletionSnapshot { + interface Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + message: Choice.Message; + /** + * The reason the model stopped generating tokens. This will be `stop` if the model + * hit a natural stop point or a provided stop sequence, `length` if the maximum + * number of tokens specified in the request was reached, `content_filter` if + * content was omitted due to a flag from our content filters, or `function_call` + * if the model called a function. + */ + finish_reason: ChatCompletion.Choice['finish_reason'] | null; + /** + * Log probability information for the choice. + */ + logprobs: ChatCompletion.Choice.Logprobs | null; + /** + * The index of the choice in the list of choices. + */ + index: number; + } + namespace Choice { + /** + * A chat completion delta generated by streamed model responses. + */ + interface Message { + /** + * The contents of the chunk message. + */ + content?: string | null; + /** + * The name and arguments of a function that should be called, as generated by the + * model. + */ + function_call?: Message.FunctionCall; + tool_calls?: Array; + /** + * The role of the author of this message. + */ + role?: 'system' | 'user' | 'assistant' | 'function' | 'tool'; + } + namespace Message { + interface ToolCall { + /** + * The ID of the tool call. + */ + id?: string; + function?: ToolCall.Function; + /** + * The type of the tool. + */ + type?: 'function'; + } + namespace ToolCall { + interface Function { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + /** + * The name of the function to call. + */ + name?: string; + } + } + /** + * The name and arguments of a function that should be called, as generated by the + * model. + */ + interface FunctionCall { + /** + * The arguments to call the function with, as generated by the model in JSON + * format. Note that the model does not always generate valid JSON, and may + * hallucinate parameters not defined by your function schema. Validate the + * arguments in your code before calling your function. + */ + arguments?: string; + /** + * The name of the function to call. + */ + name?: string; + } + } + } +} +//# sourceMappingURL=ChatCompletionStream.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStream.d.ts.map b/node_modules/openai/lib/ChatCompletionStream.d.ts.map new file mode 100644 index 0000000..3fb8dac --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStream.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStream.d.ts","sourceRoot":"","sources":["../src/lib/ChatCompletionStream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,aAAa,CAAC;AAEpC,OAAO,EACL,WAAW,EACX,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,0BAA0B,EAC/B,KAAK,8BAA8B,EACpC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,4BAA4B,EAC5B,KAAK,kCAAkC,EACxC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG1D,MAAM,WAAW,0BAA2B,SA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AAE,MAAM,CAAC;gBAEnB;;mBAEG;gBACH,IAAI,CAAC,EAAE,MAAM,CAAC;aACf;SACF;KACF;CACF"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStream.js b/node_modules/openai/lib/ChatCompletionStream.js new file mode 100644 index 0000000..21c9e4c --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStream.js @@ -0,0 +1,294 @@ +"use strict"; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _ChatCompletionStream_instances, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_addChunk, _ChatCompletionStream_endRequest, _ChatCompletionStream_accumulateChatCompletion; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChatCompletionStream = void 0; +const error_1 = require("openai/error"); +const AbstractChatCompletionRunner_1 = require("./AbstractChatCompletionRunner.js"); +const streaming_1 = require("openai/streaming"); +class ChatCompletionStream extends AbstractChatCompletionRunner_1.AbstractChatCompletionRunner { + constructor() { + super(...arguments); + _ChatCompletionStream_instances.add(this); + _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); + } + get currentChatCompletionSnapshot() { + return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new ChatCompletionStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createChatCompletion(completions, params, options) { + const runner = new ChatCompletionStream(); + runner._run(() => runner._runChatCompletion(completions, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + async _createChatCompletion(completions, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + const stream = await completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const chunk of stream) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + } + if (stream.controller.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + this._connected(); + const stream = streaming_1.Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream) { + if (chatId && chatId !== chunk.id) { + // A new request has been made. + this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + chatId = chunk.id; + } + if (stream.controller.signal?.aborted) { + throw new error_1.APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + [(_ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { + if (this.ended) + return; + const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + this._emit('chunk', chunk, completion); + const delta = chunk.choices[0]?.delta?.content; + const snapshot = completion.choices[0]?.message; + if (delta != null && snapshot?.role === 'assistant' && snapshot?.content) { + this._emit('content', delta, snapshot.content); + } + }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { + if (this.ended) { + throw new error_1.OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + if (!snapshot) { + throw new error_1.OpenAIError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + return finalizeChatCompletion(snapshot); + }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { + var _a, _b, _c; + let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + ...rest, + choices: [], + }, "f"); + } + else { + Object.assign(snapshot, rest); + } + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) { + choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; + } + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } + else { + const { content, ...rest } = logprobs; + Object.assign(choice.logprobs, rest); + if (content) { + (_a = choice.logprobs).content ?? (_a.content = []); + choice.logprobs.content.push(...content); + } + } + } + if (finish_reason) + choice.finish_reason = finish_reason; + Object.assign(choice, other); + if (!delta) + continue; // Shouldn't happen; just in case. + const { content, function_call, role, tool_calls, ...rest } = delta; + Object.assign(choice.message, rest); + if (content) + choice.message.content = (choice.message.content || '') + content; + if (role) + choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } + else { + if (function_call.name) + choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + (_b = choice.message.function_call).arguments ?? (_b.arguments = ''); + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (tool_calls) { + if (!choice.message.tool_calls) + choice.message.tool_calls = []; + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = ((_c = choice.message.tool_calls)[index] ?? (_c[index] = {})); + Object.assign(tool_call, rest); + if (id) + tool_call.id = id; + if (type) + tool_call.type = type; + if (fn) + tool_call.function ?? (tool_call.function = { arguments: '' }); + if (fn?.name) + tool_call.function.name = fn.name; + if (fn?.arguments) + tool_call.function.arguments += fn.arguments; + } + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('chunk', (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader(chunk); + } + else { + pushQueue.push(chunk); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader(undefined); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve) => readQueue.push(resolve)).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + }; + } + toReadableStream() { + const stream = new streaming_1.Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +exports.ChatCompletionStream = ChatCompletionStream; +function finalizeChatCompletion(snapshot) { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + return { + ...rest, + id, + choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { + if (!finish_reason) + throw new error_1.OpenAIError(`missing finish_reason for choice ${index}`); + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. + if (!role) + throw new error_1.OpenAIError(`missing role for choice ${index}`); + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) + throw new error_1.OpenAIError(`missing function_call.arguments for choice ${index}`); + if (!name) + throw new error_1.OpenAIError(`missing function_call.name for choice ${index}`); + return { + ...choiceRest, + message: { content, function_call: { arguments: args, name }, role }, + finish_reason, + index, + logprobs, + }; + } + if (tool_calls) { + return { + ...choiceRest, + index, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id == null) + throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); + if (type == null) + throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + if (name == null) + throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); + if (args == null) + throw new error_1.OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); + return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; + }), + }, + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role }, + finish_reason, + index, + logprobs, + }; + }), + created, + model, + object: 'chat.completion', + ...(system_fingerprint ? { system_fingerprint } : {}), + }; +} +function str(x) { + return JSON.stringify(x); +} +//# sourceMappingURL=ChatCompletionStream.js.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStream.js.map b/node_modules/openai/lib/ChatCompletionStream.js.map new file mode 100644 index 0000000..d74cb2d --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStream.js","sourceRoot":"","sources":["../src/lib/ChatCompletionStream.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,wCAA8D;AAQ9D,oFAGwC;AAExC,gDAA0C;AAW1C,MAAa,oBACX,SAAQ,2DAAwD;IADlE;;;QAIE,sEAAmE;IA+NrE,CAAC;IA7NC,IAAI,6BAA6B;QAC/B,OAAO,uBAAA,IAAI,2DAA+B,CAAC;IAC7C,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,kBAAkB,CAAC,MAAsB;QAC9C,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,oBAAoB,CACzB,WAAwB,EACxB,MAAkC,EAClC,OAA6B;QAE7B,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CACf,MAAM,CAAC,kBAAkB,CACvB,WAAW,EACX,EAAE,GAAG,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,EAC3B,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,QAAQ,EAAE,EAAE,CACxF,CACF,CAAC;QACF,OAAO,MAAM,CAAC;IAChB,CAAC;IA4BkB,KAAK,CAAC,qBAAqB,CAC5C,WAAwB,EACxB,MAAkC,EAClC,OAA6B;QAE7B,MAAM,MAAM,GAAG,OAAO,EAAE,MAAM,CAAC;QAC/B,IAAI,MAAM,EAAE;YACV,IAAI,MAAM,CAAC,OAAO;gBAAE,IAAI,CAAC,UA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AAI,EAAE,QAAQ,EAAE,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC;wBACnF,CAAC,CAAC;qBACH;iBACF,CAAC;aACH;YACD,OAAO;gBACL,GAAG,UAAU;gBACb,OAAO,EAAE,EAAE,GAAG,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE;gBAC1C,aAAa;gBACb,KAAK;gBACL,QAAQ;aACT,CAAC;QACJ,CAAC,CACF;QACD,OAAO;QACP,KAAK;QACL,MAAM,EAAE,iBAAiB;QACzB,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACtD,CAAC;AACJ,CAAC;AAED,SAAS,GAAG,CAAC,CAAU;IACrB,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAC3B,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStream.mjs b/node_modules/openai/lib/ChatCompletionStream.mjs new file mode 100644 index 0000000..507fd98 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStream.mjs @@ -0,0 +1,290 @@ +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var _ChatCompletionStream_instances, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_addChunk, _ChatCompletionStream_endRequest, _ChatCompletionStream_accumulateChatCompletion; +import { OpenAIError, APIUserAbortError } from 'openai/error'; +import { AbstractChatCompletionRunner, } from "./AbstractChatCompletionRunner.mjs"; +import { Stream } from 'openai/streaming'; +export class ChatCompletionStream extends AbstractChatCompletionRunner { + constructor() { + super(...arguments); + _ChatCompletionStream_instances.add(this); + _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); + } + get currentChatCompletionSnapshot() { + return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new ChatCompletionStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createChatCompletion(completions, params, options) { + const runner = new ChatCompletionStream(); + runner._run(() => runner._runChatCompletion(completions, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + async _createChatCompletion(completions, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + const stream = await completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const chunk of stream) { + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + this._connected(); + const stream = Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream) { + if (chatId && chatId !== chunk.id) { + // A new request has been made. + this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + chatId = chunk.id; + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + [(_ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { + if (this.ended) + return; + const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + this._emit('chunk', chunk, completion); + const delta = chunk.choices[0]?.delta?.content; + const snapshot = completion.choices[0]?.message; + if (delta != null && snapshot?.role === 'assistant' && snapshot?.content) { + this._emit('content', delta, snapshot.content); + } + }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { + if (this.ended) { + throw new OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + if (!snapshot) { + throw new OpenAIError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + return finalizeChatCompletion(snapshot); + }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { + var _a, _b, _c; + let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + ...rest, + choices: [], + }, "f"); + } + else { + Object.assign(snapshot, rest); + } + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) { + choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; + } + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } + else { + const { content, ...rest } = logprobs; + Object.assign(choice.logprobs, rest); + if (content) { + (_a = choice.logprobs).content ?? (_a.content = []); + choice.logprobs.content.push(...content); + } + } + } + if (finish_reason) + choice.finish_reason = finish_reason; + Object.assign(choice, other); + if (!delta) + continue; // Shouldn't happen; just in case. + const { content, function_call, role, tool_calls, ...rest } = delta; + Object.assign(choice.message, rest); + if (content) + choice.message.content = (choice.message.content || '') + content; + if (role) + choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } + else { + if (function_call.name) + choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + (_b = choice.message.function_call).arguments ?? (_b.arguments = ''); + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (tool_calls) { + if (!choice.message.tool_calls) + choice.message.tool_calls = []; + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = ((_c = choice.message.tool_calls)[index] ?? (_c[index] = {})); + Object.assign(tool_call, rest); + if (id) + tool_call.id = id; + if (type) + tool_call.type = type; + if (fn) + tool_call.function ?? (tool_call.function = { arguments: '' }); + if (fn?.name) + tool_call.function.name = fn.name; + if (fn?.arguments) + tool_call.function.arguments += fn.arguments; + } + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('chunk', (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader(chunk); + } + else { + pushQueue.push(chunk); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader(undefined); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve) => readQueue.push(resolve)).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + }; + } + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +function finalizeChatCompletion(snapshot) { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + return { + ...rest, + id, + choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { + if (!finish_reason) + throw new OpenAIError(`missing finish_reason for choice ${index}`); + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. + if (!role) + throw new OpenAIError(`missing role for choice ${index}`); + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) + throw new OpenAIError(`missing function_call.arguments for choice ${index}`); + if (!name) + throw new OpenAIError(`missing function_call.name for choice ${index}`); + return { + ...choiceRest, + message: { content, function_call: { arguments: args, name }, role }, + finish_reason, + index, + logprobs, + }; + } + if (tool_calls) { + return { + ...choiceRest, + index, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); + if (type == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + if (name == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); + if (args == null) + throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); + return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; + }), + }, + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role }, + finish_reason, + index, + logprobs, + }; + }), + created, + model, + object: 'chat.completion', + ...(system_fingerprint ? { system_fingerprint } : {}), + }; +} +function str(x) { + return JSON.stringify(x); +} +//# sourceMappingURL=ChatCompletionStream.mjs.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStream.mjs.map b/node_modules/openai/lib/ChatCompletionStream.mjs.map new file mode 100644 index 0000000..814f6d3 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStream.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStream.mjs","sourceRoot":"","sources":["../src/lib/ChatCompletionStream.ts"],"names":[],"mappings":";;;;;;;;;;;;OACO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,cAAc;OAQtD,EACL,4BAA4B,GAE7B;OAEM,EAAE,MAAM,EAAE,MAAM,kBAAkB;AAWzC,MAAM,OAAO,oBACX,SAAQ,4BAAwD;IADlE;;;QAIE,sEAAmE;IA+NrE,CAAC;IA7NC,IAAI,6BAA6B;QAC/B,OAAO,uBAAA,IAAI,2DAA+B,CAAC;IAC7C,CAAC;IAED;;;;;;OAMG;IACH,MAAM,CAAC,kBAAkB,CAAC,MAAsB;QAC9C,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,oBAAoB,CACzB,WAAwB,EACxB,MAAkC,EAClC,OAA6B;QAE7B,MAAM,MAAM,GAAG,IAAI,oBAAoB,EAAE,CAAC;QAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CACf,MAAM,CAAC,kBAAkB,CACvB,WAAW,EACX,EAAE,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,QAAQ,CAAC,EAAE,CAAC,CAAC;4BAC7F,IAAI,IAAI,IAAI,IAAI;gCACd,MAAM,IAAI,WAAW,CACnB,mBAAmB,KAAK,gBAAgB,CAAC,oBAAoB,GAAG,CAAC,QAAQ,CAAC,EAAE,CAC7E,CAAC;4BACJ,IAAI,IAAI,IAAI,IAAI;gCACd,MAAM,IAAI,WAAW,CACnB,mBAAmB,KAAK,gBAAgB,CAAC,yBAAyB,GAAG,CAAC,QAAQ,CAAC,EAAE,CAClF,CAAC;4BAEJ,OAAO,EAAE,GAAG,QAAQ,EAAE,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,EAAE,GAAG,MAAM,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,CAAC;wBACnF,CAAC,CAAC;qBACH;iBACF,CAAC;aACH;YACD,OAAO;gBACL,GAAG,UAAU;gBACb,OAAO,EAAE,EAAE,GAAG,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE;gBAC1C,aAAa;gBACb,KAAK;gBACL,QAAQ;aACT,CAAC;QACJ,CAAC,CACF;QACD,OAAO;QACP,KAAK;QACL,MAAM,EAAE,iBAAiB;QACzB,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACtD,CAAC;AACJ,CAAC;AAED,SAAS,GAAG,CAAC,CAAU;IACrB,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAC3B,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts b/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts new file mode 100644 index 0000000..98b53e2 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts @@ -0,0 +1,22 @@ +import { Completions, type ChatCompletionChunk, type ChatCompletionCreateParamsStreaming } from 'openai/resources/chat/completions'; +import { RunnerOptions, type AbstractChatCompletionRunnerEvents } from "./AbstractChatCompletionRunner.js"; +import { type ReadableStream } from 'openai/_shims/index'; +import { RunnableTools, type BaseFunctionsArgs, type RunnableFunctions } from "./RunnableFunction.js"; +import { ChatCompletionSnapshot, ChatCompletionStream } from "./ChatCompletionStream.js"; +export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { + content: (contentDelta: string, contentSnapshot: string) => void; + chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; +} +export type ChatCompletionStreamingFunctionRunnerParams = Omit & { + functions: RunnableFunctions; +}; +export type ChatCompletionStreamingToolRunnerParams = Omit & { + tools: RunnableTools; +}; +export declare class ChatCompletionStreamingRunner extends ChatCompletionStream implements AsyncIterable { + static fromReadableStream(stream: ReadableStream): ChatCompletionStreamingRunner; + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions: Completions, params: ChatCompletionStreamingFunctionRunnerParams, options?: RunnerOptions): ChatCompletionStreamingRunner; + static runTools(completions: Completions, params: ChatCompletionStreamingToolRunnerParams, options?: RunnerOptions): ChatCompletionStreamingRunner; +} +//# sourceMappingURL=ChatCompletionStreamingRunner.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts.map b/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts.map new file mode 100644 index 0000000..868a35f --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStreamingRunner.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStreamingRunner.d.ts","sourceRoot":"","sources":["../src/lib/ChatCompletionStreamingRunner.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,KAAK,mBAAmB,EACxB,KAAK,mCAAmC,EACzC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,KAAK,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AACxG,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,EAAE,aAAa,EAAE,KAA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/lib/ChatCompletionStreamingRunner.js b/node_modules/openai/lib/ChatCompletionStreamingRunner.js new file mode 100644 index 0000000..e926b27 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStreamingRunner.js @@ -0,0 +1,32 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChatCompletionStreamingRunner = void 0; +const ChatCompletionStream_1 = require("./ChatCompletionStream.js"); +class ChatCompletionStreamingRunner extends ChatCompletionStream_1.ChatCompletionStream { + static fromReadableStream(stream) { + const runner = new ChatCompletionStreamingRunner(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions, params, options) { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + static runTools(completions, params, options) { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } +} +exports.ChatCompletionStreamingRunner = ChatCompletionStreamingRunner; +//# sourceMappingURL=ChatCompletionStreamingRunner.js.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStreamingRunner.js.map b/node_modules/openai/lib/ChatCompletionStreamingRunner.js.map new file mode 100644 index 0000000..2f1c6eb --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStreamingRunner.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStreamingRunner.js","sourceRoot":"","sources":["../src/lib/ChatCompletionStreamingRunner.ts"],"names":[],"mappings":";;;AAQA,oEAAsF;AAqBtF,MAAa,6BACX,SAAQ,2CAAoB;IAG5B,MAAM,CAAU,kBAAkB,CAAC,MAAsB;QACvD,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAwB,EACxB,MAAsD,EACtD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,cAAc,EAAE;SAC9E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,WAAwB,EACxB,MAAkD,EAClD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE;SAC1E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAtCD,sEAsCC"} \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs b/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs new file mode 100644 index 0000000..8860e66 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs @@ -0,0 +1,28 @@ +import { ChatCompletionStream } from "./ChatCompletionStream.mjs"; +export class ChatCompletionStreamingRunner extends ChatCompletionStream { + static fromReadableStream(stream) { + const runner = new ChatCompletionStreamingRunner(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + /** @deprecated - please use `runTools` instead. */ + static runFunctions(completions, params, options) { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' }, + }; + runner._run(() => runner._runFunctions(completions, params, opts)); + return runner; + } + static runTools(completions, params, options) { + const runner = new ChatCompletionStreamingRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(completions, params, opts)); + return runner; + } +} +//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map \ No newline at end of file diff --git a/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map b/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map new file mode 100644 index 0000000..9df8909 --- /dev/null +++ b/node_modules/openai/lib/ChatCompletionStreamingRunner.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ChatCompletionStreamingRunner.mjs","sourceRoot":"","sources":["../src/lib/ChatCompletionStreamingRunner.ts"],"names":[],"mappings":"OAQO,EAA0B,oBAAoB,EAAE;AAqBvD,MAAM,OAAO,6BACX,SAAQ,oBAAoB;IAG5B,MAAM,CAAU,kBAAkB,CAAC,MAAsB;QACvD,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC;QACtD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,mDAAmD;IACnD,MAAM,CAAC,YAAY,CACjB,WAAwB,EACxB,MAAsD,EACtD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,cAAc,EAAE;SAC9E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QACnE,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,QAAQ,CACb,WAAwB,EACxB,MAAkD,EAClD,OAAuB;QAEvB,MAAM,MAAM,GAAG,IAAI,6BAA6B,EAAE,CAAC;QACnD,MAAM,IAAI,GAAG;YACX,GAAG,OAAO;YACV,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,2BAA2B,EAAE,UAAU,EAAE;SAC1E,CAAC;QACF,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;QAC/D,OAAO,MAAM,CAAC;IAChB,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/openai/lib/RunnableFunction.d.ts b/node_modules/openai/lib/RunnableFunction.d.ts new file mode 100644 index 0000000..8325604 --- /dev/null +++ b/node_modules/openai/lib/RunnableFunction.d.ts @@ -0,0 +1,95 @@ +import { type ChatCompletionRunner } from "./ChatCompletionRunner.js"; +import { type ChatCompletionStreamingRunner } from "./ChatCompletionStreamingRunner.js"; +import { JSONSchema } from "./jsonschema.js"; +type PromiseOrValue = T | Promise; +export type RunnableFunctionWithParse = { + /** + * @param args the return value from `parse`. + * @param runner the runner evaluating this callback. + * @returns a string to send back to OpenAI. + */ + function: (args: Args, runner: ChatCompletionRunner | ChatCompletionStreamingRunner) => PromiseOrValue; + /** + * @param input the raw args from the OpenAI function call. + * @returns the parsed arguments to pass to `function` + */ + parse: (input: string) => PromiseOrValue; + /** + * The parameters the function accepts, describes as a JSON Schema object. + */ + parameters: JSONSchema; + /** + * A description of what the function does, used by the model to choose when and how to call the function. + */ + description: string; + /** + * The name of the function to be called. Will default to function.name if omitted. + */ + name?: string | undefined; +}; +export type RunnableFunctionWithoutParse = { + /** + * @param args the raw args from the OpenAI function call. + * @returns a string to send back to OpenAI + */ + function: (args: string, runner: ChatCompletionRunner | ChatCompletionStreamingRunner) => PromiseOrValue; + /** + * The parameters the function accepts, describes as a JSON Schema object. + */ + parameters: JSONSchema; + /** + * A description of what the function does, used by the model to choose when and how to call the function. + */ + description: string; + /** + * The name of the function to be called. Will default to function.name if omitted. + */ + name?: string | undefined; +}; +export type RunnableFunction = Args extends string ? RunnableFunctionWithoutParse : Args extends object ? RunnableFunctionWithParse : never; +export type RunnableToolFunction = Args extends string ? RunnableToolFunctionWithoutParse : Args extends object ? RunnableToolFunctionWithParse : never; +export type RunnableToolFunctionWithoutParse = { + type: 'function'; + function: RunnableFunctionWithoutParse; +}; +export type RunnableToolFunctionWithParse = { + type: 'function'; + function: RunnableFunctionWithParse; +}; +export declare function isRunnableFunctionWithParse(fn: any): fn is RunnableFunctionWithParse; +export type BaseFunctionsArgs = readonly (object | string)[]; +export type RunnableFunctions = [ + any[] +] extends [FunctionsArgs] ? readonly RunnableFunction[] : { + [Index in keyof FunctionsArgs]: Index extends number ? RunnableFunction : FunctionsArgs[Index]; +}; +export type RunnableTools = [ + any[] +] extends [FunctionsArgs] ? readonly RunnableToolFunction[] : { + [Index in keyof FunctionsArgs]: Index extends number ? RunnableToolFunction : FunctionsArgs[Index]; +}; +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + * + * @deprecated - please use ParsingToolFunction instead. + */ +export declare class ParsingFunction { + function: RunnableFunctionWithParse['function']; + parse: RunnableFunctionWithParse['parse']; + parameters: RunnableFunctionWithParse['parameters']; + description: RunnableFunctionWithParse['description']; + name?: RunnableFunctionWithParse['name']; + constructor(input: RunnableFunctionWithParse); +} +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +export declare class ParsingToolFunction { + type: 'function'; + function: RunnableFunctionWithParse; + constructor(input: RunnableFunctionWithParse); +} +export {}; +//# sourceMappingURL=RunnableFunction.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/lib/RunnableFunction.d.ts.map b/node_modules/openai/lib/RunnableFunction.d.ts.map new file mode 100644 index 0000000..2969604 --- /dev/null +++ b/node_modules/openai/lib/RunnableFunction.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"RunnableFunction.d.ts","sourceRoot":"","sources":["../src/lib/RunnableFunction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,KAAK,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AACrF,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,KAAK,cAAc,CAAC,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAExC,MAAM,MAAM,yBAAyB,CAAC,IAAI,SAAS,MAAM,IAAI;IAC3D;;;;OAIG;IACH,QAAQ,EAAE,CACR,IAAI,EAAE,IAAI,EACV,MAAM,EAAE,oBAAoB,GAAG,6BAA6B,KACzD,cAAc,CAAC,OAAO,CAAC,CAAC;IAC7B;;;OAGG;IACH,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,cAAc,CAAC,IAAI,CAAC,CAAC;IAC/C;;OAEG;IACH,UAAU,EAAE,UAAU,CAAC;IACvB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC;;;OAGG;IACH,QAAQ,EAAE,CACR,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,oBAAoB,GAAG,6BAA6B,KACzD,cAAc,CAAC,OAAO,CAAC,CAAC;IAC7B;;OAEG;IACH,UAAU,EAAE,UAAU,CAAC;IACvB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,IAAI,CAAC,EA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EAAE;CAAC,SAAS,CAAC,aAAa,CAAC,GAAG,SAAS,oBAAoB,CAAC,GAAG,CAAC,EAAE,GACpE;KACG,KAAK,IAAI,MAAM,aAAa,GAAG,KAAK,SAAS,MAAM,GAAG,oBAAoB,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,GAC/F,aAAa,CAAC,KAAK,CAAC;CACvB,CAAC;AAEN;;;;;GAKG;AACH,qBAAa,eAAe,CAAC,IAAI,SAAS,MAAM;IAC9C,QAAQ,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,UAAU,CAAC,CAAC;IACtD,KAAK,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC;IAChD,UAAU,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC;IAC1D,WAAW,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,aAAa,CAAC,CAAC;IAC5D,IAAI,CAAC,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC;gBAEnC,KAAK,EAAE,yBAAyB,CAAC,IAAI,CAAC;CAOnD;AAED;;;GAGG;AACH,qBAAa,mBAAmB,CAAC,IAAI,SAAS,MAAM;IAClD,IAAI,EAAE,UAAU,CAAC;IACjB,QAAQ,EAAE,yBAAyB,CAAC,IAAI,CAAC,CAAC;gBAE9B,KAAK,EAAE,yBAAyB,CAAC,IAAI,CAAC;CAInD"} \ No newline at end of file diff --git a/node_modules/openai/lib/RunnableFunction.js b/node_modules/openai/lib/RunnableFunction.js new file mode 100644 index 0000000..a079269 --- /dev/null +++ b/node_modules/openai/lib/RunnableFunction.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ParsingToolFunction = exports.ParsingFunction = exports.isRunnableFunctionWithParse = void 0; +function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === 'function'; +} +exports.isRunnableFunctionWithParse = isRunnableFunctionWithParse; +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + * + * @deprecated - please use ParsingToolFunction instead. + */ +class ParsingFunction { + constructor(input) { + this.function = input.function; + this.parse = input.parse; + this.parameters = input.parameters; + this.description = input.description; + this.name = input.name; + } +} +exports.ParsingFunction = ParsingFunction; +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +class ParsingToolFunction { + constructor(input) { + this.type = 'function'; + this.function = input; + } +} +exports.ParsingToolFunction = ParsingToolFunction; +//# sourceMappingURL=RunnableFunction.js.map \ No newline at end of file diff --git a/node_modules/openai/lib/RunnableFunction.js.map b/node_modules/openai/lib/RunnableFunction.js.map new file mode 100644 index 0000000..df6ac8b --- /dev/null +++ b/node_modules/openai/lib/RunnableFunction.js.map @@ -0,0 +1 @@ +{"version":3,"file":"RunnableFunction.js","sourceRoot":"","sources":["../src/lib/RunnableFunction.ts"],"names":[],"mappings":";;;AA6EA,SAAgB,2BAA2B,CACzC,EAAO;IAEP,OAAO,OAAQ,EAAU,CAAC,KAAK,KAAK,UAAU,CAAC;AACjD,CAAC;AAJD,kEAIC;AAkBD;;;;;GAKG;AACH,MAAa,eAAe;IAO1B,YAAY,KAAsC;QAChD,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QACnC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QACrC,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IACzB,CAAC;CACF;AAdD,0CAcC;AAED;;;GAGG;AACH,MAAa,mBAAmB;IAI9B,YAAY,KAAsC;QAChD,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;IACxB,CAAC;CACF;AARD,kDAQC"} \ No newline at end of file diff --git a/node_modules/openai/lib/RunnableFunction.mjs b/node_modules/openai/lib/RunnableFunction.mjs new file mode 100644 index 0000000..c9ef113 --- /dev/null +++ b/node_modules/openai/lib/RunnableFunction.mjs @@ -0,0 +1,29 @@ +export function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === 'function'; +} +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + * + * @deprecated - please use ParsingToolFunction instead. + */ +export class ParsingFunction { + constructor(input) { + this.function = input.function; + this.parse = input.parse; + this.parameters = input.parameters; + this.description = input.description; + this.name = input.name; + } +} +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +export class ParsingToolFunction { + constructor(input) { + this.type = 'function'; + this.function = input; + } +} +//# sourceMappingURL=RunnableFunction.mjs.map \ No newline at end of file diff --git a/node_modules/openai/lib/RunnableFunction.mjs.map b/node_modules/openai/lib/RunnableFunction.mjs.map new file mode 100644 index 0000000..df60b15 --- /dev/null +++ b/node_modules/openai/lib/RunnableFunction.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"RunnableFunction.mjs","sourceRoot":"","sources":["../src/lib/RunnableFunction.ts"],"names":[],"mappings":"AA6EA,MAAM,UAAU,2BAA2B,CACzC,EAAO;IAEP,OAAO,OAAQ,EAAU,CAAC,KAAK,KAAK,UAAU,CAAC;AACjD,CAAC;AAkBD;;;;;GAKG;AACH,MAAM,OAAO,eAAe;IAO1B,YAAY,KAAsC;QAChD,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;QACzB,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;QACnC,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAC;QACrC,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;IACzB,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,OAAO,mBAAmB;IAI9B,YAAY,KAAsC;QAChD,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;IACxB,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/openai/lib/chatCompletionUtils.d.ts b/node_modules/openai/lib/chatCompletionUtils.d.ts new file mode 100644 index 0000000..fcc1b3d --- /dev/null +++ b/node_modules/openai/lib/chatCompletionUtils.d.ts @@ -0,0 +1,6 @@ +import { type ChatCompletionAssistantMessageParam, type ChatCompletionFunctionMessageParam, type ChatCompletionMessageParam, type ChatCompletionToolMessageParam } from 'openai/resources'; +export declare const isAssistantMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionAssistantMessageParam; +export declare const isFunctionMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionFunctionMessageParam; +export declare const isToolMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionToolMessageParam; +export declare function isPresent(obj: T | null | undefined): obj is T; +//# sourceMappingURL=chatCompletionUtils.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/lib/chatCompletionUtils.d.ts.map b/node_modules/openai/lib/chatCompletionUtils.d.ts.map new file mode 100644 index 0000000..62b23b3 --- /dev/null +++ b/node_modules/openai/lib/chatCompletionUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"chatCompletionUtils.d.ts","sourceRoot":"","sources":["../src/lib/chatCompletionUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,mCAAmC,EACxC,KAAK,kCAAkC,EACvC,KAAK,0BAA0B,EAC/B,KAAK,8BAA8B,EACpC,MAAM,kBAAkB,CAAC;AAE1B,eAAO,MAAM,kBAAkB,YACpB,0BAA0B,GAAG,IAAI,GAAG,SAAS,mDAGvD,CAAC;AAEF,eAAO,MAAM,iBAAiB,YACnB,0BAA0B,GAAG,IAAI,GAAG,SAAS,kDAGvD,CAAC;AAEF,eAAO,MAAM,aAAa,YACf,0BAA0B,GAAG,IAAI,GAAG,SAAS,8CAGvD,CAAC;AAEF,wBAAgB,SAAS,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,IAAI,GAAG,SAAS,GAAG,GAAG,IAAI,CAAC,CAEhE"} \ No newline at end of file diff --git a/node_modules/openai/lib/chatCompletionUtils.js b/node_modules/openai/lib/chatCompletionUtils.js new file mode 100644 index 0000000..911545f --- /dev/null +++ b/node_modules/openai/lib/chatCompletionUtils.js @@ -0,0 +1,20 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isPresent = exports.isToolMessage = exports.isFunctionMessage = exports.isAssistantMessage = void 0; +const isAssistantMessage = (message) => { + return message?.role === 'assistant'; +}; +exports.isAssistantMessage = isAssistantMessage; +const isFunctionMessage = (message) => { + return message?.role === 'function'; +}; +exports.isFunctionMessage = isFunctionMessage; +const isToolMessage = (message) => { + return message?.role === 'tool'; +}; +exports.isToolMessage = isToolMessage; +function isPresent(obj) { + return obj != null; +} +exports.isPresent = isPresent; +//# sourceMappingURL=chatCompletionUtils.js.map \ No newline at end of file diff --git a/node_modules/openai/lib/chatCompletionUtils.js.map b/node_modules/openai/lib/chatCompletionUtils.js.map new file mode 100644 index 0000000..574356f --- /dev/null +++ b/node_modules/openai/lib/chatCompletionUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chatCompletionUtils.js","sourceRoot":"","sources":["../src/lib/chatCompletionUtils.ts"],"names":[],"mappings":";;;AAOO,MAAM,kBAAkB,GAAG,CAChC,OAAsD,EACN,EAAE;IAClD,OAAO,OAAO,EAAE,IAAI,KAAK,WAAW,CAAC;AACvC,CAAC,CAAC;AAJW,QAAA,kBAAkB,sBAI7B;AAEK,MAAM,iBAAiB,GAAG,CAC/B,OAAsD,EACP,EAAE;IACjD,OAAO,OAAO,EAAE,IAAI,KAAK,UAAU,CAAC;AACtC,CAAC,CAAC;AAJW,QAAA,iBAAiB,qBAI5B;AAEK,MAAM,aAAa,GAAG,CAC3B,OAAsD,EACX,EAAE;IAC7C,OAAO,OAAO,EAAE,IAAI,KAAK,MAAM,CAAC;AAClC,CAAC,CAAC;AAJW,QAAA,aAAa,iBAIxB;AAEF,SAAgB,SAAS,CAAI,GAAyB;IACpD,OAAO,GAAG,IAAI,IAAI,CAAC;AACrB,CAAC;AAFD,8BAEC"} \ No newline at end of file diff --git a/node_modules/openai/lib/chatCompletionUtils.mjs b/node_modules/openai/lib/chatCompletionUtils.mjs new file mode 100644 index 0000000..b283429 --- /dev/null +++ b/node_modules/openai/lib/chatCompletionUtils.mjs @@ -0,0 +1,13 @@ +export const isAssistantMessage = (message) => { + return message?.role === 'assistant'; +}; +export const isFunctionMessage = (message) => { + return message?.role === 'function'; +}; +export const isToolMessage = (message) => { + return message?.role === 'tool'; +}; +export function isPresent(obj) { + return obj != null; +} +//# sourceMappingURL=chatCompletionUtils.mjs.map \ No newline at end of file diff --git a/node_modules/openai/lib/chatCompletionUtils.mjs.map b/node_modules/openai/lib/chatCompletionUtils.mjs.map new file mode 100644 index 0000000..00e60f6 --- /dev/null +++ b/node_modules/openai/lib/chatCompletionUtils.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"chatCompletionUtils.mjs","sourceRoot":"","sources":["../src/lib/chatCompletionUtils.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAChC,OAAsD,EACN,EAAE;IAClD,OAAO,OAAO,EAAE,IAAI,KAAK,WAAW,CAAC;AACvC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAC/B,OAAsD,EACP,EAAE;IACjD,OAAO,OAAO,EAAE,IAAI,KAAK,UAAU,CAAC;AACtC,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,OAAsD,EACX,EAAE;IAC7C,OAAO,OAAO,EAAE,IAAI,KAAK,MAAM,CAAC;AAClC,CAAC,CAAC;AAEF,MAAM,UAAU,SAAS,CAAI,GAAyB;IACpD,OAAO,GAAG,IAAI,IAAI,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/node_modules/openai/lib/jsonschema.d.ts b/node_modules/openai/lib/jsonschema.d.ts new file mode 100644 index 0000000..0a569e9 --- /dev/null +++ b/node_modules/openai/lib/jsonschema.d.ts @@ -0,0 +1,106 @@ +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchemaTypeName = ({} & string) | 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null'; +/** + * Primitive type + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 + */ +export type JSONSchemaType = string | number | boolean | JSONSchemaObject | JSONSchemaArray | null; +export interface JSONSchemaObject { + [key: string]: JSONSchemaType; +} +export interface JSONSchemaArray extends Array { +} +/** + * Meta schema + * + * Recommended values: + * - 'http://json-schema.org/schema#' + * - 'http://json-schema.org/hyper-schema#' + * - 'http://json-schema.org/draft-07/schema#' + * - 'http://json-schema.org/draft-07/hyper-schema#' + * + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 + */ +export type JSONSchemaVersion = string; +/** + * JSON Schema v7 + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 + */ +export type JSONSchemaDefinition = JSONSchema | boolean; +export interface JSONSchema { + $id?: string | undefined; + $comment?: string | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1 + */ + type?: JSONSchemaTypeName | JSONSchemaTypeName[] | undefined; + enum?: JSONSchemaType[] | undefined; + const?: JSONSchemaType | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2 + */ + multipleOf?: number | undefined; + maximum?: number | undefined; + exclusiveMaximum?: number | undefined; + minimum?: number | undefined; + exclusiveMinimum?: number | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3 + */ + maxLength?: number | undefined; + minLength?: number | undefined; + pattern?: string | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4 + */ + items?: JSONSchemaDefinition | JSONSchemaDefinition[] | undefined; + additionalItems?: JSONSchemaDefinition | undefined; + maxItems?: number | undefined; + minItems?: number | undefined; + uniqueItems?: boolean | undefined; + contains?: JSONSchemaDefinition | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5 + */ + maxProperties?: number | undefined; + minProperties?: number | undefined; + required?: string[] | undefined; + properties?: { + [key: string]: JSONSchemaDefinition; + } | undefined; + patternProperties?: { + [key: string]: JSONSchemaDefinition; + } | undefined; + additionalProperties?: JSONSchemaDefinition | undefined; + propertyNames?: JSONSchemaDefinition | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6 + */ + if?: JSONSchemaDefinition | undefined; + then?: JSONSchemaDefinition | undefined; + else?: JSONSchemaDefinition | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7 + */ + allOf?: JSONSchemaDefinition[] | undefined; + anyOf?: JSONSchemaDefinition[] | undefined; + oneOf?: JSONSchemaDefinition[] | undefined; + not?: JSONSchemaDefinition | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7 + */ + format?: string | undefined; + /** + * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10 + */ + title?: string | undefined; + description?: string | undefined; + default?: JSONSchemaType | undefined; + readOnly?: boolean | undefined; + writeOnly?: boolean | undefined; + examples?: JSONSchemaType | undefined; +} +//# sourceMappingURL=jsonschema.d.ts.map \ No newline at end of file diff --git a/node_modules/openai/lib/jsonschema.d.ts.map b/node_modules/openai/lib/jsonschema.d.ts.map new file mode 100644 index 0000000..6e5c623 --- /dev/null +++ b/node_modules/openai/lib/jsonschema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonschema.d.ts","sourceRoot":"","sources":["../src/lib/jsonschema.ts"],"names":[],"mappings":"AASA;;;GAGG;AAC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C;IAEvC;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE5B;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,OAAO,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IACrC,QAAQ,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC/B,SAAS,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAChC,QAAQ,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;CACvC"} \ No newline at end of file diff --git a/node_modules/openai/lib/jsonschema.js b/node_modules/openai/lib/jsonschema.js new file mode 100644 index 0000000..bf2a34e --- /dev/null +++ b/node_modules/openai/lib/jsonschema.js @@ -0,0 +1,11 @@ +"use strict"; +// File mostly copied from @types/json-schema, but stripped down a bit for brevity +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/817274f3280152ba2929a6067c93df8b34c4c9aa/types/json-schema/index.d.ts +// +// ================================================================================================== +// JSON Schema Draft 07 +// ================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +// -------------------------------------------------------------------------------------------------- +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=jsonschema.js.map \ No newline at end of file diff --git a/node_modules/openai/lib/jsonschema.js.map b/node_modules/openai/lib/jsonschema.js.map new file mode 100644 index 0000000..30d08a7 --- /dev/null +++ b/node_modules/openai/lib/jsonschema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonschema.js","sourceRoot":"","sources":["../src/lib/jsonschema.ts"],"names":[],"mappings":";AAAA,kFAAkF;AAClF,gIAAgI;AAChI,EAAE;AACF,qGAAqG;AACrG,uBAAuB;AACvB,qGAAqG;AACrG,uEAAuE;AACvE,qGAAqG"} \ No newline at end of file diff --git a/node_modules/openai/lib/jsonschema.mjs b/node_modules/openai/lib/jsonschema.mjs new file mode 100644 index 0000000..047481b --- /dev/null +++ b/node_modules/openai/lib/jsonschema.mjs @@ -0,0 +1,10 @@ +// File mostly copied from @types/json-schema, but stripped down a bit for brevity +// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/817274f3280152ba2929a6067c93df8b34c4c9aa/types/json-schema/index.d.ts +// +// ================================================================================================== +// JSON Schema Draft 07 +// ================================================================================================== +// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 +// -------------------------------------------------------------------------------------------------- +export {}; +//# sourceMappingURL=jsonschema.mjs.map \ No newline at end of file diff --git a/node_modules/openai/lib/jsonschema.mjs.map b/node_modules/openai/lib/jsonschema.mjs.map new file mode 100644 index 0000000..4603e80 --- /dev/null +++ b/node_modules/openai/lib/jsonschema.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonschema.mjs","sourceRoot":"","sources":["../src/lib/jsonschema.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,gIAAgI;AAChI,EAAE;AACF,qGAAqG;AACrG,uBAAuB;AACvB,qGAAqG;AACrG,uEAAuE;AACvE,qGAAqG"} \ No newline at end of file diff --git a/node_modules/openai/node_modules/@types/node/LICENSE b/node_modules/openai/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/openai/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/openai/node_modules/@types/node/README.md b/node_modules/openai/node_modules/@types/node/README.md new file mode 100644 index 0000000..2550d5a --- /dev/null +++ b/node_modules/openai/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/v18. + +### Additional Details + * Last updated: Wed, 24 Jan 2024 06:08:24 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), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [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), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky). diff --git a/node_modules/openai/node_modules/@types/node/assert.d.ts b/node_modules/openai/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..e4a8a78 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/assert.d.ts @@ -0,0 +1,985 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + 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/ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + 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 '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 that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * 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: this, arguments: [1, 2, 3 ] }]); + * ``` + * + * @since v18.8.0, v16.18.0 + * @param fn + * @returns An Array with 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 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // 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() + * 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 of objects containing information about the wrapper functions returned by `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 + * tracker.getCalls(callsfunc).length === 1; + * + * tracker.reset(callsfunc); + * 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 `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from '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 '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/ban-types + 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 '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 '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 '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 '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 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(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 '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 '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 '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 '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: + * 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: + * 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 '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 '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 '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 '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 '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 '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 '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 '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` 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 `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from '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 '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` 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 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from '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 '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 `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 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 '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 `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 v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + > + & { + (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; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/node_modules/openai/node_modules/@types/node/assert/strict.d.ts b/node_modules/openai/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..f333913 --- /dev/null +++ b/node_modules/openai/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/openai/node_modules/@types/node/async_hooks.d.ts b/node_modules/openai/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..1ae6885 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,522 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * 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`. + * @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 'fs'; + * import { executionAsyncId, executionAsyncResource } from '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 'http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook + * } from '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`. + * @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. + * @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 '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 '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. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @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 & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func, + ): Func & { + asyncResource: AsyncResource; + }; + /** + * 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; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `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 'http'; + * import { AsyncLocalStorage } from '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 + * // 1: start + * // 0: finish + * // 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 { + /** + * Binds the given function to the current execution context. + * @since v18.16.0 + * @param fn The function to bind to the current execution context. + * @returns A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func & { + asyncResource: AsyncResource; + }; + /** + * 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. + * @since v18.16.0 + */ + static snapshot(): ((fn: (...args: TArgs) => R, ...args: TArgs) => R) & { + asyncResource: AsyncResource; + }; + /** + * 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; + /** + * 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; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/node_modules/openai/node_modules/@types/node/buffer.d.ts b/node_modules/openai/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..cfc1f39 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2321 @@ +/** + * `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 '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/v18.0.0/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export const 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" | "utf16le" | "ucs2" | "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 '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; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new(size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * 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; + /** + * 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 (WHATWG) `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 `require('node:os').EOL`. + */ + 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. + * @experimental + * @since v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + + import { Blob as NodeBlob } from "buffer"; + // This conditional type will be the existing global Blob in a browser, or + // the copy below in a Node environment. + type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob; + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * 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 { + /** + * 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: Uint8Array): 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 containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: readonly any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): 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 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * 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( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | readonly number[]): Buffer; + from(data: WithImplicitCoercion): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: "string"): string; + }, + encoding?: BufferEncoding, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from '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 '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 '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 | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * 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 '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`. + * @since v18.16.0 + * @param view The `TypedArray` to copy. + * @param offset The starting offset within `view`. + * @param length The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * 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 '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; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from '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 '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_INVALID_ARG_VALUE` 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 '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)`, `Buffer.concat()`, and the + * deprecated`new Buffer(size)` constructor only when `size` is less than or equal + * to `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_INVALID_ARG_VALUE` 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 KB 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 '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; + /** + * 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 extends Uint8Array { + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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; + /** + * 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 '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 '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 '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; + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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(): Buffer; + /** + * 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 '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(): Buffer; + /** + * 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 '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(): Buffer; + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `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 '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 '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`. + * @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; + /** + * 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 '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 '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; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from '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 '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; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from '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; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + 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 `require('node:buffer').Blob` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { + onmessage: any; + Blob: infer T; + } ? T + : typeof NodeBlob; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/node_modules/openai/node_modules/@types/node/child_process.d.ts b/node_modules/openai/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..6c7a2c1 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1544 @@ +/** + * The `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 + * const { spawn } = require('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 `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/v18.0.0/lib/child_process.js) + */ +declare module "child_process" { + import { ObjectEncodingOptions } from "node:fs"; + import { Abortable, EventEmitter } from "node:events"; + 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; + /** + * 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 `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 + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` 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` 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 currently 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 + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('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 + * const { spawn } = require('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 + * const { spawn } = require('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'; + * const { spawn } = require('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 v18.18.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 + * const cp = require('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. + * + * 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 + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').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 `net` module, `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, currently 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 + * const { fork } = require('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 = require('net').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 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 + * const { spawn } = require('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 + * const { spawn } = require('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 + * const { spawn } = require('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 + * const { spawn } = require('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 + * const { spawn } = require('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 currently 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 + * const { spawn } = require('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; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * 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 + * const { exec } = require('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 + * const { exec } = require('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 + * const util = require('util'); + * const exec = util.promisify(require('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 + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(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: { + encoding: "buffer" | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptions, + 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: (ObjectEncodingOptions & 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: { + encoding: "buffer" | null; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | 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; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + 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 + * const { execFile } = require('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 + * const util = require('util'); + * const execFile = util.promisify(require('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 + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(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. + */ + function execFile(file: string): ChildProcess; + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + function execFile(file: string, args?: readonly string[] | null): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + // 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 `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; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + 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: (ObjectEncodingOptions & 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: (ObjectEncodingOptions & 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: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & 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 { + * const { fork } = require('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, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, 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', '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; + 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/openai/node_modules/@types/node/cluster.d.ts b/node_modules/openai/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..e33eab7 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,432 @@ +/** + * 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` 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 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * 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/v18.0.0/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 { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + serialization?: SerializationType | undefined; + cwd?: string | undefined; + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 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()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * 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()`. + * + * 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. `options` supports the following properties: + */ + 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()`. + * @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 + * 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 net = require('net'); + * 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(): void; + /** + * 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 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * 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; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + 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/openai/node_modules/@types/node/console.d.ts b/node_modules/openai/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..c627daf --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/console.d.ts @@ -0,0 +1,412 @@ +/** + * 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` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**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` 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/v18.0.0/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()`. + * + * 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 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 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()` 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()`). + * + * ```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()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` 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()`). + * + * ```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()` 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 + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 + */ + 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 + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` 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. + * Starts a JavaScript CPU profile with an optional label. + */ + 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. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + 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` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**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` 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/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | "auto" | undefined; + 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/openai/node_modules/@types/node/constants.d.ts b/node_modules/openai/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..c3ac2b8 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/constants.d.ts @@ -0,0 +1,19 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module "constants" { + import { constants as osConstants, SignalConstants } from "node:os"; + import { constants as cryptoConstants } from "node:crypto"; + import { constants as fsConstants } from "node:fs"; + + const exp: + & typeof osConstants.errno + & typeof osConstants.priority + & SignalConstants + & typeof cryptoConstants + & typeof fsConstants; + export = exp; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/node_modules/openai/node_modules/@types/node/crypto.d.ts b/node_modules/openai/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..a2cc7b1 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4457 @@ +/** + * The `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('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/v18.0.0/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](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). + * + * `` 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 `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/man1.1.0/apps/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('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('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 'buffer'; + * const { Certificate } = await import('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-v10.x/docs/api/crypto.html#crypto_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; + /** 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 "speshul" version 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; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: 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 ALPN_ENABLED: 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 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('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`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('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" | "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('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 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('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('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('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?: stream.TransformOptions): 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('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 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('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('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + 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 { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * 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; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | 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 v16.15.0 + */ + 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; + /** + * 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" | "chacha20-poly1305"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + 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; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * 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 `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * 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: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` 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 createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('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 `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('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('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 Cipher 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 `Cipher` 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 `Cipher` 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 Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * 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`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` 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: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` 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 createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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', () => { + * 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 `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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 Decipher 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 `Decipher` 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 Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + 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('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @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('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @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 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('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('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): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + 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 'assert'; + * + * const { + * createDiffieHellman + * } = await import('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, 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. + * @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`. + * @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 `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: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). 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('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. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * 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('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * 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`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * 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('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * 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('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('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('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('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('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 'buffer'; + * const { randomFillSync } = await import('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 'buffer'; + * const { randomFillSync } = await import('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 'buffer'; + * const { randomFill } = await import('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 'buffer'; + * const { randomFill } = await import('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('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('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): 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): 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): 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): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('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('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('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 'assert'; + * + * const { + * createECDH + * } = await import('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('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 is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking 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. + * + * 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; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + 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('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('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, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + 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'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): 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 'buffer'; + * const { + * hkdf + * } = await import('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. It must be at least one byte in 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 'buffer'; + * const { + * hkdfSync + * } = await import('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. It must be at least one byte in 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('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. + * @since 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 or `undefined` + * if not available. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * The information access content of this certificate or `undefined` if not + * available. + * @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 until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + 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 issued by the given `otherCert`. + * @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` + * + * The flags below are deprecated in OpenSSL-1.1.0. + * + * - `crypto.constants.ENGINE_METHOD_ECDH` + * - `crypto.constants.ENGINE_METHOD_ECDSA` + * - `crypto.constants.ENGINE_METHOD_STORE` + * @since v0.11.11 + * @param [flags=crypto.constants.ENGINE_METHOD_ALL] + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for `crypto.webcrypto.getRandomValues()`. + * This implementation is not compliant with the Web Crypto spec, + * to write web-compatible code use `crypto.webcrypto.getRandomValues()` instead. + * @since v17.4.0 + * @returns 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; + } + /** + * Calling `require('node:crypto').webcrypto` returns 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: AlgorithmIdentifier | 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: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: + | AlgorithmIdentifier + | AesDerivedKeyParams + | HmacImportParams + | HkdfParams + | Pbkdf2Params, + 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; + } + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/node_modules/openai/node_modules/@types/node/dgram.d.ts b/node_modules/openai/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..25a4f65 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,596 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`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/v18.0.0/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo } 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; + /** + * @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; + } + /** + * 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 'cluster'; + * import dgram from '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 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`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 + * @return the number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0 + * @return the 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 'dgram'; + * import { Buffer } from '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 'dgram'; + * import { Buffer } from '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 'dgram'; + * import { Buffer } from '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 | Uint8Array | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + 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 addition 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 v18.18.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/node_modules/openai/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/openai/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..e5f1202 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,546 @@ +/** + * The `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 '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. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 '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 interact with 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 '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 '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 diagnostics_channel.subscribe(name, onMessage). + * + * ```js + * import diagnostics_channel from '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 + * @returns `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 use 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 '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 '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 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @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 '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 + * @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 v18.19.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 v18.19.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: any): void; + /** + * 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(): void; + } + 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 v18.19.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 v18.19.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 v18.19.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. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v18.19.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) => any, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): void; + /** + * 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. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v18.19.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 + ): void; + /** + * 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. + * + * ```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 v18.19.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 any>( + fn: Fn, + position: number | undefined, + context: ContextType | undefined, + thisArg: any, + ...args: Parameters + ): void; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/node_modules/openai/node_modules/@types/node/dns.d.ts b/node_modules/openai/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..104dd76 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/dns.d.ts @@ -0,0 +1,809 @@ +/** + * The `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 + * const dns = require('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 `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 + * const dns = require('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` for more information. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + 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 { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + /** + * @default true + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + 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 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` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('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()` 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` object, where `err.code` is the error code. + * + * ```js + * const dns = require('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()` 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 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 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 + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | 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` 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", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "AAAA", + 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: "CNAME", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => 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: "NS", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => 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: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | 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: "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: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise; + } + /** + * 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 a 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 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` object, where `err.code` is + * one of the `DNS 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 `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v18.17.0 + */ + export 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 + * 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` 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 `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and {@link setDefaultResultOrder} have higher + * priority than `--dns-result-order`. When using `worker threads`,{@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'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @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()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('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 `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; + 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/openai/node_modules/@types/node/dns/promises.d.ts b/node_modules/openai/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..282ec72 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,381 @@ +/** + * 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 `require('dns').promises` or `require('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, + } 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` 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()` 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` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('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` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('dns').promises; + * 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` object, where `err.code`is one of the `DNS 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"): Promise; + function resolve(hostname: string, rrtype: "AAAA"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "CNAME"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "NS"): Promise; + function resolve(hostname: string, rrtype: "PTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve( + hostname: string, + rrtype: string, + ): Promise; + /** + * 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 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` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v18.17.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 `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and `dnsPromises.setDefaultResultOrder()` have + * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.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'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/node_modules/openai/node_modules/@types/node/dom-events.d.ts b/node_modules/openai/node_modules/@types/node/dom-events.d.ts new file mode 100644 index 0000000..147a7b6 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/dom-events.d.ts @@ -0,0 +1,122 @@ +export {}; // Don't export anything! + +//// DOM-like Events +// NB: The Event / EventTarget / EventListener implementations below were copied +// from lib.dom.d.ts, then edited to reflect Node's documentation at +// https://nodejs.org/api/events.html#class-eventtarget. +// Please read that link to understand important implementation differences. + +// This conditional type will be the existing global Event in a browser, or +// the copy below in a Node environment. +type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {} + : { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?]; + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + }; + +// See comment above explaining conditional type +type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {} + : { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + }; + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +import {} from "events"; // Make this an ambient declaration +declare global { + /** An event which takes place in the DOM. */ + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T + : { + prototype: __Event; + new(type: string, eventInitDict?: EventInit): __Event; + }; + + /** + * EventTarget is a DOM interface implemented by objects that can + * receive events and may have listeners for them. + */ + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T + : { + prototype: __EventTarget; + new(): __EventTarget; + }; +} diff --git a/node_modules/openai/node_modules/@types/node/domain.d.ts b/node_modules/openai/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..ca8728f --- /dev/null +++ b/node_modules/openai/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/v18.0.0/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 lowlevel 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 + * const domain = require('domain'); + * const fs = require('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/openai/node_modules/@types/node/events.d.ts b/node_modules/openai/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..9ffd523 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/events.d.ts @@ -0,0 +1,803 @@ +/** + * 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 + * const EventEmitter = require('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/v18.0.0/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; + } + // Any EventTarget with a Node-style `once` function + interface _NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + // Any EventTarget with a DOM-style `addEventListener` + interface _DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + }, + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('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 { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): 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 + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * 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.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * 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 + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('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: _NodeEventTarget, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (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')) { + * // 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 + * const { on, EventEmitter } = require('events'); + * 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()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string, + options?: StaticEventEmitterOptions, + ): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('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 + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: _DOMEventTarget | 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 v18.17.0 + */ + static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * const { + * setMaxListeners, + * EventEmitter + * } = require('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 eventsTargets 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<_DOMEventTarget | NodeJS.EventEmitter>): 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 v18.18.0 + * @experimental + * @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. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + 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 + * `EventEmitterAsyncResource` will run within its async context. + * + * The EventEmitterAsyncResource class has the same methods and takes the + * same options as EventEmitter and AsyncResource themselves. + * @throws if `options.name` is not provided when instantiated directly. + * @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 underlying AsyncResource */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + } + global { + namespace NodeJS { + interface EventEmitter { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: string, ...args: any[]): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): 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 + * 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: string | symbol, listener: (...args: any[]) => void): 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 + * 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: string | symbol, listener: (...args: any[]) => void): 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 + * 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 + * 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: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): 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(event?: string | symbol): 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 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: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * 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: string | symbol): Function[]; + /** + * 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 + * const EventEmitter = require('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: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to 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: string | symbol, listener?: Function): 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: string | symbol, listener: (...args: any[]) => void): 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: string | symbol, listener: (...args: any[]) => void): 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 + * const EventEmitter = require('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; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/node_modules/openai/node_modules/@types/node/fs.d.ts b/node_modules/openai/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..b36d51c --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4231 @@ +/** + * The `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 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from '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/v18.0.0/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} and {@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`. + * + * ```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 {} + + 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 {@link statfsSync} are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`. + * @since 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: string; + /** + * The base path that this `fs.Dirent` object refers to. + * @since v18.17.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from '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](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved 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 resolved 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; + } + /** + * 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: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => 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: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", 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: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", 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: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", 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: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * 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: "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: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => 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: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => 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: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => 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: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => 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: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): 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 '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 '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 | null, 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 | null): 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 | null): 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 '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 | null, 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 | null): 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 | null): 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 '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`. + * + * 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 '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). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * In case of an error, the err.code will be one of Common System Errors. + * @param path A path to an existing file or directory on the file system to be queried. + * @param callback + */ + 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). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * In case of an error, the err.code will be one of Common System Errors. + * @param path A path to an existing file or directory on the file system to be queried. + * @param callback + */ + 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 set, 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. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from '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 + */ + 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 + */ + 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 '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. + * + * 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. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /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 '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 'fs'; + * + * mkdtemp(path.join(os.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 + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from '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 '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; + 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; + } + /** + * 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[]; + /** + * 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; + /** + * 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 + */ + 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 `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 `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 + * @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, + 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: number | 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 + */ + 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 '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 '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 '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 '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: Buffer) => 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 | Buffer) => 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: Buffer) => 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 '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, + ): Buffer; + /** + * 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 | Buffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | 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 'fs'; + * import { Buffer } from '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 '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 'fs'; + * import { Buffer } from '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 '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 '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 '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 '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 '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 '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 '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 '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. + * @param listener The callback listener will be called each time the file is accessed. + */ + 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 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: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options?: WatchOptions | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options: WatchOptions | string, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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; + 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; + } + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `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 '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 '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 '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 '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 + */ + 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, + 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 + * @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 + */ + 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, + 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 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + export interface OpenDirOptions { + 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; + } + /** + * 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; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/node_modules/openai/node_modules/@types/node/fs/promises.d.ts b/node_modules/openai/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..7e55f89 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1205 @@ +/** + * 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, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + 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?: number | null; + } + interface CreateReadStreamOptions { + 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; + } + interface ReadableWebStreamOptions { + /** + * Whether to open a normal or a `'bytes'` stream. + * @since v18.17.0 + */ + type?: "bytes" | 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 & FlagAndOpenMode) | 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 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `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 '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 '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 Fufills 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?: number | null, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a `ReadableStream` that may be used to read the files data. + * + * 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 + * @experimental + */ + 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; + flag?: OpenMode | undefined; + } | 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. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | 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. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. For example: + * + * ```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 + * @param options See `filehandle.createReadStream()` for the options. + */ + 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 '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 resolves 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 + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is resolved 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 resolved (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 & FlagAndOpenMode & Abortable) | BufferEncoding | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is resolved 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 resolved (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=0] 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 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( + 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 resolved 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 resolved (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 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 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 '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; + /** + * An alias for {@link FileHandle.close()}. + * @since v18.18.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 resolved 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 } from 'fs/promises'; + * import { constants } from 'fs'; + * + * 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 { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('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.log('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. + * @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 resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from '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; + /** + * 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 + * resolved 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'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @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 v18.15.0 + * @return Fulfills with an {fs.StatFs} for the file system. + */ + 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 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.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 + * (`require('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem 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 + * [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 'fs/promises'; + * import { Buffer } from '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; + } & 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) | 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. + * + * 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 '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 '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; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('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: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: WatchOptions | string, + ): AsyncIterable> | AsyncIterable>; + /** + * 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; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/node_modules/openai/node_modules/@types/node/globals.d.ts b/node_modules/openai/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..f6c95e9 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/globals.d.ts @@ -0,0 +1,377 @@ +export {}; // Make this a module + +// #region Fetch and friends +// Conditional type aliases, used at the end of this file. +// Will either be empty if lib-dom is included, or the undici version otherwise. +type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; +type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; +type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; +type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; +type _RequestInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").RequestInit; +type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").ResponseInit; +// #endregion Fetch and friends + +declare global { + // Declare "static" methods in Error + interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; + } + + /*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + + // For backwards compability + interface NodeRequire extends NodeJS.Require {} + interface RequireResolve extends NodeJS.RequireResolve {} + interface NodeModule extends NodeJS.Module {} + + var process: NodeJS.Process; + var console: Console; + + var __filename: string; + var __dirname: string; + + var require: NodeRequire; + var module: NodeModule; + + // Same as module.exports + var exports: any; + + /** + * Only available if `--expose-gc` is passed to the process. + */ + var gc: undefined | (() => void); + + // #region borrowed + // from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib + /** A controller object that allows you to abort one or more DOM requests as and when desired. */ + interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(reason?: any): void; + } + + /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ + interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; + readonly reason: any; + onabort: null | ((this: AbortSignal, event: Event) => any); + throwIfAborted(): void; + } + + var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T + : { + prototype: AbortController; + new(): AbortController; + }; + + var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; + // #endregion borrowed + + // #region Disposable + interface SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: unique symbol; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: unique symbol; + } + + interface Disposable { + [Symbol.dispose](): void; + } + + interface AsyncDisposable { + [Symbol.asyncDispose](): PromiseLike; + } + // #endregion Disposable + + // #region ArrayLike.at() + interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; + } + interface String extends RelativeIndexable {} + interface Array extends RelativeIndexable {} + interface ReadonlyArray extends RelativeIndexable {} + interface Int8Array extends RelativeIndexable {} + interface Uint8Array extends RelativeIndexable {} + interface Uint8ClampedArray extends RelativeIndexable {} + interface Int16Array extends RelativeIndexable {} + interface Uint16Array extends RelativeIndexable {} + interface Int32Array extends RelativeIndexable {} + interface Uint32Array extends RelativeIndexable {} + interface Float32Array extends RelativeIndexable {} + interface Float64Array extends RelativeIndexable {} + interface BigInt64Array extends RelativeIndexable {} + interface BigUint64Array extends RelativeIndexable {} + // #endregion ArrayLike.at() end + + /** + * @since v17.0.0 + * + * Creates a deep clone of an object. + */ + function structuredClone( + value: T, + transfer?: { transfer: ReadonlyArray }, + ): T; + + /*----------------------------------------------* + * * + * GLOBAL INTERFACES * + * * + *-----------------------------------------------*/ + namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | undefined; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): 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; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + ".js": (m: Module, filename: string) => any; + ".json": (m: Module, filename: string) => any; + ".node": (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since v11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + } + + interface RequestInit extends _RequestInit {} + + function fetch( + input: string | URL | Request, + init?: RequestInit, + ): Promise; + + interface Request extends _Request {} + var Request: typeof globalThis extends { + onmessage: any; + Request: infer T; + } ? T + : typeof import("undici-types").Request; + + interface ResponseInit extends _ResponseInit {} + + interface Response extends _Response {} + var Response: typeof globalThis extends { + onmessage: any; + Response: infer T; + } ? T + : typeof import("undici-types").Response; + + interface FormData extends _FormData {} + var FormData: typeof globalThis extends { + onmessage: any; + FormData: infer T; + } ? T + : typeof import("undici-types").FormData; + + interface Headers extends _Headers {} + var Headers: typeof globalThis extends { + onmessage: any; + Headers: infer T; + } ? T + : typeof import("undici-types").Headers; +} diff --git a/node_modules/openai/node_modules/@types/node/globals.global.d.ts b/node_modules/openai/node_modules/@types/node/globals.global.d.ts new file mode 100644 index 0000000..ef1198c --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/node_modules/openai/node_modules/@types/node/http.d.ts b/node_modules/openai/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..73fd70a --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/http.d.ts @@ -0,0 +1,1801 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * 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: + * + * ```js + * { '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/v18.0.0/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { EventEmitter } from "node:events"; + import { LookupOptions } from "node:dns"; + 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-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-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; + 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; + prgama?: 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; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: + | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | 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; + 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; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v18.17.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 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; + } + 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?: () => void): this; + setTimeout(callback: () => 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 of outgoing message from + * the perspective of the participants of 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; + /** + * Aliases 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 for the header object. + * 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; + /** + * Append a single header value for the header object. + * + * If the value is an array, this is equivalent of calling this method multiple times. + * + * If there were no previous value for the header, this is equivalent of 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 HTTP header with the given name. If such a name doesn't + * exist in message, it 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 of names of headers of the outgoing outgoingMessage. 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 are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields 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; + /** + * Compulsorily 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 request. + * @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 given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not 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 `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends an HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): 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. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @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 + * const http = require('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 + * const http = require('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.getHeaders()); + * ``` + * + * 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. + * * `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(request.url, `http://${request.getHeaders().host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.getHeaders().host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @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 + * }); + * ``` + * @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; + } + 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. + * @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 + * const http = require('http'); + * + * 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 + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'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'` + * * `'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'` + * * `'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 + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'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 itself. + * @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 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` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + 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'`. + * @param name Header name + * @since v14.3.0 + */ + 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'`. + * @param name Header name + * @param value Header value + * @since v14.3.0 + */ + function validateHeaderValue(name: string, value: string): void; + + /** + * Set the maximum number of idle HTTP parsers. Default: 1000. + * @param count + * @since v18.8.0, v16.18.0 + */ + function setMaxIdleHTTPParsers(count: number): void; + + 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; +} +declare module "node:http" { + export * from "http"; +} diff --git a/node_modules/openai/node_modules/@types/node/http2.d.ts b/node_modules/openai/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..03e92ab --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2386 @@ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + 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; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('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 + * const http2 = require('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 + * const http2 = require('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?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * 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 + * const http2 = require('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 + * const http2 = require('http2'); + * const fs = require('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 + * const http2 = require('http2'); + * const fs = require('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 + * const http2 = require('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.log(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 + * const http2 = require('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 + * const http2 = require('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; + weight?: 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 + * const http2 = require('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 + * const http2 = require('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, 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 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 + * const http2 = require('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 + * const http2 = require('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 + * const http2 = require('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 { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | 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; + selectPadding?(frameLen: number, maxFrameLen: number): number; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions 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 extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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 extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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; + /** + * 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: Http2ServerRequest; + /** + * 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 + * const http2 = require('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 `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, + * 'x-trace-id': 'id for diagnostics' + * }); + * ``` + * + * @since v18.11.0 + * @param hints An object containing the values of headers + */ + 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_ORIGIN: 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 + * const http2 = require('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 + * const http2 = require('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(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer( + options: ServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('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(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('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; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/node_modules/openai/node_modules/@types/node/https.d.ts b/node_modules/openai/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..2f06928 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/https.d.ts @@ -0,0 +1,544 @@ +/** + * 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/v18.0.0/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?: typeof tls.checkServerIdentity | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + 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 & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: 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 & { req: 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/ + * const https = require('https'); + * const fs = require('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 + * const https = require('https'); + * const fs = require('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 + * const https = require('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 + * const tls = require('tls'); + * const https = require('https'); + * const crypto = require('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-sha25 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 + * const https = require('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/openai/node_modules/@types/node/index.d.ts b/node_modules/openai/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..a596cad --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/index.d.ts @@ -0,0 +1,88 @@ +/** + * 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 NodeJS and TypeScript 4.9+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/node_modules/openai/node_modules/@types/node/inspector.d.ts b/node_modules/openai/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..9022f38 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2739 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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?: {} | 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: {}; + } + } + 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?: {} | 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?: {} | 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?: {} | 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[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + 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 TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + 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: Array<{}>; + } + } + 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 NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: 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. + * @since v8.0.0 + */ + connect(): 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. + * @since v8.0.0 + */ + 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. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => 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; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => 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; + /** + * 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; + // Events + 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; + /** + * 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; + 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: 'NodeRuntime.waitingForDisconnect'): 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; + /** + * 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; + 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; + /** + * 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; + 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; + /** + * 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; + 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; + /** + * 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; + } + /** + * 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` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * 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; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + import inspector = require('inspector'); + export = inspector; +} diff --git a/node_modules/openai/node_modules/@types/node/module.d.ts b/node_modules/openai/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..3a08656 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/module.d.ts @@ -0,0 +1,298 @@ +/** + * @since v0.3.7 + */ +declare module "module" { + import { URL } from "node:url"; + import { MessagePort } from "node:worker_threads"; + namespace Module { + /** + * 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 + * const fs = require('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('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; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + */ + function findSourceMap(path: string, error?: Error): SourceMap; + 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; + /** + * 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 { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(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 | {}; + } + /** @deprecated Use `ImportAttributes` instead */ + interface ImportAssertions extends ImportAttributes {} + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + interface GlobalPreloadContext { + port: MessagePort; + } + /** + * @deprecated This hook will be removed in a future version. + * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. + * + * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. + * This hook allows the return of a string that is run as a sloppy-mode script on startup. + * + * @param context Information to assist the preload code + * @return Code to run before application startup + */ + type GlobalPreloadHook = (context: GlobalPreloadContext) => string; + /** + * 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 `register`. + * + * This hook can receive data from a `register` invocation, including ports and other transferrable 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[]; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * 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) + */ + format?: ModuleFormat | null | undefined; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions?: ImportAttributes | 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 resolving file URL for a given module specifier and parent URL, and optionally its 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. + * + * @param specifier The specified URL path of the module to be resolved + * @param context + * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: ResolveHookContext, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain + */ + format: ModuleFormat; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: ModuleFormat; + /** + * 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; + } + /** + * 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 assertion. + * + * @param url The URL/path of the module to be loaded + * @param context Metadata about the module + * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + } + interface RegisterOptions { + parentURL: string | URL; + data?: Data | undefined; + transferList?: any[] | undefined; + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; + static Module: typeof Module; + static register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + static register(specifier: string | URL, options?: RegisterOptions): void; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/node_modules/openai/node_modules/@types/node/net.d.ts b/node_modules/openai/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..782b891 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/net.d.ts @@ -0,0 +1,913 @@ +/** + * > Stability: 2 - Stable + * + * The `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 + * const net = require('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | 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, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + 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; + } + interface IpcSocketConnectOpts extends ConnectOpts { + 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) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => 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 + * @return The socket itself. + */ + 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 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 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 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * @see {https://nodejs.org/api/net.html#socketreadystate} + * @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'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @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. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. ready + * 9. 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: "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: "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: "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: "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: "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: "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 { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: 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; + } + 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.log('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): void; + /** + * 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 + */ + 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 v18.18.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; + } + 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 + * const net = require('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`: + * + * ```console + * $ 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: + * + * ```console + * $ 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; + /** + * 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); + /** + * @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; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/node_modules/openai/node_modules/@types/node/os.d.ts b/node_modules/openai/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..00d0373 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/os.d.ts @@ -0,0 +1,473 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + 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 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. + * @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 18.4.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` 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 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; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * 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, aarch64, mips, mips64, ppc64, ppc64le, s390, 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 + */ + 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/openai/node_modules/@types/node/package.json b/node_modules/openai/node_modules/@types/node/package.json new file mode 100644 index 0000000..67169e6 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/package.json @@ -0,0 +1,235 @@ +{ + "name": "@types/node", + "version": "18.19.9", + "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": "Alvis HT Tang", + "githubUsername": "alvis", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "githubUsername": "smac89", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "githubUsername": "DeividasBakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "githubUsername": "eyqs", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "githubUsername": "Hannes-Magnusson-CK", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "githubUsername": "hoo29", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "githubUsername": "kjin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "githubUsername": "ajafff", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "githubUsername": "islishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "githubUsername": "mwiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nicolas Even", + "githubUsername": "n-e", + "url": "https://github.com/n-e" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "githubUsername": "parambirs", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Simon Schick", + "githubUsername": "SimonSchick", + "url": "https://github.com/SimonSchick" + }, + { + "name": "Thomas den Hollander", + "githubUsername": "ThomasdenH", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "githubUsername": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "githubUsername": "samuela", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "githubUsername": "kuehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "githubUsername": "bhongy", + "url": "https://github.com/bhongy" + }, + { + "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": "Yongsheng Zhang", + "githubUsername": "ZYSzys", + "url": "https://github.com/ZYSzys" + }, + { + "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" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=4.8": { + "*": [ + "ts4.8/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~5.26.4" + }, + "typesPublisherContentHash": "0e51d539034444cb5194149387246b7a07c3c731efa6731aab0864477b0b9f00", + "typeScriptVersion": "4.6", + "nonNpm": true +} \ No newline at end of file diff --git a/node_modules/openai/node_modules/@types/node/path.d.ts b/node_modules/openai/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..1465c38 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/path.d.ts @@ -0,0 +1,191 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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; + /** + * 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/openai/node_modules/@types/node/perf_hooks.d.ts b/node_modules/openai/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..9ad41b9 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,626 @@ +/** + * 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/) + * + * ```js + * const { PerformanceObserver, performance } = require('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/v18.0.0/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns"; + 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; + } + /** + * @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; + } + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + /** + * _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 { + /** + * 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 V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = ( + util1?: EventLoopUtilization, + util2?: 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. + * @param name + */ + 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. + * @param name + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * 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. + * @param name + * @return The PerformanceMark entry that was created + */ + mark(name?: string, options?: MarkOptions): PerformanceMark; + /** + * 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; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * 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. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * 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; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * 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 + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * 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 + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * 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; + 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 + * const { + * performance, + * PerformanceObserver + * } = require('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; + } + 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 { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * 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 minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * 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; + } + 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; + } + 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. + * + * ## Examples + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from other to this histogram. + * @since v17.4.0, v16.14.0 + * @param other Recordable Histogram to combine with + */ + 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 + * const { monitorEventLoopDelay } = require('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 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: 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 } from "perf_hooks"; + global { + /** + * `performance` is a global reference for `require('perf_hooks').performance` + * https://nodejs.org/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/openai/node_modules/@types/node/process.d.ts b/node_modules/openai/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..c5d6f87 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/process.d.ts @@ -0,0 +1,1548 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + 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 { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + 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 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" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "s390" + | "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 { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * 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. + * + * @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 error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, 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 '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; + }; + openStdin(): Socket; + /** + * 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 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ 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. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * 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 '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 '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 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * 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 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from '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, the `options` argument is ignored. + * @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: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from '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 '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 '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 '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. + * @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 '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 '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 '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. + */ + exit(code?: number): 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`. + * @since v0.11.8 + */ + exitCode?: number | 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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; + /** + * This function enables or disables the Source Map v3 support for stack traces. + * It provides same features as launching Node.js process with commandline options --enable-source-maps. + * @since v16.6.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v18.19.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from '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 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `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_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @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 '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; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from '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 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * 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'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from '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 '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, `undefined` is returned. + */ + constrainedMemory(): number | undefined; + /** + * 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 '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 '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 '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 '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; + /** + * 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: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/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; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `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?: { + swallowErrors?: 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 '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`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from '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 `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; + /* 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/openai/node_modules/@types/node/punycode.d.ts b/node_modules/openai/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..cfe559b --- /dev/null +++ b/node_modules/openai/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 + * const punycode = require('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/v18.0.0/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/openai/node_modules/@types/node/querystring.d.ts b/node_modules/openai/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..1837171 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,141 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('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/v18.0.0/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | readonly string[] + | readonly number[] + | readonly boolean[] + | 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: + * + * ```js + * { + * 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/openai/node_modules/@types/node/readline.d.ts b/node_modules/openai/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..60ccb8e --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/readline.d.ts @@ -0,0 +1,666 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) 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 `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/v18.0.0/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` 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 v0.1.104 + */ + export class Interface extends EventEmitter { + 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-v10.x/docs/api/readline.html#readline_class_interface + */ + 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-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.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 `readline.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 `readline.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 `readline.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. + * + * 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); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @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 `readline.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 `readline.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 `readline.Interface` instance. + * @since v0.1.98 + */ + close(): 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 `readline.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](): AsyncIterableIterator; + } + 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 { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + 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; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: 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; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('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 `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * 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 + * const readline = require('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 + * const fs = require('fs'); + * const readline = require('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 + * const fs = require('fs'); + * const readline = require('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 + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('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` 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` 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` `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` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('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 + * const fs = require('fs'); + * const readline = require('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 + * const fs = require('fs'); + * const readline = require('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 + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('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 + * @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/openai/node_modules/@types/node/readline/promises.d.ts b/node_modules/openai/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..ba603ef --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,143 @@ +/** + * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. + * + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) + * @since v17.0.0 + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + + 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 readlinePromises.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. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + + 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. + */ + 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. + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + */ + 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. + */ + 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. + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. + */ + rollback(): this; + } + + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('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). + * + * ## Use of the `completer` function + * + * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: + * + * - An Array with matching entries for the completion. + * - The substring that was used for the matching. + * + * For instance: `[[substr1, substr2, ...], originalsubstring]`. + * + * ```js + * function completer(line) { + * const completions = '.help .error .exit .quit .q'.split(' '); + * const hits = completions.filter((c) => c.startsWith(line)); + * // Show all completions if none found + * return [hits.length ? hits : completions, line]; + * } + * ``` + * + * The `completer` function can also returns a `Promise`, or be asynchronous: + * + * ```js + * async function completer(linePartial) { + * await someAsyncWork(); + * return [['123'], linePartial]; + * } + * ``` + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/node_modules/openai/node_modules/@types/node/repl.d.ts b/node_modules/openai/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..7ed370b --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `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 + * const repl = require('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + 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-v10.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-v11.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; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('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-v10.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-v10.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-v10.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-v10.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-v10.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-v10.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 + * const repl = require('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, an ellipsis 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(path: string, 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 + * const repl = require('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-v10.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/openai/node_modules/@types/node/stream.d.ts b/node_modules/openai/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..f7d2afb --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1731 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `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` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 streamConsumers from "node:stream/consumers"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + 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: Readable, 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. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.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 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'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` 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 + * const fs = require('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). + * const { StringDecoder } = require('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`, `Uint8Array` 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 `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 + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('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 }): AsyncIterableIterator; + /** + * 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; + /** + * 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; + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v18.18.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: Writable, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Writable, 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 + * @experimental + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + 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; + /** + * 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` or `Uint8Array`. 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!'. + * const fs = require('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` or `Uint8Array`. 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; + /** + * 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; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void; + } + /** + * 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 Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * 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 `false`. + * + * 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; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + /** + * 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; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, 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 {} + /** + * 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. + * + * ```js + * const fs = require('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; + * } + * } + * })(); + * ``` + * @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 `16384` (16 KiB), or `16` for `objectMode`. + * @since v18.17.0 + * @param objectMode + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v18.17.0 + * @param objectMode + * @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 function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * 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: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `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. + * @return 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 + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('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, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, { signal }) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function* ({ signal }) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `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 + * const fs = require('fs'); + * const http = require('http'); + * const { pipeline } = require('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 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + + /** + * Returns whether the stream is readable. + * @since v17.4.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/node_modules/openai/node_modules/@types/node/stream/consumers.d.ts b/node_modules/openai/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..5ad9cba --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { Readable } from "node:stream"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/node_modules/openai/node_modules/@types/node/stream/promises.d.ts b/node_modules/openai/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,83 @@ +declare module "stream/promises" { + import { + FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + 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/openai/node_modules/@types/node/stream/web.d.ts b/node_modules/openai/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..aac0523 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,352 @@ +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; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; + 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 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; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + 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; + 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: string): CompressionStream; + }; + interface DecompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: string): DecompressionStream; + }; +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/openai/node_modules/@types/node/string_decoder.d.ts b/node_modules/openai/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..e9a8cc2 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `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 + * const { StringDecoder } = require('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * 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 + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): 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 A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/node_modules/openai/node_modules/@types/node/test.d.ts b/node_modules/openai/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..5557822 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/test.d.ts @@ -0,0 +1,1113 @@ +/** + * The `node:test` module provides a standalone testing module. + * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/test.js) + */ +declare module "node:test" { + import { AsyncResource } from "node:async_hooks"; + /** + * Programmatically start the test runner. + * @since v18.9.0 + * @param options Configuration options for running tests. + * @returns A {@link TestsStream} that emits events about the test execution. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `test()` function is the value imported from the test module. Each invocation of this + * function results in reporting the test to the {@link TestsStream}. + * + * The {@link 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 {@link Promise} that resolves once the test completes. 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); + * }); + * }); + * }); + * ``` + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: 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. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + 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 { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo }; + } + /** + * @since v18.6.0 + * @param name The name of the suite, which is displayed when reporting suite results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite + * @param fn The function under suite. Default: A no-op function. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function describe(name?: string, fn?: SuiteFn): Promise; + function describe(options?: TestOptions, fn?: SuiteFn): Promise; + function describe(fn?: SuiteFn): Promise; + namespace describe { + /** + * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + */ + 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`, same as `describe([name], { todo: true }[, fn])`. + */ + 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`, same as `describe([name], { only: true }[, fn])`. + * @since v18.15.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; + } + + /** + * @since v18.6.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: 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. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + */ + function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function it(name?: string, fn?: TestFn): Promise; + function it(options?: TestOptions, fn?: TestFn): Promise; + function it(fn?: TestFn): Promise; + namespace it { + /** + * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + */ + 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`, same as `it([name], { todo: true }[, fn])`. + */ + 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`, same as `it([name], { only: true }[, fn])`. + * @since v18.15.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; + } + /** + * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. + * @since v18.17.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`, same as `test([name], { todo: true }[, fn])`. + * @since v18.17.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`, same as `test([name], { only: true }[, fn])`. + * @since v18.17.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 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. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * The type of a function under Suite. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `` 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 files would run in parallel. + * If truthy, it would run (number of cpu cores - 1) files in parallel. + * If falsy, it would only run one file at a time. + * If unspecified, subtests inherit this value from their parent. + * @default true + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. + * If unspecified, the test runner execution model will be used. + */ + files?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + * @default undefined + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the test will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * That can be used to only run 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. + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; + /** + * If truthy, the test context will only run tests that have the `only` option set + * @since v18.19.0 + */ + only?: boolean; + /** + * A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run. + */ + setup?: (root: Test) => void | Promise; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @since v18.19.0 + * @default undefined + */ + shard?: TestShard | undefined; + } + class Test extends AsyncResource { + concurrency: number; + nesting: number; + only: boolean; + reporter: TestsStream; + runOnlySubtests: boolean; + testNumber: number; + timeout: number | null; + } + + /** + * A successful call of the `run()` method will return a new `TestsStream` object, + * streaming a series of events representing the execution of the tests. + * `TestsStream` will emit events in the order of the tests' definitions. + * @since v18.9.0 + */ + interface TestsStream extends NodeJS.ReadableStream { + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:fail", listener: (data: TestFail) => void): this; + addListener(event: "test:pass", listener: (data: TestPass) => void): this; + addListener(event: "test:plan", listener: (data: TestPlan) => void): this; + addListener(event: "test:start", listener: (data: TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:fail", data: TestFail): boolean; + emit(event: "test:pass", data: TestPass): boolean; + emit(event: "test:plan", data: TestPlan): boolean; + emit(event: "test:start", data: TestStart): boolean; + emit(event: "test:stderr", data: TestStderr): boolean; + emit(event: "test:stdout", data: TestStdout): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:fail", listener: (data: TestFail) => void): this; + on(event: "test:pass", listener: (data: TestPass) => void): this; + on(event: "test:plan", listener: (data: TestPlan) => void): this; + on(event: "test:start", listener: (data: TestStart) => void): this; + on(event: "test:stderr", listener: (data: TestStderr) => void): this; + on(event: "test:stdout", listener: (data: TestStdout) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:fail", listener: (data: TestFail) => void): this; + once(event: "test:pass", listener: (data: TestPass) => void): this; + once(event: "test:plan", listener: (data: TestPlan) => void): this; + once(event: "test:start", listener: (data: TestStart) => void): this; + once(event: "test:stderr", listener: (data: TestStderr) => void): this; + once(event: "test:stdout", listener: (data: TestStdout) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + + /** + * 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 + */ + interface TestContext { + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.17.0 + */ + before: typeof before; + + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach: typeof beforeEach; + + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach: typeof afterEach; + + /** + * 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. + * @param message Message to be reported. + * @since v18.0.0 + */ + diagnostic(message: string): void; + + /** + * The name of the test. + * @since v18.8.0 + */ + readonly name: string; + + /** + * 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. + * @param shouldRunOnlyTests Whether or not to run `only` tests. + * @since v18.0.0 + */ + runOnly(shouldRunOnlyTests: boolean): void; + + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.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. + * @param message Optional skip message. + * @since v18.0.0 + */ + 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. + * @param message Optional `TODO` message. + * @since v18.0.0 + */ + 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. + * Default: 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. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + + /** + * 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 + */ + class SuiteContext { + /** + * 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; + } + + /** + * This function is used to create a hook running before running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function before(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function after(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running before each subtest of the current suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + + /** + * The hook function. If the hook uses callbacks, the callback function is passed as the + * second argument. + */ + type HookFn = (s: SuiteContext, 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; + }; + + type NoOpFunction = (...args: any[]) => undefined; + + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + + interface MockTracker { + /** + * This function is used to create a mock function. + * @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. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. + * @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. + */ + 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 {@link MockTracker.method} with `options.getter` set to `true`. + */ + 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 {@link MockTracker.method} with `options.setter` set to `true`. + */ + 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 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. + */ + 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. + */ + restoreAll(): void; + 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; + } + + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the mock. + */ + readonly calls: Array>; + + /** + * 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. + */ + callCount(): number; + + /** + * This function is used to change the behavior of an existing mock. + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: Function): 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. + * @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: Function, onCall?: number): void; + + /** + * Resets the call history of the mock function. + */ + resetCalls(): void; + + /** + * Resets the implementation of the mock function to its original behavior. + * The mock can still be used after calling this function. + */ + restore(): void; + } + type Timer = "setInterval" | "clearInterval" | "setTimeout" | "clearTimeout"; + /** + * 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 `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v18.19.0 + * @experimental + */ + class 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. + * + * Example usage: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable(['setInterval']); + * ``` + * + * The above example enables mocking for the `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `setInterval`and `clearInterval` functions from `node:timers`,`node:timers/promises`, and`globalThis` will be mocked. + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout`functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * @since v18.19.0 + */ + enable(timers?: Timer[]): 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 v18.19.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(['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(['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); + * }); + * ``` + * @since v18.19.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. + * + * 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(['setTimeout']); + * 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]); + * }); + * ``` + * + * **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 v18.19.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + + export { after, afterEach, before, beforeEach, describe, it, mock, run, test, test as default }; +} + +interface TestLocationInfo { + /** + * 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 is not ran through a file. + */ + file?: string; + /** + * The line number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + line?: number; +} +interface DiagnosticData extends TestLocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestFail extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since 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 TestPass extends TestLocationInfo { + /** + * 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 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 TestLocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; +} +interface TestStart extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestStderr extends TestLocationInfo { + /** + * The message written to `stderr` + */ + message: string; +} +interface TestStdout extends TestLocationInfo { + /** + * The message written to `stdout` + */ + message: string; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} + +/** + * 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 'test/reporters'; + * ``` + * @since v18.17.0 + * @see [source](https://github.com/nodejs/node/blob/v18.17.0/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform } from "node:stream"; + + type TestEvent = + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:fail"; data: TestFail } + | { type: "test:pass"; data: TestPass } + | { type: "test:plan"; data: TestPlan } + | { type: "test:start"; data: TestStart } + | { type: "test:stderr"; data: TestStderr } + | { type: "test:stdout"; data: TestStdout } + | { type: "test:enqueue"; data: TestEnqueue } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:watch:drained" }; + type TestEventGenerator = AsyncGenerator; + + /** + * 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`. + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + */ + function tap(source: TestEventGenerator): AsyncGenerator; + /** + * The `spec` reporter outputs the test results in a human-readable format. + */ + class Spec extends Transform { + constructor(); + } + /** + * The `junit` reporter outputs test results in a jUnit XML format + */ + function junit(source: TestEventGenerator): AsyncGenerator; + export { dot, junit, Spec as spec, tap, TestEvent }; +} diff --git a/node_modules/openai/node_modules/@types/node/timers.d.ts b/node_modules/openai/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..0d1beed --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/timers.d.ts @@ -0,0 +1,126 @@ +/** + * 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 call `require('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/v18.0.0/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import { + setImmediate as setImmediatePromise, + setInterval as setIntervalPromise, + setTimeout as setTimeoutPromise, + } from "node:timers/promises"; + 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; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + interface Immediate extends RefCounted { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v18.18.0 + */ + [Symbol.dispose](): void; + } + interface Timeout extends Timer { + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * 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 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v18.18.0 + */ + [Symbol.dispose](): void; + } + } + /** + * 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`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. + * If `callback` is not a function, a [TypeError](https://nodejs.org/api/errors.html#class-typeerror) will be thrown. + * @since v0.0.1 + */ + function setTimeout( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + function setInterval( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/node_modules/openai/node_modules/@types/node/timers/promises.d.ts b/node_modules/openai/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..abb5b42 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,93 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from '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. + * + * ```js + * import { + * setInterval, + * } from '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 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + + interface Scheduler { + /** + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * An experimental API defined by the 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. + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: TimerOptions) => Promise; + /** + * An experimental API defined by the 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 v16.14.0 + * @experimental + */ + yield: () => Promise; + } + + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/node_modules/openai/node_modules/@types/node/tls.d.ts b/node_modules/openai/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..8c6ff90 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1203 @@ +/** + * The `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 + * const tls = require('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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, 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: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * 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.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). + */ + addContext(hostname: string, context: SecureContextOptions): 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; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + 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. + * @since v18.19.0 + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | 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. + */ + 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. + */ + 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. + */ + 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 `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('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. + * const tls = require('tls'); + * const fs = require('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; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * {@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 {@link createServer} and `server.addContext()`, but has no public methods. + * + * 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). + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * 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`. + * + * 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 tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.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. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.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. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the ciphers option of tls.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. + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/node_modules/openai/node_modules/@types/node/trace_events.d.ts b/node_modules/openai/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..7f0fe55 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,171 @@ +/** + * The `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` trace data. + * The `async_hooks` 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.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` 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 `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * 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 `trace_events` module: + * + * ```js + * const trace_events = require('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` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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. + */ + 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. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + 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 + * const trace_events = require('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 + * @return . + */ + 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 + * const trace_events = require('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/openai/node_modules/@types/node/ts4.8/assert.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/assert.d.ts new file mode 100644 index 0000000..e4a8a78 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/assert.d.ts @@ -0,0 +1,985 @@ +/** + * The `assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 `assert` module + * will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + actual: unknown; + expected: unknown; + operator: string; + generatedMessage: boolean; + 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/ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is currently experimental and behavior might still change. + * @since v14.2.0, v12.19.0 + * @experimental + */ + 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 '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 that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * 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: this, arguments: [1, 2, 3 ] }]); + * ``` + * + * @since v18.8.0, v16.18.0 + * @param fn + * @returns An Array with 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 'assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * function foo() {} + * + * // 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() + * 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 of objects containing information about the wrapper functions returned by `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 + * tracker.getCalls(callsfunc).length === 1; + * + * tracker.reset(callsfunc); + * 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 `tracker.calls()` and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from '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 '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/ban-types + 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 '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 '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 '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 '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 'assert'; + * + * const obj1 = { + * a: { + * b: 1 + * } + * }; + * const obj2 = { + * a: { + * b: 2 + * } + * }; + * const obj3 = { + * a: { + * b: 1 + * } + * }; + * const obj4 = Object.create(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 '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 '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 '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 '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: + * 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: + * 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 '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 '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 '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 '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 '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 '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 '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 '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` 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 `AssertionError` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value' + * } + * ); + * ``` + * + * ```js + * import assert from '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 '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` 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 'assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError + * ); + * ``` + * + * ```js + * import assert from '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 '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 `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 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 '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 `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 v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + > + & { + (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; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/assert/strict.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/assert/strict.d.ts new file mode 100644 index 0000000..f333913 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/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/openai/node_modules/@types/node/ts4.8/async_hooks.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/async_hooks.d.ts new file mode 100644 index 0000000..1ae6885 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/async_hooks.d.ts @@ -0,0 +1,522 @@ +/** + * The `async_hooks` module provides an API to track asynchronous resources. It + * can be accessed using: + * + * ```js + * import async_hooks from 'async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'async_hooks'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * 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`. + * @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 'fs'; + * import { executionAsyncId, executionAsyncResource } from '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 'http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook + * } from '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`. + * @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. + * @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 '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 '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. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @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 & { + asyncResource: AsyncResource; + }; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * + * The returned function will have an `asyncResource` property referencing + * the `AsyncResource` to which the function is bound. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>( + fn: Func, + ): Func & { + asyncResource: AsyncResource; + }; + /** + * 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; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `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 'http'; + * import { AsyncLocalStorage } from '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 + * // 1: start + * // 0: finish + * // 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 { + /** + * Binds the given function to the current execution context. + * @since v18.16.0 + * @param fn The function to bind to the current execution context. + * @returns A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func & { + asyncResource: AsyncResource; + }; + /** + * 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. + * @since v18.16.0 + */ + static snapshot(): ((fn: (...args: TArgs) => R, ...args: TArgs) => R) & { + asyncResource: AsyncResource; + }; + /** + * 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; + /** + * 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; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/buffer.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/buffer.d.ts new file mode 100644 index 0000000..cfc1f39 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/buffer.d.ts @@ -0,0 +1,2321 @@ +/** + * `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 '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/v18.0.0/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export const 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" | "utf16le" | "ucs2" | "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 '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; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new(size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * 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; + /** + * 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 (WHATWG) `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 `require('node:os').EOL`. + */ + 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. + * @experimental + * @since v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + + import { Blob as NodeBlob } from "buffer"; + // This conditional type will be the existing global Blob in a browser, or + // the copy below in a Node environment. + type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob; + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * 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 { + /** + * 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: Uint8Array): 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 containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: readonly any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): 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 'buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * 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( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | readonly number[]): Buffer; + from(data: WithImplicitCoercion): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: "string"): string; + }, + encoding?: BufferEncoding, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from '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 '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 '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 | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * 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 '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`. + * @since v18.16.0 + * @param view The `TypedArray` to copy. + * @param offset The starting offset within `view`. + * @param length The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * 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 '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; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_INVALID_ARG_VALUE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from '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 '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_INVALID_ARG_VALUE` 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 '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)`, `Buffer.concat()`, and the + * deprecated`new Buffer(size)` constructor only when `size` is less than or equal + * to `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_INVALID_ARG_VALUE` 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 KB 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 '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; + /** + * 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 extends Uint8Array { + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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; + /** + * 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 '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 '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 '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; + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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(): Buffer; + /** + * 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 '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(): Buffer; + /** + * 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 '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(): Buffer; + /** + * 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 'buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * ``` + * + * `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 '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 '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`. + * @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; + /** + * 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 '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 '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; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from '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 '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; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from '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; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + 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 `require('node:buffer').Blob` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { + onmessage: any; + Blob: infer T; + } ? T + : typeof NodeBlob; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/child_process.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/child_process.d.ts new file mode 100644 index 0000000..6c7a2c1 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/child_process.d.ts @@ -0,0 +1,1544 @@ +/** + * The `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 + * const { spawn } = require('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 `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/v18.0.0/lib/child_process.js) + */ +declare module "child_process" { + import { ObjectEncodingOptions } from "node:fs"; + import { Abortable, EventEmitter } from "node:events"; + 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; + /** + * 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 `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 + * const { spawn } = require('child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` 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` 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 currently 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 + * const assert = require('assert'); + * const fs = require('fs'); + * const child_process = require('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 + * const { spawn } = require('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 + * const { spawn } = require('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'; + * const { spawn } = require('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 v18.18.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 + * const cp = require('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. + * + * 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 + * const subprocess = require('child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('net').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 `net` module, `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, currently 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 + * const { fork } = require('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 = require('net').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 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 + * const { spawn } = require('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 + * const { spawn } = require('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 + * const { spawn } = require('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 + * const { spawn } = require('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 + * const { spawn } = require('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 currently 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 + * const { spawn } = require('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; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + } + /** + * 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 + * const { exec } = require('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 + * const { exec } = require('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 + * const util = require('util'); + * const exec = util.promisify(require('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 + * const { exec } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.log(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: { + encoding: "buffer" | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptions, + 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: (ObjectEncodingOptions & 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: { + encoding: "buffer" | null; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | 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; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + 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 + * const { execFile } = require('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 + * const util = require('util'); + * const execFile = util.promisify(require('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 + * const { execFile } = require('child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.log(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. + */ + function execFile(file: string): ChildProcess; + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + function execFile(file: string, args?: readonly string[] | null): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + // 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 `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; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + 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: (ObjectEncodingOptions & 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: (ObjectEncodingOptions & 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: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & 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 { + * const { fork } = require('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, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, 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', '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; + 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/openai/node_modules/@types/node/ts4.8/cluster.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/cluster.d.ts new file mode 100644 index 0000000..e33eab7 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/cluster.d.ts @@ -0,0 +1,432 @@ +/** + * 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` 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 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * 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/v18.0.0/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 { + execArgv?: string[] | undefined; // default: process.execArgv + exec?: string | undefined; + args?: string[] | undefined; + silent?: boolean | undefined; + stdio?: any[] | undefined; + uid?: number | undefined; + gid?: number | undefined; + inspectPort?: number | (() => number) | undefined; + serialization?: SerializationType | undefined; + cwd?: string | undefined; + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 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()`, the returned object + * from this function is stored as `.process`. In a worker, the global `process`is stored. + * + * See: `Child Process module`. + * + * 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()`. + * + * 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. `options` supports the following properties: + */ + 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()`. + * @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 + * 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 net = require('net'); + * 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(): void; + /** + * 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 'cluster'; + * import http from 'http'; + * import { cpus } from 'os'; + * import process from 'process'; + * + * const numCPUs = cpus().length; + * + * 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; + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + readonly isPrimary: boolean; + readonly isWorker: boolean; + schedulingPolicy: number; + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use setupPrimary. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in cluster.settings. + */ + setupPrimary(settings?: ClusterSettings): void; + readonly worker?: Worker | undefined; + 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/openai/node_modules/@types/node/ts4.8/console.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/console.d.ts new file mode 100644 index 0000000..c627daf --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/console.d.ts @@ -0,0 +1,412 @@ +/** + * 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` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**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` 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/v18.0.0/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()`. + * + * 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 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 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()` 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()`). + * + * ```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()` is called on each argument and the resulting string + * values are concatenated. See `util.format()` 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()`). + * + * ```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()` 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 + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('100-elements'); + * for (let i = 0; i < 100; i++) {} + * console.timeEnd('100-elements'); + * // prints 100-elements: 225.438ms + * ``` + * @since v0.1.104 + */ + 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 + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the `util.format()` 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. + * Starts a JavaScript CPU profile with an optional label. + */ + 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. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + 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` and `process.stderr`. The global `console` can be used without calling`require('console')`. + * + * _**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` 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/v16.4.2/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + ignoreErrors?: boolean | undefined; + colorMode?: boolean | "auto" | undefined; + 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/openai/node_modules/@types/node/ts4.8/constants.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/constants.d.ts new file mode 100644 index 0000000..c3ac2b8 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/constants.d.ts @@ -0,0 +1,19 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module "constants" { + import { constants as osConstants, SignalConstants } from "node:os"; + import { constants as cryptoConstants } from "node:crypto"; + import { constants as fsConstants } from "node:fs"; + + const exp: + & typeof osConstants.errno + & typeof osConstants.priority + & SignalConstants + & typeof cryptoConstants + & typeof fsConstants; + export = exp; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/crypto.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/crypto.d.ts new file mode 100644 index 0000000..ee6cba3 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/crypto.d.ts @@ -0,0 +1,4456 @@ +/** + * The `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('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/v18.0.0/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](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen). + * + * `` 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 `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/man1.1.0/apps/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('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('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 'buffer'; + * const { Certificate } = await import('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-v10.x/docs/api/crypto.html#crypto_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; + /** 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 "speshul" version 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; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: 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 ALPN_ENABLED: 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 'fs'; + * import { argv } from 'process'; + * const { + * createHash + * } = await import('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`. + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream + * } from 'fs'; + * import { argv } from 'process'; + * const { + * createHmac + * } = await import('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" | "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('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 'fs'; + * import { stdout } from 'process'; + * const { createHash } = await import('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('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('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?: stream.TransformOptions): 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('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 'fs'; + * import { stdout } from 'process'; + * const { + * createHmac + * } = await import('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('crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + */ + 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 { webcrypto, KeyObject } = await import('crypto'); + * const { subtle } = webcrypto; + * + * 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; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | 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 v16.15.0 + */ + 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; + /** + * 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" | "chacha20-poly1305"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + 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; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`. + * + * 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 `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * 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: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` 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 createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('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 `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * + * import { + * pipeline + * } from 'stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv + * } = await import('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('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 Cipher 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 `Cipher` 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 `Cipher` 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 Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key). + * + * 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`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` 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: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` 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 createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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', () => { + * 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 `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'fs'; + * import { Buffer } from 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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 'buffer'; + * const { + * scryptSync, + * createDecipheriv + * } = await import('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 Decipher 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 `Decipher` 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 Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + 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('crypto'); + * + * generateKey('hmac', { length: 64 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * @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('crypto'); + * + * const key = generateKeySync('hmac', { length: 64 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * @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 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('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('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): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + 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 'assert'; + * + * const { + * createDiffieHellman + * } = await import('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, 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. + * @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`. + * @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 `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: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`, + * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). 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('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. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * 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('crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been + * deprecated and use should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey); // '3745e48...aa39b34' + * }); + * ``` + * + * 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`. + * + * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated, + * please specify a `digest` explicitly. + * + * 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('crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use + * should be avoided. + * + * ```js + * import crypto from 'crypto'; + * crypto.DEFAULT_ENCODING = 'hex'; + * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512'); + * console.log(key); // '3745e48...aa39b34' + * ``` + * + * 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('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('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('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('crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt + * } = await import('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 'buffer'; + * const { randomFillSync } = await import('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 'buffer'; + * const { randomFillSync } = await import('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 'buffer'; + * const { randomFill } = await import('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 'buffer'; + * const { randomFill } = await import('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('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('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): 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): 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): 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): Buffer; + /** + * ```js + * const { + * getCiphers + * } = await import('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('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('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 'assert'; + * + * const { + * createECDH + * } = await import('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('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 is based on a constant-time algorithm. + * Returns true if `a` is equal to `b`, without leaking 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. + * + * 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; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: BufferEncoding; + 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('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('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, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + 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'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): 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 'buffer'; + * const { + * hkdf + * } = await import('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. It must be at least one byte in 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 'buffer'; + * const { + * hkdfSync + * } = await import('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. It must be at least one byte in 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; + } + /** + * 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): string; + 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('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. + * @since 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 or `undefined` + * if not available. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * The information access content of this certificate or `undefined` if not + * available. + * @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 until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + 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 issued by the given `otherCert`. + * @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` + * + * The flags below are deprecated in OpenSSL-1.1.0. + * + * - `crypto.constants.ENGINE_METHOD_ECDH` + * - `crypto.constants.ENGINE_METHOD_ECDSA` + * - `crypto.constants.ENGINE_METHOD_STORE` + * @since v0.11.11 + * @param [flags=crypto.constants.ENGINE_METHOD_ALL] + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for `crypto.webcrypto.getRandomValues()`. + * This implementation is not compliant with the Web Crypto spec, + * to write web-compatible code use `crypto.webcrypto.getRandomValues()` instead. + * @since v17.4.0 + * @returns 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; + } + /** + * Calling `require('node:crypto').webcrypto` returns 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(): string; + 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: AlgorithmIdentifier | 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: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: + | AlgorithmIdentifier + | AesDerivedKeyParams + | HmacImportParams + | HkdfParams + | Pbkdf2Params, + 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; + } + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/dgram.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/dgram.d.ts new file mode 100644 index 0000000..25a4f65 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/dgram.d.ts @@ -0,0 +1,596 @@ +/** + * The `dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`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/v18.0.0/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo } 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; + /** + * @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; + } + /** + * 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 'cluster'; + * import dgram from '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 'dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.log(`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 + * @return the number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0 + * @return the 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 'dgram'; + * import { Buffer } from '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 'dgram'; + * import { Buffer } from '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 'dgram'; + * import { Buffer } from '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 | Uint8Array | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + 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 addition 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 v18.18.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts new file mode 100644 index 0000000..e5f1202 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts @@ -0,0 +1,546 @@ +/** + * The `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 '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. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 '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 interact with 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 '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 '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 diagnostics_channel.subscribe(name, onMessage). + * + * ```js + * import diagnostics_channel from '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 + * @returns `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 use 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 '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 '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 'diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @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 '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 + * @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 v18.19.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 v18.19.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: any): void; + /** + * 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(): void; + } + 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 v18.19.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 v18.19.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 v18.19.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. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v18.19.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) => any, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): void; + /** + * 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. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v18.19.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 + ): void; + /** + * 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. + * + * ```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 v18.19.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 any>( + fn: Fn, + position: number | undefined, + context: ContextType | undefined, + thisArg: any, + ...args: Parameters + ): void; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/dns.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/dns.d.ts new file mode 100644 index 0000000..104dd76 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/dns.d.ts @@ -0,0 +1,809 @@ +/** + * The `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 + * const dns = require('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 `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 + * const dns = require('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` for more information. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + 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 { + family?: number | undefined; + hints?: number | undefined; + all?: boolean | undefined; + /** + * @default true + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + address: string; + 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 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` before using`dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('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()` 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` object, where `err.code` is the error code. + * + * ```js + * const dns = require('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()` 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 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 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 + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | 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` 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", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "AAAA", + 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: "CNAME", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => 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: "NS", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => 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: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | 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: "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: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise; + } + /** + * 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 a 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 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` object, where `err.code` is + * one of the `DNS 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 `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v18.17.0 + */ + export 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 + * 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` 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 `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and {@link setDefaultResultOrder} have higher + * priority than `--dns-result-order`. When using `worker threads`,{@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'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + // Error codes + export const NODATA: string; + export const FORMERR: string; + export const SERVFAIL: string; + export const NOTFOUND: string; + export const NOTIMP: string; + export const REFUSED: string; + export const BADQUERY: string; + export const BADNAME: string; + export const BADFAMILY: string; + export const BADRESP: string; + export const CONNREFUSED: string; + export const TIMEOUT: string; + export const EOF: string; + export const FILE: string; + export const NOMEM: string; + export const DESTRUCTION: string; + export const BADSTR: string; + export const BADFLAGS: string; + export const NONAME: string; + export const BADHINTS: string; + export const NOTINITIALIZED: string; + export const LOADIPHLPAPI: string; + export const ADDRGETNETWORKPARAMS: string; + export const CANCELLED: string; + export interface ResolverOptions { + timeout?: number | undefined; + /** + * @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()` does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('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 `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; + 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/openai/node_modules/@types/node/ts4.8/dns/promises.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/dns/promises.d.ts new file mode 100644 index 0000000..282ec72 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/dns/promises.d.ts @@ -0,0 +1,381 @@ +/** + * 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 `require('dns').promises` or `require('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, + } 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` 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()` 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` before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('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` object, where `err.code`is the error code. + * + * ```js + * const dnsPromises = require('dns').promises; + * 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` object, where `err.code`is one of the `DNS 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"): Promise; + function resolve(hostname: string, rrtype: "AAAA"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "CNAME"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "NS"): Promise; + function resolve(hostname: string, rrtype: "PTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve( + hostname: string, + rrtype: string, + ): Promise; + /** + * 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 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` object, where `err.code`is one of the `DNS error codes`. + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v18.17.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 `verbatim` in `dns.lookup()` and `dnsPromises.lookup()`. The value could be: + * + * * `ipv4first`: sets default `verbatim` `false`. + * * `verbatim`: sets default `verbatim` `true`. + * + * The default is `ipv4first` and `dnsPromises.setDefaultResultOrder()` have + * higher priority than `--dns-result-order`. When using `worker threads`,`dnsPromises.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'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "verbatim"): void; + class Resolver { + constructor(options?: ResolverOptions); + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/dom-events.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/dom-events.d.ts new file mode 100644 index 0000000..147a7b6 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/dom-events.d.ts @@ -0,0 +1,122 @@ +export {}; // Don't export anything! + +//// DOM-like Events +// NB: The Event / EventTarget / EventListener implementations below were copied +// from lib.dom.d.ts, then edited to reflect Node's documentation at +// https://nodejs.org/api/events.html#class-eventtarget. +// Please read that link to understand important implementation differences. + +// This conditional type will be the existing global Event in a browser, or +// the copy below in a Node environment. +type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {} + : { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?]; + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + }; + +// See comment above explaining conditional type +type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {} + : { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + }; + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +import {} from "events"; // Make this an ambient declaration +declare global { + /** An event which takes place in the DOM. */ + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T + : { + prototype: __Event; + new(type: string, eventInitDict?: EventInit): __Event; + }; + + /** + * EventTarget is a DOM interface implemented by objects that can + * receive events and may have listeners for them. + */ + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T + : { + prototype: __EventTarget; + new(): __EventTarget; + }; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/domain.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/domain.d.ts new file mode 100644 index 0000000..ca8728f --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/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/v18.0.0/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 lowlevel 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 + * const domain = require('domain'); + * const fs = require('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/openai/node_modules/@types/node/ts4.8/events.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/events.d.ts new file mode 100644 index 0000000..bcdf24f --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/events.d.ts @@ -0,0 +1,754 @@ +/** + * 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 + * const EventEmitter = require('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/v18.0.0/lib/events.js) + */ +declare module "events" { + // 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; + } + // Any EventTarget with a Node-style `once` function + interface _NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + // Any EventTarget with a DOM-style `addEventListener` + interface _DOMEventTarget { + addEventListener( + eventName: string, + listener: (...args: any[]) => void, + opts?: { + once: boolean; + }, + ): any; + } + interface StaticEventEmitterOptions { + signal?: AbortSignal | undefined; + } + interface EventEmitter extends NodeJS.EventEmitter {} + /** + * The `EventEmitter` class is defined and exposed by the `events` module: + * + * ```js + * const EventEmitter = require('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 { + constructor(options?: EventEmitterOptions); + /** + * 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 + * const { once, EventEmitter } = require('events'); + * + * async function run() { + * 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.log('error happened', err); + * } + * } + * + * run(); + * ``` + * + * 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 + * const { EventEmitter, once } = require('events'); + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.log('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * const { EventEmitter, once } = require('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: _NodeEventTarget, + eventName: string | symbol, + options?: StaticEventEmitterOptions, + ): Promise; + static once(emitter: _DOMEventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * const { on, EventEmitter } = require('events'); + * + * (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')) { + * // 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 + * const { on, EventEmitter } = require('events'); + * 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()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string, + options?: StaticEventEmitterOptions, + ): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName`registered on the given `emitter`. + * + * ```js + * const { EventEmitter, listenerCount } = require('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 + * const { getEventListeners, EventEmitter } = require('events'); + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * getEventListeners(ee, 'foo'); // [listener] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * getEventListeners(et, 'foo'); // [listener] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: _DOMEventTarget | 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 v18.17.0 + */ + static getMaxListeners(emitter: _DOMEventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * const { + * setMaxListeners, + * EventEmitter + * } = require('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 eventsTargets 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<_DOMEventTarget | NodeJS.EventEmitter>): 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 v18.18.0 + * @experimental + * @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. + */ + static readonly errorMonitor: unique symbol; + static readonly captureRejectionSymbol: unique symbol; + /** + * Sets or gets the default captureRejection value for all emitters. + */ + // TODO: These should be described using static getter/setter pairs: + static captureRejections: boolean; + 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; + } + } + global { + namespace NodeJS { + interface EventEmitter { + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: string | symbol, listener: (...args: any[]) => void): 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 + * 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: string | symbol, listener: (...args: any[]) => void): 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 + * 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: string | symbol, listener: (...args: any[]) => void): 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 + * 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 + * 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: string | symbol, listener: (...args: any[]) => void): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: string | symbol, listener: (...args: any[]) => void): 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(event?: string | symbol): 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 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: string | symbol): Function[]; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * 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: string | symbol): Function[]; + /** + * 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 + * const EventEmitter = require('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: string | symbol, ...args: any[]): boolean; + /** + * Returns the number of listeners listening to 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: string | symbol, listener?: Function): 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: string | symbol, listener: (...args: any[]) => void): 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: string | symbol, listener: (...args: any[]) => void): 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 + * const EventEmitter = require('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; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/fs.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/fs.d.ts new file mode 100644 index 0000000..b36d51c --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/fs.d.ts @@ -0,0 +1,4231 @@ +/** + * The `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 'fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from '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/v18.0.0/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} and {@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`. + * + * ```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 {} + + 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 {@link statfsSync} are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`. + * @since 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: string; + /** + * The base path that this `fs.Dirent` object refers to. + * @since v18.17.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from '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](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be resolved 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 resolved 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; + } + /** + * 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: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => 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: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", 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: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", 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: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", 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: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * 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: "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: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => 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: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => 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: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => 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: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => 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: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): 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 '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 '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 | null, 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 | null): 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 | null): 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 '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 | null, 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 | null): 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 | null): 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 '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`. + * + * 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 '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). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * In case of an error, the err.code will be one of Common System Errors. + * @param path A path to an existing file or directory on the file system to be queried. + * @param callback + */ + 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). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * In case of an error, the err.code will be one of Common System Errors. + * @param path A path to an existing file or directory on the file system to be queried. + * @param callback + */ + 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 set, 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. + * + * Relative targets are relative to the link’s parent directory. + * + * ```js + * import { symlink } from '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 + */ + 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 + */ + 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 '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. + * + * 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. + * + * ```js + * import { mkdir } from 'fs'; + * + * // Creates /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 '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 'fs'; + * + * mkdtemp(path.join(os.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 + * (`require('path').sep`). + * + * ```js + * import { tmpdir } from 'os'; + * import { mkdtemp } from '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 '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; + 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; + } + /** + * 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[]; + /** + * 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; + /** + * 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 + */ + 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 `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 `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 + * @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, + 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: number | 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 + */ + 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 '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 '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 '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 '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: Buffer) => 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 | Buffer) => 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: Buffer) => 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 '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, + ): Buffer; + /** + * 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 | Buffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | 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 'fs'; + * import { Buffer } from '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 '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 'fs'; + * import { Buffer } from '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 '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 '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 '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 '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 '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 '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 '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 '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. + * @param listener The callback listener will be called each time the file is accessed. + */ + 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 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: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options?: WatchOptions | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options: WatchOptions | string, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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; + 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; + } + /** + * Unlike the 16 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `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 '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 '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 '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 '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 + */ + 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, + 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 + * @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 + */ + 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, + 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 + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + export interface OpenDirOptions { + 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; + } + /** + * 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; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/fs/promises.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/fs/promises.d.ts new file mode 100644 index 0000000..7e55f89 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/fs/promises.d.ts @@ -0,0 +1,1205 @@ +/** + * 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, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + 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?: number | null; + } + interface CreateReadStreamOptions { + 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; + } + interface ReadableWebStreamOptions { + /** + * Whether to open a normal or a `'bytes'` stream. + * @since v18.17.0 + */ + type?: "bytes" | 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 & FlagAndOpenMode) | 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 kb default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 kb. + * + * `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 '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 '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 Fufills 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?: number | null, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a `ReadableStream` that may be used to read the files data. + * + * 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 + * @experimental + */ + 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; + flag?: OpenMode | undefined; + } | 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. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | 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. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. For example: + * + * ```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 + * @param options See `filehandle.createReadStream()` for the options. + */ + 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 '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 resolves 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 + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is resolved 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 resolved (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 & FlagAndOpenMode & Abortable) | BufferEncoding | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is resolved 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 resolved (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=0] 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 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( + 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 resolved 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 resolved (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 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 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 '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; + /** + * An alias for {@link FileHandle.close()}. + * @since v18.18.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 resolved 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 } from 'fs/promises'; + * import { constants } from 'fs'; + * + * 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 { constants } from 'fs'; + * import { copyFile } from 'fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.log('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.log('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. + * @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 resolved array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from '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; + /** + * 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 + * resolved 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'`. Windows junction points require the destination path + * to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. + * @since v10.0.0 + * @param [type='file'] + * @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 v18.15.0 + * @return Fulfills with an {fs.StatFs} for the file system. + */ + 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 'fs/promises'; + * + * try { + * await mkdtemp(path.join(os.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 + * (`require('path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the filesystem 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 + * [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 'fs/promises'; + * import { Buffer } from '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; + } & 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) | 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. + * + * 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 '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 '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; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('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: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: WatchOptions | string, + ): AsyncIterable> | AsyncIterable>; + /** + * 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; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/globals.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/globals.d.ts new file mode 100644 index 0000000..f6c95e9 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/globals.d.ts @@ -0,0 +1,377 @@ +export {}; // Make this a module + +// #region Fetch and friends +// Conditional type aliases, used at the end of this file. +// Will either be empty if lib-dom is included, or the undici version otherwise. +type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; +type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; +type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; +type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; +type _RequestInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").RequestInit; +type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").ResponseInit; +// #endregion Fetch and friends + +declare global { + // Declare "static" methods in Error + interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; + } + + /*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + + // For backwards compability + interface NodeRequire extends NodeJS.Require {} + interface RequireResolve extends NodeJS.RequireResolve {} + interface NodeModule extends NodeJS.Module {} + + var process: NodeJS.Process; + var console: Console; + + var __filename: string; + var __dirname: string; + + var require: NodeRequire; + var module: NodeModule; + + // Same as module.exports + var exports: any; + + /** + * Only available if `--expose-gc` is passed to the process. + */ + var gc: undefined | (() => void); + + // #region borrowed + // from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib + /** A controller object that allows you to abort one or more DOM requests as and when desired. */ + interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(reason?: any): void; + } + + /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ + interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; + readonly reason: any; + onabort: null | ((this: AbortSignal, event: Event) => any); + throwIfAborted(): void; + } + + var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T + : { + prototype: AbortController; + new(): AbortController; + }; + + var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; + // #endregion borrowed + + // #region Disposable + interface SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: unique symbol; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: unique symbol; + } + + interface Disposable { + [Symbol.dispose](): void; + } + + interface AsyncDisposable { + [Symbol.asyncDispose](): PromiseLike; + } + // #endregion Disposable + + // #region ArrayLike.at() + interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; + } + interface String extends RelativeIndexable {} + interface Array extends RelativeIndexable {} + interface ReadonlyArray extends RelativeIndexable {} + interface Int8Array extends RelativeIndexable {} + interface Uint8Array extends RelativeIndexable {} + interface Uint8ClampedArray extends RelativeIndexable {} + interface Int16Array extends RelativeIndexable {} + interface Uint16Array extends RelativeIndexable {} + interface Int32Array extends RelativeIndexable {} + interface Uint32Array extends RelativeIndexable {} + interface Float32Array extends RelativeIndexable {} + interface Float64Array extends RelativeIndexable {} + interface BigInt64Array extends RelativeIndexable {} + interface BigUint64Array extends RelativeIndexable {} + // #endregion ArrayLike.at() end + + /** + * @since v17.0.0 + * + * Creates a deep clone of an object. + */ + function structuredClone( + value: T, + transfer?: { transfer: ReadonlyArray }, + ): T; + + /*----------------------------------------------* + * * + * GLOBAL INTERFACES * + * * + *-----------------------------------------------*/ + namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | undefined; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): 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; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + ".js": (m: Module, filename: string) => any; + ".json": (m: Module, filename: string) => any; + ".node": (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since v11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + } + + interface RequestInit extends _RequestInit {} + + function fetch( + input: string | URL | Request, + init?: RequestInit, + ): Promise; + + interface Request extends _Request {} + var Request: typeof globalThis extends { + onmessage: any; + Request: infer T; + } ? T + : typeof import("undici-types").Request; + + interface ResponseInit extends _ResponseInit {} + + interface Response extends _Response {} + var Response: typeof globalThis extends { + onmessage: any; + Response: infer T; + } ? T + : typeof import("undici-types").Response; + + interface FormData extends _FormData {} + var FormData: typeof globalThis extends { + onmessage: any; + FormData: infer T; + } ? T + : typeof import("undici-types").FormData; + + interface Headers extends _Headers {} + var Headers: typeof globalThis extends { + onmessage: any; + Headers: infer T; + } ? T + : typeof import("undici-types").Headers; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/globals.global.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/globals.global.d.ts new file mode 100644 index 0000000..ef1198c --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/http.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/http.d.ts new file mode 100644 index 0000000..73fd70a --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/http.d.ts @@ -0,0 +1,1801 @@ +/** + * To use the HTTP server and client one must `require('http')`. + * + * 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: + * + * ```js + * { '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/v18.0.0/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { EventEmitter } from "node:events"; + import { LookupOptions } from "node:dns"; + 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-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-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; + 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; + prgama?: 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; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: + | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | 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; + 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; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v18.17.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 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; + } + 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?: () => void): this; + setTimeout(callback: () => 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 of outgoing message from + * the perspective of the participants of 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; + /** + * Aliases 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 for the header object. + * 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; + /** + * Append a single header value for the header object. + * + * If the value is an array, this is equivalent of calling this method multiple times. + * + * If there were no previous value for the header, this is equivalent of 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 HTTP header with the given name. If such a name doesn't + * exist in message, it 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 of names of headers of the outgoing outgoingMessage. 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 are **only** be emitted if the message is chunked encoded. If not, + * the trailer will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header fields 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; + /** + * Compulsorily 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 request. + * @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 given in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * does not 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 `TypeError` being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends an HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): 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. + * + * Node.js does not check whether Content-Length and the length of the + * body which has been transmitted are equal or not. + * @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 + * const http = require('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 + * const http = require('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.getHeaders()); + * ``` + * + * 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. + * * `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(request.url, `http://${request.getHeaders().host}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and`request.getHeaders().host` is `'localhost:3000'`: + * + * ```console + * $ node + * > new URL(request.url, `http://${request.getHeaders().host}`) + * URL { + * href: 'http://localhost:3000/status?name=ryan', + * origin: 'http://localhost:3000', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost:3000', + * hostname: 'localhost', + * port: '3000', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @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 + * }); + * ``` + * @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; + } + 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. + * @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 + * const http = require('http'); + * + * 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 + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'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'` + * * `'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'` + * * `'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 + * * `'error'` on the `res` object with an error with message`'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'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 itself. + * @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 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` always set to `GET`. Properties that are inherited from the prototype are ignored. + */ + 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'`. + * @param name Header name + * @since v14.3.0 + */ + 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'`. + * @param name Header name + * @param value Header value + * @since v14.3.0 + */ + function validateHeaderValue(name: string, value: string): void; + + /** + * Set the maximum number of idle HTTP parsers. Default: 1000. + * @param count + * @since v18.8.0, v16.18.0 + */ + function setMaxIdleHTTPParsers(count: number): void; + + 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; +} +declare module "node:http" { + export * from "http"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/http2.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/http2.d.ts new file mode 100644 index 0000000..03e92ab --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/http2.d.ts @@ -0,0 +1,2386 @@ +/** + * The `http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. It + * can be accessed using: + * + * ```js + * const http2 = require('http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + 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; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('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 + * const http2 = require('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 + * const http2 = require('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?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * const http2 = require('http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * 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 + * const http2 = require('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 + * const http2 = require('http2'); + * const fs = require('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 + * const http2 = require('http2'); + * const fs = require('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 + * const http2 = require('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.log(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 + * const http2 = require('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 + * const http2 = require('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; + weight?: 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 + * const http2 = require('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 + * const http2 = require('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, 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 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 + * const http2 = require('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 + * const http2 = require('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 + * const http2 = require('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 { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | 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; + selectPadding?(frameLen: number, maxFrameLen: number): number; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions 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 extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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 extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => 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; + /** + * 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: Http2ServerRequest; + /** + * 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 + * const http2 = require('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 `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, + * 'x-trace-id': 'id for diagnostics' + * }); + * ``` + * + * @since v18.11.0 + * @param hints An object containing the values of headers + */ + 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_ORIGIN: 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 + * const http2 = require('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 + * const http2 = require('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(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer( + options: ServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session`instances. + * + * ```js + * const http2 = require('http2'); + * const fs = require('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(80); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('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; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/https.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/https.d.ts new file mode 100644 index 0000000..2f06928 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/https.d.ts @@ -0,0 +1,544 @@ +/** + * 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/v18.0.0/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?: typeof tls.checkServerIdentity | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + 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 & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: 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 & { req: 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/ + * const https = require('https'); + * const fs = require('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 + * const https = require('https'); + * const fs = require('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 + * const https = require('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 + * const tls = require('tls'); + * const https = require('https'); + * const crypto = require('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-sha25 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 + * const https = require('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/openai/node_modules/@types/node/ts4.8/index.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/index.d.ts new file mode 100644 index 0000000..7c8b38c --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/index.d.ts @@ -0,0 +1,88 @@ +/** + * 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 NodeJS and TypeScript 4.8 and earlier. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/inspector.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/inspector.d.ts new file mode 100644 index 0000000..9022f38 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/inspector.d.ts @@ -0,0 +1,2739 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + + +/** + * The `inspector` module provides an API for interacting with the V8 inspector. + * + * It can be accessed using: + * + * ```js + * const inspector = require('inspector'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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?: {} | 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: {}; + } + } + 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?: {} | 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?: {} | 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?: {} | 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[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + 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 TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + 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: Array<{}>; + } + } + 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 NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: 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. + * @since v8.0.0 + */ + connect(): 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. + * @since v8.0.0 + */ + 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. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => 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; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => 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; + /** + * 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; + // Events + 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; + /** + * 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; + 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: 'NodeRuntime.waitingForDisconnect'): 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; + /** + * 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; + 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; + /** + * 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; + 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; + /** + * 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; + 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; + /** + * 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; + } + /** + * 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` regarding the `host`parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + */ + function open(port?: number, host?: string, wait?: boolean): void; + /** + * 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; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + import inspector = require('inspector'); + export = inspector; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/module.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/module.d.ts new file mode 100644 index 0000000..3a08656 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/module.d.ts @@ -0,0 +1,298 @@ +/** + * @since v0.3.7 + */ +declare module "module" { + import { URL } from "node:url"; + import { MessagePort } from "node:worker_threads"; + namespace Module { + /** + * 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 + * const fs = require('fs'); + * const assert = require('assert'); + * const { syncBuiltinESMExports } = require('module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('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; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + */ + function findSourceMap(path: string, error?: Error): SourceMap; + 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; + /** + * 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 { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(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 | {}; + } + /** @deprecated Use `ImportAttributes` instead */ + interface ImportAssertions extends ImportAttributes {} + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + interface GlobalPreloadContext { + port: MessagePort; + } + /** + * @deprecated This hook will be removed in a future version. + * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. + * + * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. + * This hook allows the return of a string that is run as a sloppy-mode script on startup. + * + * @param context Information to assist the preload code + * @return Code to run before application startup + */ + type GlobalPreloadHook = (context: GlobalPreloadContext) => string; + /** + * 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 `register`. + * + * This hook can receive data from a `register` invocation, including ports and other transferrable 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[]; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * 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) + */ + format?: ModuleFormat | null | undefined; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions?: ImportAttributes | 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 resolving file URL for a given module specifier and parent URL, and optionally its 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. + * + * @param specifier The specified URL path of the module to be resolved + * @param context + * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: ResolveHookContext, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain + */ + format: ModuleFormat; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: ModuleFormat; + /** + * 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; + } + /** + * 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 assertion. + * + * @param url The URL/path of the module to be loaded + * @param context Metadata about the module + * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + } + interface RegisterOptions { + parentURL: string | URL; + data?: Data | undefined; + transferList?: any[] | undefined; + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; + static Module: typeof Module; + static register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + static register(specifier: string | URL, options?: RegisterOptions): void; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + url: string; + /** + * @experimental + * This feature is only available with the `--experimental-import-meta-resolve` + * command flag enabled. + * + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * @param specified The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. If none + * is specified, the value of `import.meta.url` is used as the default. + */ + resolve?(specified: string, parent?: string | URL): Promise; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/net.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/net.d.ts new file mode 100644 index 0000000..782b891 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/net.d.ts @@ -0,0 +1,913 @@ +/** + * > Stability: 2 - Stable + * + * The `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 + * const net = require('net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | 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, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + 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; + } + interface IpcSocketConnectOpts extends ConnectOpts { + 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) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => 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 + * @return The socket itself. + */ + 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 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 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 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * @see {https://nodejs.org/api/net.html#socketreadystate} + * @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'`. + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. + * @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. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. ready + * 9. 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: "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: "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: "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: "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: "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: "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 { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: 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; + } + 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.log('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): void; + /** + * 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 + */ + 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 v18.18.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; + } + 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 + * const net = require('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`: + * + * ```console + * $ 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: + * + * ```console + * $ 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; + /** + * 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); + /** + * @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; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/os.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/os.d.ts new file mode 100644 index 0000000..00d0373 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/os.d.ts @@ -0,0 +1,473 @@ +/** + * The `os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + 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 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. + * @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 18.4.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` 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 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; + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'mips'`,`'mipsel'`, `'ppc'`, `'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * The return value is equivalent to `process.arch`. + * @since v0.5.0 + */ + function arch(): string; + /** + * 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, aarch64, mips, mips64, ppc64, ppc64le, s390, 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 + */ + 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/openai/node_modules/@types/node/ts4.8/path.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/path.d.ts new file mode 100644 index 0000000..1465c38 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/path.d.ts @@ -0,0 +1,191 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `path` module provides utilities for working with file and directory paths. + * It can be accessed using: + * + * ```js + * const path = require('path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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; + /** + * 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/openai/node_modules/@types/node/ts4.8/perf_hooks.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/perf_hooks.d.ts new file mode 100644 index 0000000..1960fb3 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/perf_hooks.d.ts @@ -0,0 +1,626 @@ +/** + * 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/) + * + * ```js + * const { PerformanceObserver, performance } = require('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/v18.0.0/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http"; + 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; + } + /** + * @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; + } + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + /** + * _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 { + /** + * 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 V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param util1 The result of a previous call to eventLoopUtilization() + * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 + */ + type EventLoopUtilityFunction = ( + util1?: EventLoopUtilization, + util2?: 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. + * @param name + */ + 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. + * @param name + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * 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. + * @param name + * @return The PerformanceMark entry that was created + */ + mark(name?: string, options?: MarkOptions): PerformanceMark; + /** + * 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; + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + /** + * 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. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * 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; + } + interface PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0 + * * } + * * ] + * + * 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 + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0 + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0 + * * } + * * ] + * + * 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 + * const { + * performance, + * PerformanceObserver + * } = require('perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0 + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0 + * * } + * * ] + * + * 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; + 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 + * const { + * performance, + * PerformanceObserver + * } = require('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; + } + 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 { + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * 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 minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * 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; + } + 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; + } + 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. + * + * ## Examples + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from other to this histogram. + * @since v17.4.0, v16.14.0 + * @param other Recordable Histogram to combine with + */ + 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 + * const { monitorEventLoopDelay } = require('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 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: 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 } from "perf_hooks"; + global { + /** + * `performance` is a global reference for `require('perf_hooks').performance` + * https://nodejs.org/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/openai/node_modules/@types/node/ts4.8/process.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/process.d.ts new file mode 100644 index 0000000..c5d6f87 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/process.d.ts @@ -0,0 +1,1548 @@ +declare module "process" { + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + 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 { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + 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 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" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "s390" + | "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 { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * 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. + * + * @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 error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, 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 '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; + }; + openStdin(): Socket; + /** + * 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 'process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```console + * $ 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. + * + * ```console + * $ node --harmony script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ['--harmony'] + * ``` + * + * 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 '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 '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 'process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * 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 'process'; + * + * // Emit a warning with a code and additional detail. + * emitWarning('Something happened!', { + * code: 'MY_WARNING', + * detail: 'This is some additional information' + * }); + * // Emits: + * // (node:56338) [MY_WARNING] Warning: Something happened! + * // This is some additional information + * ``` + * + * In this example, an `Error` object is generated internally by`process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from '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, the `options` argument is ignored. + * @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: + * + * ```console + * $ node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from '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 '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 '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 '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. + * @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 '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 '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 '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. + */ + exit(code?: number): 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`. + * @since v0.11.8 + */ + exitCode?: number | 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 '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 '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 '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 '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 '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 '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 '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 '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 '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 '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; + /** + * This function enables or disables the Source Map v3 support for stack traces. + * It provides same features as launching Node.js process with commandline options --enable-source-maps. + * @since v16.6.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v18.19.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from '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 'process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '11.13.0', + * v8: '7.0.276.38-node.18', + * uv: '1.27.0', + * zlib: '1.2.11', + * brotli: '1.0.7', + * ares: '1.15.0', + * modules: '67', + * nghttp2: '1.34.0', + * napi: '4', + * llhttp: '1.1.1', + * openssl: '1.1.1b', + * cldr: '34.0', + * icu: '63.1', + * tz: '2018e', + * unicode: '11.0' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns an `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_dtrace: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * + * The `process.config` property is **not** read-only and there are existing + * modules in the ecosystem that are known to extend, modify, or entirely replace + * the value of `process.config`. + * + * Modifying the `process.config` property, or any child-property of the`process.config` object has been deprecated. The `process.config` will be made + * read-only in a future release. + * @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 '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; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from '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 'process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * 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'`, `'mips'`,`'mipsel'`, `'ppc'`,`'ppc64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from '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 '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, `undefined` is returned. + */ + constrainedMemory(): number | undefined; + /** + * 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 '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 '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 '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 '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; + /** + * 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: 'Erbium', + * sourceUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v12.18.1/node-v12.18.1-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v12.18.1/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; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `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?: { + swallowErrors?: 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 '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`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from '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 `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; + /* 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/openai/node_modules/@types/node/ts4.8/punycode.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/punycode.d.ts new file mode 100644 index 0000000..cfe559b --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/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 + * const punycode = require('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/v18.0.0/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/openai/node_modules/@types/node/ts4.8/querystring.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/querystring.d.ts new file mode 100644 index 0000000..1837171 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/querystring.d.ts @@ -0,0 +1,141 @@ +/** + * The `querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('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/v18.0.0/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + maxKeys?: number | undefined; + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | readonly string[] + | readonly number[] + | readonly boolean[] + | 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: + * + * ```js + * { + * 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/openai/node_modules/@types/node/ts4.8/readline.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/readline.d.ts new file mode 100644 index 0000000..60ccb8e --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/readline.d.ts @@ -0,0 +1,666 @@ +/** + * The `readline` module provides an interface for reading data from a `Readable` stream (such as `process.stdin`) 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 `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/v18.0.0/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` 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 v0.1.104 + */ + export class Interface extends EventEmitter { + 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-v10.x/docs/api/readline.html#readline_class_interface + */ + 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-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.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 `readline.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 `readline.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 `readline.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. + * + * 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); + * ``` + * + * If this method is invoked as it's util.promisify()ed version, it returns a + * Promise that fulfills with the answer. If the question is canceled using + * an `AbortController` it will reject with an `AbortError`. + * + * ```js + * const util = require('util'); + * const question = util.promisify(rl.question).bind(rl); + * + * async function questionExample() { + * try { + * const answer = await question('What is you favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * } catch (err) { + * console.error('Question rejected', err); + * } + * } + * questionExample(); + * ``` + * @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 `readline.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 `readline.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 `readline.Interface` instance. + * @since v0.1.98 + */ + close(): 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 `readline.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](): AsyncIterableIterator; + } + 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 { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + 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; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: 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; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface`instance. + * + * ```js + * const readline = require('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 `EOF` (Ctrl+D on + * Linux/macOS, Ctrl+Z followed by Return on + * Windows). + * If you want your application to exit without waiting for user input, you can `unref()` the standard input stream: + * + * ```js + * 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 + * const readline = require('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 + * const fs = require('fs'); + * const readline = require('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 + * const fs = require('fs'); + * const readline = require('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 + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('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` 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` 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` `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` `stream`. + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('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 + * const fs = require('fs'); + * const readline = require('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 + * const fs = require('fs'); + * const readline = require('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 + * const { once } = require('events'); + * const { createReadStream } = require('fs'); + * const { createInterface } = require('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 + * @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/openai/node_modules/@types/node/ts4.8/readline/promises.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/readline/promises.d.ts new file mode 100644 index 0000000..ba603ef --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/readline/promises.d.ts @@ -0,0 +1,143 @@ +/** + * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. + * + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) + * @since v17.0.0 + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + + 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 readlinePromises.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. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + + 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. + */ + 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. + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + */ + 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. + */ + 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. + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. + */ + rollback(): this; + } + + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('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). + * + * ## Use of the `completer` function + * + * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: + * + * - An Array with matching entries for the completion. + * - The substring that was used for the matching. + * + * For instance: `[[substr1, substr2, ...], originalsubstring]`. + * + * ```js + * function completer(line) { + * const completions = '.help .error .exit .quit .q'.split(' '); + * const hits = completions.filter((c) => c.startsWith(line)); + * // Show all completions if none found + * return [hits.length ? hits : completions, line]; + * } + * ``` + * + * The `completer` function can also returns a `Promise`, or be asynchronous: + * + * ```js + * async function completer(linePartial) { + * await someAsyncWork(); + * return [['123'], linePartial]; + * } + * ``` + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/repl.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/repl.d.ts new file mode 100644 index 0000000..7ed370b --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `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 + * const repl = require('repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + 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-v10.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-v11.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; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('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-v10.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-v10.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-v10.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-v10.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-v10.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-v10.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 + * const repl = require('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, an ellipsis 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(path: string, 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 + * const repl = require('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-v10.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/openai/node_modules/@types/node/ts4.8/stream.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/stream.d.ts new file mode 100644 index 0000000..f7d2afb --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/stream.d.ts @@ -0,0 +1,1731 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `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` and `process.stdout` are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of `EventEmitter`. + * + * To access the `stream` module: + * + * ```js + * const stream = require('stream'); + * ``` + * + * The `stream` module is useful for creating new types of stream instances. It is + * usually not necessary to use the `stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 streamConsumers from "node:stream/consumers"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + 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: Readable, 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. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call `readable.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 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding`property can be set using the `readable.setEncoding()` method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when `'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` 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 + * const fs = require('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). + * const { StringDecoder } = require('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`, `Uint8Array` 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 `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 + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('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 }): AsyncIterableIterator; + /** + * 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; + /** + * 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; + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v18.18.0 + */ + [Symbol.asyncDispose](): Promise; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: Writable, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Writable, 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 + * @experimental + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + 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; + /** + * 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` or `Uint8Array`. 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!'. + * const fs = require('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` or `Uint8Array`. 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; + /** + * 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; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void; + } + /** + * 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 Readable implements Writable { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * 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 `false`. + * + * 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; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + /** + * 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; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, 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 {} + /** + * 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. + * + * ```js + * const fs = require('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; + * } + * } + * })(); + * ``` + * @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 `16384` (16 KiB), or `16` for `objectMode`. + * @since v18.17.0 + * @param objectMode + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v18.17.0 + * @param objectMode + * @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 function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('stream'); + * + * 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: + * + * ```js + * const { finished } = require('stream/promises'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * async function run() { + * await finished(rs); + * console.log('Stream is done reading.'); + * } + * + * run().catch(console.error); + * rs.resume(); // Drain the stream. + * ``` + * + * `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. + * @return 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 + * const { pipeline } = require('stream'); + * const fs = require('fs'); + * const zlib = require('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, which can also + * receive an options argument as the last parameter with a`signal` `AbortSignal` property. When the signal is aborted,`destroy` will be called on the underlying pipeline, with + * an`AbortError`. + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * To use an `AbortSignal`, pass it inside an options object, + * as the last argument: + * + * ```js + * const { pipeline } = require('stream/promises'); + * + * async function run() { + * const ac = new AbortController(); + * const signal = ac.signal; + * + * setTimeout(() => ac.abort(), 1); + * await pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * { signal }, + * ); + * } + * + * run().catch(console.error); // AbortError + * ``` + * + * The `pipeline` API also supports async generators: + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * fs.createReadStream('lowercase.txt'), + * async function* (source, { signal }) { + * source.setEncoding('utf8'); // Work with strings rather than `Buffer`s. + * for await (const chunk of source) { + * yield await processChunk(chunk, { signal }); + * } + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * Remember to handle the `signal` argument passed into the async generator. + * Especially in the case where the async generator is the source for the + * pipeline (i.e. first argument) or the pipeline will never complete. + * + * ```js + * const { pipeline } = require('stream/promises'); + * const fs = require('fs'); + * + * async function run() { + * await pipeline( + * async function* ({ signal }) { + * await someLongRunningfn({ signal }); + * yield 'asd'; + * }, + * fs.createWriteStream('uppercase.txt') + * ); + * console.log('Pipeline succeeded.'); + * } + * + * run().catch(console.error); + * ``` + * + * `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 + * const fs = require('fs'); + * const http = require('http'); + * const { pipeline } = require('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 + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + + /** + * Returns whether the stream is readable. + * @since v17.4.0 + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/stream/consumers.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/stream/consumers.d.ts new file mode 100644 index 0000000..5ad9cba --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { Readable } from "node:stream"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/stream/promises.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/stream/promises.d.ts @@ -0,0 +1,83 @@ +declare module "stream/promises" { + import { + FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + 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/openai/node_modules/@types/node/ts4.8/stream/web.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/stream/web.d.ts new file mode 100644 index 0000000..aac0523 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/stream/web.d.ts @@ -0,0 +1,352 @@ +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; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; + 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 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; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + 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; + 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: string): CompressionStream; + }; + interface DecompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: string): DecompressionStream; + }; +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/string_decoder.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/string_decoder.d.ts new file mode 100644 index 0000000..e9a8cc2 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `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 + * const { StringDecoder } = require('string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); + * ``` + * + * 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 + * const { StringDecoder } = require('string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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 A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + write(buffer: Buffer): 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 A `Buffer`, or `TypedArray`, or `DataView` containing the bytes to decode. + */ + end(buffer?: Buffer): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/test.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/test.d.ts new file mode 100644 index 0000000..5557822 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/test.d.ts @@ -0,0 +1,1113 @@ +/** + * The `node:test` module provides a standalone testing module. + * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/test.js) + */ +declare module "node:test" { + import { AsyncResource } from "node:async_hooks"; + /** + * Programmatically start the test runner. + * @since v18.9.0 + * @param options Configuration options for running tests. + * @returns A {@link TestsStream} that emits events about the test execution. + */ + function run(options?: RunOptions): TestsStream; + /** + * The `test()` function is the value imported from the test module. Each invocation of this + * function results in reporting the test to the {@link TestsStream}. + * + * The {@link 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 {@link Promise} that resolves once the test completes. 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); + * }); + * }); + * }); + * ``` + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: 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. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + 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 { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo }; + } + /** + * @since v18.6.0 + * @param name The name of the suite, which is displayed when reporting suite results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the suite + * @param fn The function under suite. Default: A no-op function. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function describe(name?: string, fn?: SuiteFn): Promise; + function describe(options?: TestOptions, fn?: SuiteFn): Promise; + function describe(fn?: SuiteFn): Promise; + namespace describe { + /** + * Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + */ + 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`, same as `describe([name], { todo: true }[, fn])`. + */ + 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`, same as `describe([name], { only: true }[, fn])`. + * @since v18.15.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; + } + + /** + * @since v18.6.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: 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. If the test uses callbacks, the callback function is + * passed as the second argument. Default: A no-op function. + */ + function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function it(name?: string, fn?: TestFn): Promise; + function it(options?: TestOptions, fn?: TestFn): Promise; + function it(fn?: TestFn): Promise; + namespace it { + /** + * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + */ + 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`, same as `it([name], { todo: true }[, fn])`. + */ + 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`, same as `it([name], { only: true }[, fn])`. + * @since v18.15.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; + } + /** + * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. + * @since v18.17.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`, same as `test([name], { todo: true }[, fn])`. + * @since v18.17.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`, same as `test([name], { only: true }[, fn])`. + * @since v18.17.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 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. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => any; + /** + * The type of a function under Suite. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `` 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 files would run in parallel. + * If truthy, it would run (number of cpu cores - 1) files in parallel. + * If falsy, it would only run one file at a time. + * If unspecified, subtests inherit this value from their parent. + * @default true + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. + * If unspecified, the test runner execution model will be used. + */ + files?: readonly string[] | undefined; + /** + * Allows aborting an in-progress test execution. + * @default undefined + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the test will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * That can be used to only run 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. + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; + /** + * If truthy, the test context will only run tests that have the `only` option set + * @since v18.19.0 + */ + only?: boolean; + /** + * A function that accepts the TestsStream instance and can be used to setup listeners before any tests are run. + */ + setup?: (root: Test) => void | Promise; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @since v18.19.0 + * @default undefined + */ + shard?: TestShard | undefined; + } + class Test extends AsyncResource { + concurrency: number; + nesting: number; + only: boolean; + reporter: TestsStream; + runOnlySubtests: boolean; + testNumber: number; + timeout: number | null; + } + + /** + * A successful call of the `run()` method will return a new `TestsStream` object, + * streaming a series of events representing the execution of the tests. + * `TestsStream` will emit events in the order of the tests' definitions. + * @since v18.9.0 + */ + interface TestsStream extends NodeJS.ReadableStream { + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:fail", listener: (data: TestFail) => void): this; + addListener(event: "test:pass", listener: (data: TestPass) => void): this; + addListener(event: "test:plan", listener: (data: TestPlan) => void): this; + addListener(event: "test:start", listener: (data: TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:fail", data: TestFail): boolean; + emit(event: "test:pass", data: TestPass): boolean; + emit(event: "test:plan", data: TestPlan): boolean; + emit(event: "test:start", data: TestStart): boolean; + emit(event: "test:stderr", data: TestStderr): boolean; + emit(event: "test:stdout", data: TestStdout): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:fail", listener: (data: TestFail) => void): this; + on(event: "test:pass", listener: (data: TestPass) => void): this; + on(event: "test:plan", listener: (data: TestPlan) => void): this; + on(event: "test:start", listener: (data: TestStart) => void): this; + on(event: "test:stderr", listener: (data: TestStderr) => void): this; + on(event: "test:stdout", listener: (data: TestStdout) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:fail", listener: (data: TestFail) => void): this; + once(event: "test:pass", listener: (data: TestPass) => void): this; + once(event: "test:plan", listener: (data: TestPlan) => void): this; + once(event: "test:start", listener: (data: TestStart) => void): this; + once(event: "test:stderr", listener: (data: TestStderr) => void): this; + once(event: "test:stdout", listener: (data: TestStdout) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + + /** + * 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 + */ + interface TestContext { + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.17.0 + */ + before: typeof before; + + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach: typeof beforeEach; + + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach: typeof afterEach; + + /** + * 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. + * @param message Message to be reported. + * @since v18.0.0 + */ + diagnostic(message: string): void; + + /** + * The name of the test. + * @since v18.8.0 + */ + readonly name: string; + + /** + * 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. + * @param shouldRunOnlyTests Whether or not to run `only` tests. + * @since v18.0.0 + */ + runOnly(shouldRunOnlyTests: boolean): void; + + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.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. + * @param message Optional skip message. + * @since v18.0.0 + */ + 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. + * @param message Optional `TODO` message. + * @since v18.0.0 + */ + 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. + * Default: 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. Default: A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + + /** + * 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 + */ + class SuiteContext { + /** + * 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; + } + + /** + * This function is used to create a hook running before running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function before(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function after(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running before each subtest of the current suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + + /** + * The hook function. If the hook uses callbacks, the callback function is passed as the + * second argument. + */ + type HookFn = (s: SuiteContext, 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; + }; + + type NoOpFunction = (...args: any[]) => undefined; + + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + + interface MockTracker { + /** + * This function is used to create a mock function. + * @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. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. + * @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. + */ + 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 {@link MockTracker.method} with `options.getter` set to `true`. + */ + 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 {@link MockTracker.method} with `options.setter` set to `true`. + */ + 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 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. + */ + 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. + */ + restoreAll(): void; + 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; + } + + interface MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the mock. + */ + readonly calls: Array>; + + /** + * 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. + */ + callCount(): number; + + /** + * This function is used to change the behavior of an existing mock. + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: Function): 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. + * @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: Function, onCall?: number): void; + + /** + * Resets the call history of the mock function. + */ + resetCalls(): void; + + /** + * Resets the implementation of the mock function to its original behavior. + * The mock can still be used after calling this function. + */ + restore(): void; + } + type Timer = "setInterval" | "clearInterval" | "setTimeout" | "clearTimeout"; + /** + * 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 `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v18.19.0 + * @experimental + */ + class 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. + * + * Example usage: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable(['setInterval']); + * ``` + * + * The above example enables mocking for the `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `setInterval`and `clearInterval` functions from `node:timers`,`node:timers/promises`, and`globalThis` will be mocked. + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout`functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * @since v18.19.0 + */ + enable(timers?: Timer[]): 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 v18.19.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(['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(['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); + * }); + * ``` + * @since v18.19.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. + * + * 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(['setTimeout']); + * 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]); + * }); + * ``` + * + * **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 v18.19.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + + export { after, afterEach, before, beforeEach, describe, it, mock, run, test, test as default }; +} + +interface TestLocationInfo { + /** + * 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 is not ran through a file. + */ + file?: string; + /** + * The line number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + line?: number; +} +interface DiagnosticData extends TestLocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestFail extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The error thrown by the test. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since 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 TestPass extends TestLocationInfo { + /** + * 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 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 TestLocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; +} +interface TestStart extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestStderr extends TestLocationInfo { + /** + * The message written to `stderr` + */ + message: string; +} +interface TestStdout extends TestLocationInfo { + /** + * The message written to `stdout` + */ + message: string; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} + +/** + * 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 'test/reporters'; + * ``` + * @since v18.17.0 + * @see [source](https://github.com/nodejs/node/blob/v18.17.0/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform } from "node:stream"; + + type TestEvent = + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:fail"; data: TestFail } + | { type: "test:pass"; data: TestPass } + | { type: "test:plan"; data: TestPlan } + | { type: "test:start"; data: TestStart } + | { type: "test:stderr"; data: TestStderr } + | { type: "test:stdout"; data: TestStdout } + | { type: "test:enqueue"; data: TestEnqueue } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:watch:drained" }; + type TestEventGenerator = AsyncGenerator; + + /** + * 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`. + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + */ + function tap(source: TestEventGenerator): AsyncGenerator; + /** + * The `spec` reporter outputs the test results in a human-readable format. + */ + class Spec extends Transform { + constructor(); + } + /** + * The `junit` reporter outputs test results in a jUnit XML format + */ + function junit(source: TestEventGenerator): AsyncGenerator; + export { dot, junit, Spec as spec, tap, TestEvent }; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/timers.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/timers.d.ts new file mode 100644 index 0000000..0d1beed --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/timers.d.ts @@ -0,0 +1,126 @@ +/** + * 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 call `require('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/v18.0.0/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import { + setImmediate as setImmediatePromise, + setInterval as setIntervalPromise, + setTimeout as setTimeoutPromise, + } from "node:timers/promises"; + 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; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + interface Immediate extends RefCounted { + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v18.18.0 + */ + [Symbol.dispose](): void; + } + interface Timeout extends Timer { + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * 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 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v18.18.0 + */ + [Symbol.dispose](): void; + } + } + /** + * 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`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. + * If `callback` is not a function, a [TypeError](https://nodejs.org/api/errors.html#class-typeerror) will be thrown. + * @since v0.0.1 + */ + function setTimeout( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + function setInterval( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/timers/promises.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/timers/promises.d.ts new file mode 100644 index 0000000..abb5b42 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/timers/promises.d.ts @@ -0,0 +1,93 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via`require('timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from '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. + * + * ```js + * import { + * setInterval, + * } from '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 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + + interface Scheduler { + /** + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * An experimental API defined by the 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. + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: TimerOptions) => Promise; + /** + * An experimental API defined by the 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 v16.14.0 + * @experimental + */ + yield: () => Promise; + } + + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/tls.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/tls.d.ts new file mode 100644 index 0000000..8c6ff90 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/tls.d.ts @@ -0,0 +1,1203 @@ +/** + * The `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 + * const tls = require('tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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, 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: + * + * ```json + * { + * "name": "AES128-SHA256", + * "standardName": "TLS_RSA_WITH_AES_128_CBC_SHA256", + * "version": "TLSv1.2" + * } + * ``` + * + * 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.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). + */ + addContext(hostname: string, context: SecureContextOptions): 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; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + 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. + * @since v18.19.0 + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | 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. + */ + 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. + */ + 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. + */ + 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 `cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('tls'); + * const fs = require('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. + * const tls = require('tls'); + * const fs = require('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; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and`encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * {@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 {@link createServer} and `server.addContext()`, but has no public methods. + * + * 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). + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * 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`. + * + * 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 tls.createSecureContext() for further + * information. + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the maxVersion option of + * tls.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. + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the minVersion option of tls.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. + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the ciphers option of tls.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. + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM + * format) used for verifying peer certificates. This is the default value + * of the ca option to tls.createSecureContext(). + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/trace_events.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/trace_events.d.ts new file mode 100644 index 0000000..7f0fe55 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/trace_events.d.ts @@ -0,0 +1,171 @@ +/** + * The `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` trace data. + * The `async_hooks` 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.dns.native`: Enables capture of trace data for DNS queries. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.perf`: Enables capture of `Performance API` 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 `vm` module's`runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The `V8` events are GC, compiling, and execution related. + * + * 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 `trace_events` module: + * + * ```js + * const trace_events = require('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` threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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. + */ + 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. + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + */ + 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 + * const trace_events = require('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 + * @return . + */ + 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 + * const trace_events = require('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/openai/node_modules/@types/node/ts4.8/tty.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/tty.d.ts new file mode 100644 index 0000000..c030415 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/tty.d.ts @@ -0,0 +1,206 @@ +/** + * The `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 + * const tty = require('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/v18.0.0/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. Defaults to `false`. + * @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/openai/node_modules/@types/node/ts4.8/url.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/url.d.ts new file mode 100644 index 0000000..ea7b7b1 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/url.d.ts @@ -0,0 +1,937 @@ +/** + * The `url` module provides utilities for URL resolution and parsing. It can be + * accessed using: + * + * ```js + * import url from 'url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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; + } + /** + * 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. + * + * Use of the legacy `url.parse()` method is discouraged. Users should + * use the WHATWG `URL` API. Because the `url.parse()` method uses a + * lenient, non-standard algorithm for parsing URL strings, security + * issues can be introduced. Specifically, issues with [host name spoofing](https://hackerone.com/reports/678487) and + * incorrect handling of usernames and passwords have been identified. + * + * Deprecation of this API has been shelved for now primarily due to the the + * inability of the [WHATWG API to parse relative URLs](https://github.com/nodejs/node/issues/12682#issuecomment-1154492373). + * [Discussions are ongoing](https://github.com/whatwg/url/issues/531) for the best way to resolve this. + * + * @since v0.1.25 + * @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 + * const url = require('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 + * const url = require('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 + * const url = require('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}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from '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}. + * + * This feature is only available if the `node` executable was compiled with `ICU` enabled. If not, the domain names are passed through unchanged. + * + * ```js + * import url from '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 '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): string; + /** + * 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 '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): 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 '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 { + auth?: boolean | undefined; + fragment?: boolean | undefined; + search?: boolean | undefined; + 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 + * const { + * Blob, + * resolveObjectURL, + * } = require('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 + * @experimental + */ + 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 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(objectUrl: 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 v18.17.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; + constructor(input: 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:82'; + * 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; + } + /** + * 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[@@iterator]()`. + */ + entries(): IterableIterator<[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( + callback: (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(): IterableIterator; + /** + * 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 v18.16.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(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/util.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/util.d.ts new file mode 100644 index 0000000..3b1d9f9 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/util.d.ts @@ -0,0 +1,2075 @@ +/** + * The `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 + * const util = require('util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.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; + } + /** + * 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; + /** + * 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; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * 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 is fulfilled when the `signal` is aborted. + * If the passed `resource` is garbage collected before the `signal` is aborted, the returned promise shall remain pending indefinitely. + * @param resource Any non-null entity, reference to which is held weakly. + */ + 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 `@@toStringTag` 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 + * const { inspect } = require('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 + * const util = require('util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('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(util.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(util.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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('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 + * const { inspect } = require('util'); + * const assert = require('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 + * const { inspect } = require('util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(thousand, million, bigNumber, bigDecimal); + * // 1_000 1_000_000 123_456_789n 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MB. 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 + * const util = require('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[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates`@@toStringTag`. + * + * ```js + * const util = require('util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * 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('util'); + * const EventEmitter = require('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 + * const EventEmitter = require('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 { + 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 + * const util = require('util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('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 + * const util = require('util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('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 + * const util = require('util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = 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 const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Deprecated: Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('util'); + * + * exports.obsoleteFunction = util.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 + * const util = require('util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, '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 + * const util = require('util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.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 + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('util'); + * const fs = require('fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify`will return its value, see `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 + * const util = require('util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // 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; + } + /** + * 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 `require('util').TextDecoder` + * 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 `require('util').TextEncoder` + * 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 high-level API for command-line argument parsing. Takes a + * specification for the expected arguments and returns a structured object + * with the parsed values and positionals. + * + * `config` provides arguments for parsing and configures the parser. It + * supports the following properties: + * + * - `args` The array of argument strings. **Default:** `process.argv` with + * `execPath` and `filename` removed. + * - `options` Arguments known to the parser. Keys of `options` are the long + * names of options and values are objects accepting the following properties: + * + * - `type` Type of argument, which must be either `boolean` (for options + * which do not take values) or `string` (for options which do). + * - `multiple` 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`. + * - `short` A single character alias for the option. + * - `default` The default option value when it is not set by args. It + * must be of the same type as the `type` property. When `multiple` + * is `true`, it must be an array. + * + * - `strict`: Whether an error should be thrown when unknown arguments + * are encountered, or when arguments are passed that do not match the + * `type` configured in `options`. **Default:** `true`. + * - `allowPositionals`: Whether this command accepts positional arguments. + * **Default:** `false` if `strict` is `true`, otherwise `true`. + * - `tokens`: Whether tokens {boolean} 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`. + * + * @returns The parsed command line arguments: + * + * - `values` A mapping of parsed option names with their string + * or boolean values. + * - `positionals` Positional arguments. + * - `tokens` Detailed parse information (only if `tokens` was specified). + */ + export function parseArgs(config?: T): ParsedResults; + + interface ParseArgsOptionConfig { + /** + * Type of argument. + */ + type: "string" | "boolean"; + /** + * 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 option value when it is not set by args. + * It must be of the same type as the the `type` property. + * When `multiple` is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + + interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionConfig; + } + + 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; + /** + * 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 ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? { + -readonly [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + undefined | Array>, + undefined | ExtractOptionValue + >; + } + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionConfig, + > = 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; + + /** + * @since 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. + */ + type: string; + + /** + * Gets and sets the subtype portion of the MIME. + */ + subtype: string; + + /** + * Gets the essence of the MIME. + * + * Use `mime.type` or `mime.subtype` to alter the MIME. + */ + readonly essence: string; + + /** + * Gets the `MIMEParams` object representing the parameters of the MIME. + */ + readonly params: MIMEParams; + + /** + * 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; + } + + /** + * @since 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. + */ + entries(): IterableIterator<[string, string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. + * If there are no such pairs, `null` is returned. + */ + 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. + */ + keys(): IterableIterator; + /** + * 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`. + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } +} +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 `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 + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * 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 is an instance of a built-in `Error` type. + * + * ```js + * util.types.isNativeError(new Error()); // Returns true + * util.types.isNativeError(new TypeError()); // Returns true + * util.types.isNativeError(new RangeError()); // Returns true + * ``` + * @since v10.0.0 + */ + 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/openai/node_modules/@types/node/ts4.8/v8.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/v8.d.ts new file mode 100644 index 0000000..b22d7fb --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/v8.d.ts @@ -0,0 +1,541 @@ +/** + * The `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 + * const v8 = require('v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/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; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + /** + * 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. + * + * ```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 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * 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. + * const v8 = require('v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * 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 + * const v8 = require('v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable Stream containing the V8 heap snapshot + */ + function getHeapSnapshot(): 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 + * const { writeHeapSnapshot } = require('v8'); + * const { + * Worker, + * isMainThread, + * parentPort + * } = require('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): string; + /** + * Returns an object with the following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794 + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @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.TypedArray): 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; + + /** + * This API collects GC data in current thread. + */ + class GCProfiler { + /** + * Start collecting GC data. + */ + start(): void; + /** + * Stop collecting GC data and return a object. + */ + 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; +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/node_modules/openai/node_modules/@types/node/ts4.8/vm.d.ts b/node_modules/openai/node_modules/@types/node/ts4.8/vm.d.ts new file mode 100644 index 0000000..c63d156 --- /dev/null +++ b/node_modules/openai/node_modules/@types/node/ts4.8/vm.d.ts @@ -0,0 +1,667 @@ +/** + * The `vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `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 + * const vm = require('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/v18.0.0/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; + } + interface ScriptOptions extends BaseOptions { + /** + * V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Called during evaluation of this module when `import()` is called. + * If this option is not specified, calls to `import()` will reject with `ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING`. + */ + importModuleDynamically?: + | ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module) + | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * Default: `true`. + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * Default: `false`. + */ + breakOnSigint?: boolean | undefined; + } + interface RunningScriptInNewContextOptions extends RunningScriptOptions { + /** + * Human-readable name of the newly created context. + */ + contextName?: CreateContextOptions["name"]; + /** + * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, + * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + */ + contextOrigin?: CreateContextOptions["origin"]; + contextCodeGeneration?: CreateContextOptions["codeGeneration"]; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: CreateContextOptions["microtaskMode"]; + } + interface RunningCodeOptions extends RunningScriptOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: "afterEvaluate" | undefined; + } + type MeasureMemoryMode = "summary" | "detailed"; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + /** + * @default 'default' + */ + execution?: "default" | "eager" | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions | string); + /** + * Runs the compiled code contained by the `vm.Script` object within the given`contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('vm'); + * + * const context = { + * animal: 'cat', + * count: 2 + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's`cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutX = script.createCachedData(); + * + * script.runInThisContext(); + * + * const cacheWithX = script.createCachedData(); + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + /** + * When the script is compiled from a source that contains a source map magic comment, this property will be set to the URL of the source map. + */ + sourceMapURL?: string | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will `prepare + * that object` so that it can be used in calls to {@link runInContext} or `script.runInContext()`. Inside such scripts, + * the `contextObject` will be the global object, retaining all of its existing + * properties but also having the built-in objects and functions any standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global variables + * will remain unchanged. + * + * ```js + * const vm = require('vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all ` +``` + +This script is browserified and wrapped in a [umd](https://github.com/umdjs/umd) +wrapper so you should be able to use it standalone or together with a module +loader. + +## API + +### `psl.parse(domain)` + +Parse domain based on Public Suffix List. Returns an `Object` with the following +properties: + +* `tld`: Top level domain (this is the _public suffix_). +* `sld`: Second level domain (the first private part of the domain name). +* `domain`: The domain name is the `sld` + `tld`. +* `subdomain`: Optional parts left of the domain. + +#### Example: + +```js +var psl = require('psl'); + +// Parse domain without subdomain +var parsed = psl.parse('google.com'); +console.log(parsed.tld); // 'com' +console.log(parsed.sld); // 'google' +console.log(parsed.domain); // 'google.com' +console.log(parsed.subdomain); // null + +// Parse domain with subdomain +var parsed = psl.parse('www.google.com'); +console.log(parsed.tld); // 'com' +console.log(parsed.sld); // 'google' +console.log(parsed.domain); // 'google.com' +console.log(parsed.subdomain); // 'www' + +// Parse domain with nested subdomains +var parsed = psl.parse('a.b.c.d.foo.com'); +console.log(parsed.tld); // 'com' +console.log(parsed.sld); // 'foo' +console.log(parsed.domain); // 'foo.com' +console.log(parsed.subdomain); // 'a.b.c.d' +``` + +### `psl.get(domain)` + +Get domain name, `sld` + `tld`. Returns `null` if not valid. + +#### Example: + +```js +var psl = require('psl'); + +// null input. +psl.get(null); // null + +// Mixed case. +psl.get('COM'); // null +psl.get('example.COM'); // 'example.com' +psl.get('WwW.example.COM'); // 'example.com' + +// Unlisted TLD. +psl.get('example'); // null +psl.get('example.example'); // 'example.example' +psl.get('b.example.example'); // 'example.example' +psl.get('a.b.example.example'); // 'example.example' + +// TLD with only 1 rule. +psl.get('biz'); // null +psl.get('domain.biz'); // 'domain.biz' +psl.get('b.domain.biz'); // 'domain.biz' +psl.get('a.b.domain.biz'); // 'domain.biz' + +// TLD with some 2-level rules. +psl.get('uk.com'); // null); +psl.get('example.uk.com'); // 'example.uk.com'); +psl.get('b.example.uk.com'); // 'example.uk.com'); + +// More complex TLD. +psl.get('c.kobe.jp'); // null +psl.get('b.c.kobe.jp'); // 'b.c.kobe.jp' +psl.get('a.b.c.kobe.jp'); // 'b.c.kobe.jp' +psl.get('city.kobe.jp'); // 'city.kobe.jp' +psl.get('www.city.kobe.jp'); // 'city.kobe.jp' + +// IDN labels. +psl.get('食狮.com.cn'); // '食狮.com.cn' +psl.get('食狮.公司.cn'); // '食狮.公司.cn' +psl.get('www.食狮.公司.cn'); // '食狮.公司.cn' + +// Same as above, but punycoded. +psl.get('xn--85x722f.com.cn'); // 'xn--85x722f.com.cn' +psl.get('xn--85x722f.xn--55qx5d.cn'); // 'xn--85x722f.xn--55qx5d.cn' +psl.get('www.xn--85x722f.xn--55qx5d.cn'); // 'xn--85x722f.xn--55qx5d.cn' +``` + +### `psl.isValid(domain)` + +Check whether a domain has a valid Public Suffix. Returns a `Boolean` indicating +whether the domain has a valid Public Suffix. + +#### Example + +```js +var psl = require('psl'); + +psl.isValid('google.com'); // true +psl.isValid('www.google.com'); // true +psl.isValid('x.yz'); // false +``` + + +## Testing and Building + +Test are written using [`mocha`](https://mochajs.org/) and can be +run in two different environments: `node` and `phantomjs`. + +```sh +# This will run `eslint`, `mocha` and `karma`. +npm test + +# Individual test environments +# Run tests in node only. +./node_modules/.bin/mocha test +# Run tests in phantomjs only. +./node_modules/.bin/karma start ./karma.conf.js --single-run + +# Build data (parse raw list) and create dist files +npm run build +``` + +Feel free to fork if you see possible improvements! + + +## Acknowledgements + +* Mozilla Foundation's [Public Suffix List](https://publicsuffix.org/) +* Thanks to Rob Stradling of [Comodo](https://www.comodo.com/) for providing + test data. +* Inspired by [weppos/publicsuffix-ruby](https://github.com/weppos/publicsuffix-ruby) + + +## License + +The MIT License (MIT) + +Copyright (c) 2017 Lupo Montero + +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/psl/browserstack-logo.svg b/node_modules/psl/browserstack-logo.svg new file mode 100644 index 0000000..195f64d --- /dev/null +++ b/node_modules/psl/browserstack-logo.svg @@ -0,0 +1,90 @@ + + + + +Browserstack-logo-white + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/node_modules/psl/data/rules.json b/node_modules/psl/data/rules.json new file mode 100644 index 0000000..aaae417 --- /dev/null +++ b/node_modules/psl/data/rules.json @@ -0,0 +1,9376 @@ +[ +"ac", +"com.ac", +"edu.ac", +"gov.ac", +"net.ac", +"mil.ac", +"org.ac", +"ad", +"nom.ad", +"ae", +"co.ae", +"net.ae", +"org.ae", +"sch.ae", +"ac.ae", +"gov.ae", +"mil.ae", +"aero", +"accident-investigation.aero", +"accident-prevention.aero", +"aerobatic.aero", +"aeroclub.aero", +"aerodrome.aero", +"agents.aero", +"aircraft.aero", +"airline.aero", +"airport.aero", +"air-surveillance.aero", +"airtraffic.aero", +"air-traffic-control.aero", +"ambulance.aero", +"amusement.aero", +"association.aero", +"author.aero", +"ballooning.aero", +"broker.aero", +"caa.aero", +"cargo.aero", +"catering.aero", +"certification.aero", +"championship.aero", +"charter.aero", +"civilaviation.aero", +"club.aero", +"conference.aero", +"consultant.aero", +"consulting.aero", +"control.aero", +"council.aero", +"crew.aero", +"design.aero", +"dgca.aero", +"educator.aero", +"emergency.aero", +"engine.aero", +"engineer.aero", +"entertainment.aero", +"equipment.aero", +"exchange.aero", +"express.aero", +"federation.aero", +"flight.aero", +"fuel.aero", +"gliding.aero", +"government.aero", +"groundhandling.aero", +"group.aero", +"hanggliding.aero", +"homebuilt.aero", +"insurance.aero", +"journal.aero", +"journalist.aero", +"leasing.aero", +"logistics.aero", +"magazine.aero", +"maintenance.aero", +"media.aero", +"microlight.aero", +"modelling.aero", +"navigation.aero", +"parachuting.aero", +"paragliding.aero", +"passenger-association.aero", +"pilot.aero", +"press.aero", +"production.aero", +"recreation.aero", +"repbody.aero", +"res.aero", +"research.aero", +"rotorcraft.aero", +"safety.aero", +"scientist.aero", +"services.aero", +"show.aero", +"skydiving.aero", +"software.aero", +"student.aero", +"trader.aero", +"trading.aero", +"trainer.aero", +"union.aero", +"workinggroup.aero", +"works.aero", +"af", +"gov.af", +"com.af", +"org.af", +"net.af", +"edu.af", +"ag", +"com.ag", +"org.ag", +"net.ag", +"co.ag", +"nom.ag", +"ai", +"off.ai", +"com.ai", +"net.ai", +"org.ai", +"al", +"com.al", +"edu.al", +"gov.al", +"mil.al", +"net.al", +"org.al", +"am", +"co.am", +"com.am", +"commune.am", +"net.am", +"org.am", +"ao", +"ed.ao", +"gv.ao", +"og.ao", +"co.ao", +"pb.ao", +"it.ao", +"aq", +"ar", +"bet.ar", +"com.ar", +"coop.ar", +"edu.ar", +"gob.ar", +"gov.ar", +"int.ar", +"mil.ar", +"musica.ar", +"mutual.ar", +"net.ar", +"org.ar", +"senasa.ar", +"tur.ar", +"arpa", +"e164.arpa", +"in-addr.arpa", +"ip6.arpa", +"iris.arpa", +"uri.arpa", +"urn.arpa", +"as", +"gov.as", +"asia", +"at", +"ac.at", +"co.at", +"gv.at", +"or.at", +"sth.ac.at", +"au", +"com.au", +"net.au", +"org.au", +"edu.au", +"gov.au", +"asn.au", +"id.au", +"info.au", +"conf.au", +"oz.au", +"act.au", +"nsw.au", +"nt.au", +"qld.au", +"sa.au", +"tas.au", +"vic.au", +"wa.au", +"act.edu.au", +"catholic.edu.au", +"nsw.edu.au", +"nt.edu.au", +"qld.edu.au", +"sa.edu.au", +"tas.edu.au", +"vic.edu.au", +"wa.edu.au", +"qld.gov.au", +"sa.gov.au", +"tas.gov.au", +"vic.gov.au", +"wa.gov.au", +"schools.nsw.edu.au", +"aw", +"com.aw", +"ax", +"az", +"com.az", +"net.az", +"int.az", +"gov.az", +"org.az", +"edu.az", +"info.az", +"pp.az", +"mil.az", +"name.az", +"pro.az", +"biz.az", +"ba", +"com.ba", +"edu.ba", +"gov.ba", +"mil.ba", +"net.ba", +"org.ba", +"bb", +"biz.bb", +"co.bb", +"com.bb", +"edu.bb", +"gov.bb", +"info.bb", +"net.bb", +"org.bb", +"store.bb", +"tv.bb", +"*.bd", +"be", +"ac.be", +"bf", +"gov.bf", +"bg", +"a.bg", +"b.bg", +"c.bg", +"d.bg", +"e.bg", +"f.bg", +"g.bg", +"h.bg", +"i.bg", +"j.bg", +"k.bg", +"l.bg", +"m.bg", +"n.bg", +"o.bg", +"p.bg", +"q.bg", +"r.bg", +"s.bg", +"t.bg", +"u.bg", +"v.bg", +"w.bg", +"x.bg", +"y.bg", +"z.bg", +"0.bg", +"1.bg", +"2.bg", +"3.bg", +"4.bg", +"5.bg", +"6.bg", +"7.bg", +"8.bg", +"9.bg", +"bh", +"com.bh", +"edu.bh", +"net.bh", +"org.bh", +"gov.bh", +"bi", +"co.bi", +"com.bi", +"edu.bi", +"or.bi", +"org.bi", +"biz", +"bj", +"asso.bj", +"barreau.bj", +"gouv.bj", +"bm", +"com.bm", +"edu.bm", +"gov.bm", +"net.bm", +"org.bm", +"bn", +"com.bn", +"edu.bn", +"gov.bn", +"net.bn", +"org.bn", +"bo", +"com.bo", +"edu.bo", +"gob.bo", +"int.bo", +"org.bo", +"net.bo", +"mil.bo", +"tv.bo", +"web.bo", +"academia.bo", +"agro.bo", +"arte.bo", +"blog.bo", +"bolivia.bo", +"ciencia.bo", +"cooperativa.bo", +"democracia.bo", +"deporte.bo", +"ecologia.bo", +"economia.bo", +"empresa.bo", +"indigena.bo", +"industria.bo", +"info.bo", +"medicina.bo", +"movimiento.bo", +"musica.bo", +"natural.bo", +"nombre.bo", +"noticias.bo", +"patria.bo", +"politica.bo", +"profesional.bo", +"plurinacional.bo", +"pueblo.bo", +"revista.bo", +"salud.bo", +"tecnologia.bo", +"tksat.bo", +"transporte.bo", +"wiki.bo", +"br", +"9guacu.br", +"abc.br", +"adm.br", +"adv.br", +"agr.br", +"aju.br", +"am.br", +"anani.br", +"aparecida.br", +"app.br", +"arq.br", +"art.br", +"ato.br", +"b.br", +"barueri.br", +"belem.br", +"bhz.br", +"bib.br", +"bio.br", +"blog.br", +"bmd.br", +"boavista.br", +"bsb.br", +"campinagrande.br", +"campinas.br", +"caxias.br", +"cim.br", +"cng.br", +"cnt.br", +"com.br", +"contagem.br", +"coop.br", +"coz.br", +"cri.br", +"cuiaba.br", +"curitiba.br", +"def.br", +"des.br", +"det.br", +"dev.br", +"ecn.br", +"eco.br", +"edu.br", +"emp.br", +"enf.br", +"eng.br", +"esp.br", +"etc.br", +"eti.br", +"far.br", +"feira.br", +"flog.br", +"floripa.br", +"fm.br", +"fnd.br", +"fortal.br", +"fot.br", +"foz.br", +"fst.br", +"g12.br", +"geo.br", +"ggf.br", +"goiania.br", +"gov.br", +"ac.gov.br", +"al.gov.br", +"am.gov.br", +"ap.gov.br", +"ba.gov.br", +"ce.gov.br", +"df.gov.br", +"es.gov.br", +"go.gov.br", +"ma.gov.br", +"mg.gov.br", +"ms.gov.br", +"mt.gov.br", +"pa.gov.br", +"pb.gov.br", +"pe.gov.br", +"pi.gov.br", +"pr.gov.br", +"rj.gov.br", +"rn.gov.br", +"ro.gov.br", +"rr.gov.br", +"rs.gov.br", +"sc.gov.br", +"se.gov.br", +"sp.gov.br", +"to.gov.br", +"gru.br", +"imb.br", +"ind.br", +"inf.br", +"jab.br", +"jampa.br", +"jdf.br", +"joinville.br", +"jor.br", +"jus.br", +"leg.br", +"lel.br", +"log.br", +"londrina.br", +"macapa.br", +"maceio.br", +"manaus.br", +"maringa.br", +"mat.br", +"med.br", +"mil.br", +"morena.br", +"mp.br", +"mus.br", +"natal.br", +"net.br", +"niteroi.br", +"*.nom.br", +"not.br", +"ntr.br", +"odo.br", +"ong.br", +"org.br", +"osasco.br", +"palmas.br", +"poa.br", +"ppg.br", +"pro.br", +"psc.br", +"psi.br", +"pvh.br", +"qsl.br", +"radio.br", +"rec.br", +"recife.br", +"rep.br", +"ribeirao.br", +"rio.br", +"riobranco.br", +"riopreto.br", +"salvador.br", +"sampa.br", +"santamaria.br", +"santoandre.br", +"saobernardo.br", +"saogonca.br", +"seg.br", +"sjc.br", +"slg.br", +"slz.br", +"sorocaba.br", +"srv.br", +"taxi.br", +"tc.br", +"tec.br", +"teo.br", +"the.br", +"tmp.br", +"trd.br", +"tur.br", +"tv.br", +"udi.br", +"vet.br", +"vix.br", +"vlog.br", +"wiki.br", +"zlg.br", +"bs", +"com.bs", +"net.bs", +"org.bs", +"edu.bs", +"gov.bs", +"bt", +"com.bt", +"edu.bt", +"gov.bt", +"net.bt", +"org.bt", +"bv", +"bw", +"co.bw", +"org.bw", +"by", +"gov.by", +"mil.by", +"com.by", +"of.by", +"bz", +"com.bz", +"net.bz", +"org.bz", +"edu.bz", +"gov.bz", +"ca", +"ab.ca", +"bc.ca", +"mb.ca", +"nb.ca", +"nf.ca", +"nl.ca", +"ns.ca", +"nt.ca", +"nu.ca", +"on.ca", +"pe.ca", +"qc.ca", +"sk.ca", +"yk.ca", +"gc.ca", +"cat", +"cc", +"cd", +"gov.cd", +"cf", +"cg", +"ch", +"ci", +"org.ci", +"or.ci", +"com.ci", +"co.ci", +"edu.ci", +"ed.ci", +"ac.ci", +"net.ci", +"go.ci", +"asso.ci", +"aéroport.ci", +"int.ci", +"presse.ci", +"md.ci", +"gouv.ci", +"*.ck", +"!www.ck", +"cl", +"co.cl", +"gob.cl", +"gov.cl", +"mil.cl", +"cm", +"co.cm", +"com.cm", +"gov.cm", +"net.cm", +"cn", +"ac.cn", +"com.cn", +"edu.cn", +"gov.cn", +"net.cn", +"org.cn", +"mil.cn", +"公司.cn", +"网络.cn", +"網絡.cn", +"ah.cn", +"bj.cn", +"cq.cn", +"fj.cn", +"gd.cn", +"gs.cn", +"gz.cn", +"gx.cn", +"ha.cn", +"hb.cn", +"he.cn", +"hi.cn", +"hl.cn", +"hn.cn", +"jl.cn", +"js.cn", +"jx.cn", +"ln.cn", +"nm.cn", +"nx.cn", +"qh.cn", +"sc.cn", +"sd.cn", +"sh.cn", +"sn.cn", +"sx.cn", +"tj.cn", +"xj.cn", +"xz.cn", +"yn.cn", +"zj.cn", +"hk.cn", +"mo.cn", +"tw.cn", +"co", +"arts.co", +"com.co", +"edu.co", +"firm.co", +"gov.co", +"info.co", +"int.co", +"mil.co", +"net.co", +"nom.co", +"org.co", +"rec.co", +"web.co", +"com", +"coop", +"cr", +"ac.cr", +"co.cr", +"ed.cr", +"fi.cr", +"go.cr", +"or.cr", +"sa.cr", +"cu", +"com.cu", +"edu.cu", +"org.cu", +"net.cu", +"gov.cu", +"inf.cu", +"cv", +"com.cv", +"edu.cv", +"int.cv", +"nome.cv", +"org.cv", +"cw", +"com.cw", +"edu.cw", +"net.cw", +"org.cw", +"cx", +"gov.cx", +"cy", +"ac.cy", +"biz.cy", +"com.cy", +"ekloges.cy", +"gov.cy", +"ltd.cy", +"mil.cy", +"net.cy", +"org.cy", +"press.cy", +"pro.cy", +"tm.cy", +"cz", +"de", +"dj", +"dk", +"dm", +"com.dm", +"net.dm", +"org.dm", +"edu.dm", +"gov.dm", +"do", +"art.do", +"com.do", +"edu.do", +"gob.do", +"gov.do", +"mil.do", +"net.do", +"org.do", +"sld.do", +"web.do", +"dz", +"art.dz", +"asso.dz", +"com.dz", +"edu.dz", +"gov.dz", +"org.dz", +"net.dz", +"pol.dz", +"soc.dz", +"tm.dz", +"ec", +"com.ec", +"info.ec", +"net.ec", +"fin.ec", +"k12.ec", +"med.ec", +"pro.ec", +"org.ec", +"edu.ec", +"gov.ec", +"gob.ec", +"mil.ec", +"edu", +"ee", +"edu.ee", +"gov.ee", +"riik.ee", +"lib.ee", +"med.ee", +"com.ee", +"pri.ee", +"aip.ee", +"org.ee", +"fie.ee", +"eg", +"com.eg", +"edu.eg", +"eun.eg", +"gov.eg", +"mil.eg", +"name.eg", +"net.eg", +"org.eg", +"sci.eg", +"*.er", +"es", +"com.es", +"nom.es", +"org.es", +"gob.es", +"edu.es", +"et", +"com.et", +"gov.et", +"org.et", +"edu.et", +"biz.et", +"name.et", +"info.et", +"net.et", +"eu", +"fi", +"aland.fi", +"fj", +"ac.fj", +"biz.fj", +"com.fj", +"gov.fj", +"info.fj", +"mil.fj", +"name.fj", +"net.fj", +"org.fj", +"pro.fj", +"*.fk", +"com.fm", +"edu.fm", +"net.fm", +"org.fm", +"fm", +"fo", +"fr", +"asso.fr", +"com.fr", +"gouv.fr", +"nom.fr", +"prd.fr", +"tm.fr", +"aeroport.fr", +"avocat.fr", +"avoues.fr", +"cci.fr", +"chambagri.fr", +"chirurgiens-dentistes.fr", +"experts-comptables.fr", +"geometre-expert.fr", +"greta.fr", +"huissier-justice.fr", +"medecin.fr", +"notaires.fr", +"pharmacien.fr", +"port.fr", +"veterinaire.fr", +"ga", +"gb", +"edu.gd", +"gov.gd", +"gd", +"ge", +"com.ge", +"edu.ge", +"gov.ge", +"org.ge", +"mil.ge", +"net.ge", +"pvt.ge", +"gf", +"gg", +"co.gg", +"net.gg", +"org.gg", +"gh", +"com.gh", +"edu.gh", +"gov.gh", +"org.gh", +"mil.gh", +"gi", +"com.gi", +"ltd.gi", +"gov.gi", +"mod.gi", +"edu.gi", +"org.gi", +"gl", +"co.gl", +"com.gl", +"edu.gl", +"net.gl", +"org.gl", +"gm", +"gn", +"ac.gn", +"com.gn", +"edu.gn", +"gov.gn", +"org.gn", +"net.gn", +"gov", +"gp", +"com.gp", +"net.gp", +"mobi.gp", +"edu.gp", +"org.gp", +"asso.gp", +"gq", +"gr", +"com.gr", +"edu.gr", +"net.gr", +"org.gr", +"gov.gr", +"gs", +"gt", +"com.gt", +"edu.gt", +"gob.gt", +"ind.gt", +"mil.gt", +"net.gt", +"org.gt", +"gu", +"com.gu", +"edu.gu", +"gov.gu", +"guam.gu", +"info.gu", +"net.gu", +"org.gu", +"web.gu", +"gw", +"gy", +"co.gy", +"com.gy", +"edu.gy", +"gov.gy", +"net.gy", +"org.gy", +"hk", +"com.hk", +"edu.hk", +"gov.hk", +"idv.hk", +"net.hk", +"org.hk", +"公司.hk", +"教育.hk", +"敎育.hk", +"政府.hk", +"個人.hk", +"个��.hk", +"箇人.hk", +"網络.hk", +"网络.hk", +"组織.hk", +"網絡.hk", +"网絡.hk", +"组织.hk", +"組織.hk", +"組织.hk", +"hm", +"hn", +"com.hn", +"edu.hn", +"org.hn", +"net.hn", +"mil.hn", +"gob.hn", +"hr", +"iz.hr", +"from.hr", +"name.hr", +"com.hr", +"ht", +"com.ht", +"shop.ht", +"firm.ht", +"info.ht", +"adult.ht", +"net.ht", +"pro.ht", +"org.ht", +"med.ht", +"art.ht", +"coop.ht", +"pol.ht", +"asso.ht", +"edu.ht", +"rel.ht", +"gouv.ht", +"perso.ht", +"hu", +"co.hu", +"info.hu", +"org.hu", +"priv.hu", +"sport.hu", +"tm.hu", +"2000.hu", +"agrar.hu", +"bolt.hu", +"casino.hu", +"city.hu", +"erotica.hu", +"erotika.hu", +"film.hu", +"forum.hu", +"games.hu", +"hotel.hu", +"ingatlan.hu", +"jogasz.hu", +"konyvelo.hu", +"lakas.hu", +"media.hu", +"news.hu", +"reklam.hu", +"sex.hu", +"shop.hu", +"suli.hu", +"szex.hu", +"tozsde.hu", +"utazas.hu", +"video.hu", +"id", +"ac.id", +"biz.id", +"co.id", +"desa.id", +"go.id", +"mil.id", +"my.id", +"net.id", +"or.id", +"ponpes.id", +"sch.id", +"web.id", +"ie", +"gov.ie", +"il", +"ac.il", +"co.il", +"gov.il", +"idf.il", +"k12.il", +"muni.il", +"net.il", +"org.il", +"im", +"ac.im", +"co.im", +"com.im", +"ltd.co.im", +"net.im", +"org.im", +"plc.co.im", +"tt.im", +"tv.im", +"in", +"co.in", +"firm.in", +"net.in", +"org.in", +"gen.in", +"ind.in", +"nic.in", +"ac.in", +"edu.in", +"res.in", +"gov.in", +"mil.in", +"info", +"int", +"eu.int", +"io", +"com.io", +"iq", +"gov.iq", +"edu.iq", +"mil.iq", +"com.iq", +"org.iq", +"net.iq", +"ir", +"ac.ir", +"co.ir", +"gov.ir", +"id.ir", +"net.ir", +"org.ir", +"sch.ir", +"ایران.ir", +"ايران.ir", +"is", +"net.is", +"com.is", +"edu.is", +"gov.is", +"org.is", +"int.is", +"it", +"gov.it", +"edu.it", +"abr.it", +"abruzzo.it", +"aosta-valley.it", +"aostavalley.it", +"bas.it", +"basilicata.it", +"cal.it", +"calabria.it", +"cam.it", +"campania.it", +"emilia-romagna.it", +"emiliaromagna.it", +"emr.it", +"friuli-v-giulia.it", +"friuli-ve-giulia.it", +"friuli-vegiulia.it", +"friuli-venezia-giulia.it", +"friuli-veneziagiulia.it", +"friuli-vgiulia.it", +"friuliv-giulia.it", +"friulive-giulia.it", +"friulivegiulia.it", +"friulivenezia-giulia.it", +"friuliveneziagiulia.it", +"friulivgiulia.it", +"fvg.it", +"laz.it", +"lazio.it", +"lig.it", +"liguria.it", +"lom.it", +"lombardia.it", +"lombardy.it", +"lucania.it", +"mar.it", +"marche.it", +"mol.it", +"molise.it", +"piedmont.it", +"piemonte.it", +"pmn.it", +"pug.it", +"puglia.it", +"sar.it", +"sardegna.it", +"sardinia.it", +"sic.it", +"sicilia.it", +"sicily.it", +"taa.it", +"tos.it", +"toscana.it", +"trentin-sud-tirol.it", +"trentin-süd-tirol.it", +"trentin-sudtirol.it", +"trentin-südtirol.it", +"trentin-sued-tirol.it", +"trentin-suedtirol.it", +"trentino-a-adige.it", +"trentino-aadige.it", +"trentino-alto-adige.it", +"trentino-altoadige.it", +"trentino-s-tirol.it", +"trentino-stirol.it", +"trentino-sud-tirol.it", +"trentino-süd-tirol.it", +"trentino-sudtirol.it", +"trentino-südtirol.it", +"trentino-sued-tirol.it", +"trentino-suedtirol.it", +"trentino.it", +"trentinoa-adige.it", +"trentinoaadige.it", +"trentinoalto-adige.it", +"trentinoaltoadige.it", +"trentinos-tirol.it", +"trentinostirol.it", +"trentinosud-tirol.it", +"trentinosüd-tirol.it", +"trentinosudtirol.it", +"trentinosüdtirol.it", +"trentinosued-tirol.it", +"trentinosuedtirol.it", +"trentinsud-tirol.it", +"trentinsüd-tirol.it", +"trentinsudtirol.it", +"trentinsüdtirol.it", +"trentinsued-tirol.it", +"trentinsuedtirol.it", +"tuscany.it", +"umb.it", +"umbria.it", +"val-d-aosta.it", +"val-daosta.it", +"vald-aosta.it", +"valdaosta.it", +"valle-aosta.it", +"valle-d-aosta.it", +"valle-daosta.it", +"valleaosta.it", +"valled-aosta.it", +"valledaosta.it", +"vallee-aoste.it", +"vallée-aoste.it", +"vallee-d-aoste.it", +"vallée-d-aoste.it", +"valleeaoste.it", +"valléeaoste.it", +"valleedaoste.it", +"valléedaoste.it", +"vao.it", +"vda.it", +"ven.it", +"veneto.it", +"ag.it", +"agrigento.it", +"al.it", +"alessandria.it", +"alto-adige.it", +"altoadige.it", +"an.it", +"ancona.it", +"andria-barletta-trani.it", +"andria-trani-barletta.it", +"andriabarlettatrani.it", +"andriatranibarletta.it", +"ao.it", +"aosta.it", +"aoste.it", +"ap.it", +"aq.it", +"aquila.it", +"ar.it", +"arezzo.it", +"ascoli-piceno.it", +"ascolipiceno.it", +"asti.it", +"at.it", +"av.it", +"avellino.it", +"ba.it", +"balsan-sudtirol.it", +"balsan-südtirol.it", +"balsan-suedtirol.it", +"balsan.it", +"bari.it", +"barletta-trani-andria.it", +"barlettatraniandria.it", +"belluno.it", +"benevento.it", +"bergamo.it", +"bg.it", +"bi.it", +"biella.it", +"bl.it", +"bn.it", +"bo.it", +"bologna.it", +"bolzano-altoadige.it", +"bolzano.it", +"bozen-sudtirol.it", +"bozen-südtirol.it", +"bozen-suedtirol.it", +"bozen.it", +"br.it", +"brescia.it", +"brindisi.it", +"bs.it", +"bt.it", +"bulsan-sudtirol.it", +"bulsan-südtirol.it", +"bulsan-suedtirol.it", +"bulsan.it", +"bz.it", +"ca.it", +"cagliari.it", +"caltanissetta.it", +"campidano-medio.it", +"campidanomedio.it", +"campobasso.it", +"carbonia-iglesias.it", +"carboniaiglesias.it", +"carrara-massa.it", +"carraramassa.it", +"caserta.it", +"catania.it", +"catanzaro.it", +"cb.it", +"ce.it", +"cesena-forli.it", +"cesena-forlì.it", +"cesenaforli.it", +"cesenaforlì.it", +"ch.it", +"chieti.it", +"ci.it", +"cl.it", +"cn.it", +"co.it", +"como.it", +"cosenza.it", +"cr.it", +"cremona.it", +"crotone.it", +"cs.it", +"ct.it", +"cuneo.it", +"cz.it", +"dell-ogliastra.it", +"dellogliastra.it", +"en.it", +"enna.it", +"fc.it", +"fe.it", +"fermo.it", +"ferrara.it", +"fg.it", +"fi.it", +"firenze.it", +"florence.it", +"fm.it", +"foggia.it", +"forli-cesena.it", +"forlì-cesena.it", +"forlicesena.it", +"forlìcesena.it", +"fr.it", +"frosinone.it", +"ge.it", +"genoa.it", +"genova.it", +"go.it", +"gorizia.it", +"gr.it", +"grosseto.it", +"iglesias-carbonia.it", +"iglesiascarbonia.it", +"im.it", +"imperia.it", +"is.it", +"isernia.it", +"kr.it", +"la-spezia.it", +"laquila.it", +"laspezia.it", +"latina.it", +"lc.it", +"le.it", +"lecce.it", +"lecco.it", +"li.it", +"livorno.it", +"lo.it", +"lodi.it", +"lt.it", +"lu.it", +"lucca.it", +"macerata.it", +"mantova.it", +"massa-carrara.it", +"massacarrara.it", +"matera.it", +"mb.it", +"mc.it", +"me.it", +"medio-campidano.it", +"mediocampidano.it", +"messina.it", +"mi.it", +"milan.it", +"milano.it", +"mn.it", +"mo.it", +"modena.it", +"monza-brianza.it", +"monza-e-della-brianza.it", +"monza.it", +"monzabrianza.it", +"monzaebrianza.it", +"monzaedellabrianza.it", +"ms.it", +"mt.it", +"na.it", +"naples.it", +"napoli.it", +"no.it", +"novara.it", +"nu.it", +"nuoro.it", +"og.it", +"ogliastra.it", +"olbia-tempio.it", +"olbiatempio.it", +"or.it", +"oristano.it", +"ot.it", +"pa.it", +"padova.it", +"padua.it", +"palermo.it", +"parma.it", +"pavia.it", +"pc.it", +"pd.it", +"pe.it", +"perugia.it", +"pesaro-urbino.it", +"pesarourbino.it", +"pescara.it", +"pg.it", +"pi.it", +"piacenza.it", +"pisa.it", +"pistoia.it", +"pn.it", +"po.it", +"pordenone.it", +"potenza.it", +"pr.it", +"prato.it", +"pt.it", +"pu.it", +"pv.it", +"pz.it", +"ra.it", +"ragusa.it", +"ravenna.it", +"rc.it", +"re.it", +"reggio-calabria.it", +"reggio-emilia.it", +"reggiocalabria.it", +"reggioemilia.it", +"rg.it", +"ri.it", +"rieti.it", +"rimini.it", +"rm.it", +"rn.it", +"ro.it", +"roma.it", +"rome.it", +"rovigo.it", +"sa.it", +"salerno.it", +"sassari.it", +"savona.it", +"si.it", +"siena.it", +"siracusa.it", +"so.it", +"sondrio.it", +"sp.it", +"sr.it", +"ss.it", +"suedtirol.it", +"südtirol.it", +"sv.it", +"ta.it", +"taranto.it", +"te.it", +"tempio-olbia.it", +"tempioolbia.it", +"teramo.it", +"terni.it", +"tn.it", +"to.it", +"torino.it", +"tp.it", +"tr.it", +"trani-andria-barletta.it", +"trani-barletta-andria.it", +"traniandriabarletta.it", +"tranibarlettaandria.it", +"trapani.it", +"trento.it", +"treviso.it", +"trieste.it", +"ts.it", +"turin.it", +"tv.it", +"ud.it", +"udine.it", +"urbino-pesaro.it", +"urbinopesaro.it", +"va.it", +"varese.it", +"vb.it", +"vc.it", +"ve.it", +"venezia.it", +"venice.it", +"verbania.it", +"vercelli.it", +"verona.it", +"vi.it", +"vibo-valentia.it", +"vibovalentia.it", +"vicenza.it", +"viterbo.it", +"vr.it", +"vs.it", +"vt.it", +"vv.it", +"je", +"co.je", +"net.je", +"org.je", +"*.jm", +"jo", +"com.jo", +"org.jo", +"net.jo", +"edu.jo", +"sch.jo", +"gov.jo", +"mil.jo", +"name.jo", +"jobs", +"jp", +"ac.jp", +"ad.jp", +"co.jp", +"ed.jp", +"go.jp", +"gr.jp", +"lg.jp", +"ne.jp", +"or.jp", +"aichi.jp", +"akita.jp", +"aomori.jp", +"chiba.jp", +"ehime.jp", +"fukui.jp", +"fukuoka.jp", +"fukushima.jp", +"gifu.jp", +"gunma.jp", +"hiroshima.jp", +"hokkaido.jp", +"hyogo.jp", +"ibaraki.jp", +"ishikawa.jp", +"iwate.jp", +"kagawa.jp", +"kagoshima.jp", +"kanagawa.jp", +"kochi.jp", +"kumamoto.jp", +"kyoto.jp", +"mie.jp", +"miyagi.jp", +"miyazaki.jp", +"nagano.jp", +"nagasaki.jp", +"nara.jp", +"niigata.jp", +"oita.jp", +"okayama.jp", +"okinawa.jp", +"osaka.jp", +"saga.jp", +"saitama.jp", +"shiga.jp", +"shimane.jp", +"shizuoka.jp", +"tochigi.jp", +"tokushima.jp", +"tokyo.jp", +"tottori.jp", +"toyama.jp", +"wakayama.jp", +"yamagata.jp", +"yamaguchi.jp", +"yamanashi.jp", +"栃木.jp", +"愛知.jp", +"愛媛.jp", +"兵庫.jp", +"熊本.jp", +"茨城.jp", +"北海道.jp", +"千葉.jp", +"和歌山.jp", +"長崎.jp", +"長野.jp", +"新潟.jp", +"青森.jp", +"静岡.jp", +"東京.jp", +"石川.jp", +"埼玉.jp", +"三重.jp", +"京都.jp", +"佐賀.jp", +"大分.jp", +"大阪.jp", +"奈良.jp", +"宮城.jp", +"宮崎.jp", +"富山.jp", +"山口.jp", +"山形.jp", +"山梨.jp", +"岩手.jp", +"岐阜.jp", +"岡山.jp", +"島根.jp", +"広島.jp", +"徳島.jp", +"沖縄.jp", +"滋賀.jp", +"神奈川.jp", +"福井.jp", +"福岡.jp", +"福島.jp", +"秋田.jp", +"群馬.jp", +"香川.jp", +"高知.jp", +"鳥取.jp", +"鹿児島.jp", +"*.kawasaki.jp", +"*.kitakyushu.jp", +"*.kobe.jp", +"*.nagoya.jp", +"*.sapporo.jp", +"*.sendai.jp", +"*.yokohama.jp", +"!city.kawasaki.jp", +"!city.kitakyushu.jp", +"!city.kobe.jp", +"!city.nagoya.jp", +"!city.sapporo.jp", +"!city.sendai.jp", +"!city.yokohama.jp", +"aisai.aichi.jp", +"ama.aichi.jp", +"anjo.aichi.jp", +"asuke.aichi.jp", +"chiryu.aichi.jp", +"chita.aichi.jp", +"fuso.aichi.jp", +"gamagori.aichi.jp", +"handa.aichi.jp", +"hazu.aichi.jp", +"hekinan.aichi.jp", +"higashiura.aichi.jp", +"ichinomiya.aichi.jp", +"inazawa.aichi.jp", +"inuyama.aichi.jp", +"isshiki.aichi.jp", +"iwakura.aichi.jp", +"kanie.aichi.jp", +"kariya.aichi.jp", +"kasugai.aichi.jp", +"kira.aichi.jp", +"kiyosu.aichi.jp", +"komaki.aichi.jp", +"konan.aichi.jp", +"kota.aichi.jp", +"mihama.aichi.jp", +"miyoshi.aichi.jp", +"nishio.aichi.jp", +"nisshin.aichi.jp", +"obu.aichi.jp", +"oguchi.aichi.jp", +"oharu.aichi.jp", +"okazaki.aichi.jp", +"owariasahi.aichi.jp", +"seto.aichi.jp", +"shikatsu.aichi.jp", +"shinshiro.aichi.jp", +"shitara.aichi.jp", +"tahara.aichi.jp", +"takahama.aichi.jp", +"tobishima.aichi.jp", +"toei.aichi.jp", +"togo.aichi.jp", +"tokai.aichi.jp", +"tokoname.aichi.jp", +"toyoake.aichi.jp", +"toyohashi.aichi.jp", +"toyokawa.aichi.jp", +"toyone.aichi.jp", +"toyota.aichi.jp", +"tsushima.aichi.jp", +"yatomi.aichi.jp", +"akita.akita.jp", +"daisen.akita.jp", +"fujisato.akita.jp", +"gojome.akita.jp", +"hachirogata.akita.jp", +"happou.akita.jp", +"higashinaruse.akita.jp", +"honjo.akita.jp", +"honjyo.akita.jp", +"ikawa.akita.jp", +"kamikoani.akita.jp", +"kamioka.akita.jp", +"katagami.akita.jp", +"kazuno.akita.jp", +"kitaakita.akita.jp", +"kosaka.akita.jp", +"kyowa.akita.jp", +"misato.akita.jp", +"mitane.akita.jp", +"moriyoshi.akita.jp", +"nikaho.akita.jp", +"noshiro.akita.jp", +"odate.akita.jp", +"oga.akita.jp", +"ogata.akita.jp", +"semboku.akita.jp", +"yokote.akita.jp", +"yurihonjo.akita.jp", +"aomori.aomori.jp", +"gonohe.aomori.jp", +"hachinohe.aomori.jp", +"hashikami.aomori.jp", +"hiranai.aomori.jp", +"hirosaki.aomori.jp", +"itayanagi.aomori.jp", +"kuroishi.aomori.jp", +"misawa.aomori.jp", +"mutsu.aomori.jp", +"nakadomari.aomori.jp", +"noheji.aomori.jp", +"oirase.aomori.jp", +"owani.aomori.jp", +"rokunohe.aomori.jp", +"sannohe.aomori.jp", +"shichinohe.aomori.jp", +"shingo.aomori.jp", +"takko.aomori.jp", +"towada.aomori.jp", +"tsugaru.aomori.jp", +"tsuruta.aomori.jp", +"abiko.chiba.jp", +"asahi.chiba.jp", +"chonan.chiba.jp", +"chosei.chiba.jp", +"choshi.chiba.jp", +"chuo.chiba.jp", +"funabashi.chiba.jp", +"futtsu.chiba.jp", +"hanamigawa.chiba.jp", +"ichihara.chiba.jp", +"ichikawa.chiba.jp", +"ichinomiya.chiba.jp", +"inzai.chiba.jp", +"isumi.chiba.jp", +"kamagaya.chiba.jp", +"kamogawa.chiba.jp", +"kashiwa.chiba.jp", +"katori.chiba.jp", +"katsuura.chiba.jp", +"kimitsu.chiba.jp", +"kisarazu.chiba.jp", +"kozaki.chiba.jp", +"kujukuri.chiba.jp", +"kyonan.chiba.jp", +"matsudo.chiba.jp", +"midori.chiba.jp", +"mihama.chiba.jp", +"minamiboso.chiba.jp", +"mobara.chiba.jp", +"mutsuzawa.chiba.jp", +"nagara.chiba.jp", +"nagareyama.chiba.jp", +"narashino.chiba.jp", +"narita.chiba.jp", +"noda.chiba.jp", +"oamishirasato.chiba.jp", +"omigawa.chiba.jp", +"onjuku.chiba.jp", +"otaki.chiba.jp", +"sakae.chiba.jp", +"sakura.chiba.jp", +"shimofusa.chiba.jp", +"shirako.chiba.jp", +"shiroi.chiba.jp", +"shisui.chiba.jp", +"sodegaura.chiba.jp", +"sosa.chiba.jp", +"tako.chiba.jp", +"tateyama.chiba.jp", +"togane.chiba.jp", +"tohnosho.chiba.jp", +"tomisato.chiba.jp", +"urayasu.chiba.jp", +"yachimata.chiba.jp", +"yachiyo.chiba.jp", +"yokaichiba.chiba.jp", +"yokoshibahikari.chiba.jp", +"yotsukaido.chiba.jp", +"ainan.ehime.jp", +"honai.ehime.jp", +"ikata.ehime.jp", +"imabari.ehime.jp", +"iyo.ehime.jp", +"kamijima.ehime.jp", +"kihoku.ehime.jp", +"kumakogen.ehime.jp", +"masaki.ehime.jp", +"matsuno.ehime.jp", +"matsuyama.ehime.jp", +"namikata.ehime.jp", +"niihama.ehime.jp", +"ozu.ehime.jp", +"saijo.ehime.jp", +"seiyo.ehime.jp", +"shikokuchuo.ehime.jp", +"tobe.ehime.jp", +"toon.ehime.jp", +"uchiko.ehime.jp", +"uwajima.ehime.jp", +"yawatahama.ehime.jp", +"echizen.fukui.jp", +"eiheiji.fukui.jp", +"fukui.fukui.jp", +"ikeda.fukui.jp", +"katsuyama.fukui.jp", +"mihama.fukui.jp", +"minamiechizen.fukui.jp", +"obama.fukui.jp", +"ohi.fukui.jp", +"ono.fukui.jp", +"sabae.fukui.jp", +"sakai.fukui.jp", +"takahama.fukui.jp", +"tsuruga.fukui.jp", +"wakasa.fukui.jp", +"ashiya.fukuoka.jp", +"buzen.fukuoka.jp", +"chikugo.fukuoka.jp", +"chikuho.fukuoka.jp", +"chikujo.fukuoka.jp", +"chikushino.fukuoka.jp", +"chikuzen.fukuoka.jp", +"chuo.fukuoka.jp", +"dazaifu.fukuoka.jp", +"fukuchi.fukuoka.jp", +"hakata.fukuoka.jp", +"higashi.fukuoka.jp", +"hirokawa.fukuoka.jp", +"hisayama.fukuoka.jp", +"iizuka.fukuoka.jp", +"inatsuki.fukuoka.jp", +"kaho.fukuoka.jp", +"kasuga.fukuoka.jp", +"kasuya.fukuoka.jp", +"kawara.fukuoka.jp", +"keisen.fukuoka.jp", +"koga.fukuoka.jp", +"kurate.fukuoka.jp", +"kurogi.fukuoka.jp", +"kurume.fukuoka.jp", +"minami.fukuoka.jp", +"miyako.fukuoka.jp", +"miyama.fukuoka.jp", +"miyawaka.fukuoka.jp", +"mizumaki.fukuoka.jp", +"munakata.fukuoka.jp", +"nakagawa.fukuoka.jp", +"nakama.fukuoka.jp", +"nishi.fukuoka.jp", +"nogata.fukuoka.jp", +"ogori.fukuoka.jp", +"okagaki.fukuoka.jp", +"okawa.fukuoka.jp", +"oki.fukuoka.jp", +"omuta.fukuoka.jp", +"onga.fukuoka.jp", +"onojo.fukuoka.jp", +"oto.fukuoka.jp", +"saigawa.fukuoka.jp", +"sasaguri.fukuoka.jp", +"shingu.fukuoka.jp", +"shinyoshitomi.fukuoka.jp", +"shonai.fukuoka.jp", +"soeda.fukuoka.jp", +"sue.fukuoka.jp", +"tachiarai.fukuoka.jp", +"tagawa.fukuoka.jp", +"takata.fukuoka.jp", +"toho.fukuoka.jp", +"toyotsu.fukuoka.jp", +"tsuiki.fukuoka.jp", +"ukiha.fukuoka.jp", +"umi.fukuoka.jp", +"usui.fukuoka.jp", +"yamada.fukuoka.jp", +"yame.fukuoka.jp", +"yanagawa.fukuoka.jp", +"yukuhashi.fukuoka.jp", +"aizubange.fukushima.jp", +"aizumisato.fukushima.jp", +"aizuwakamatsu.fukushima.jp", +"asakawa.fukushima.jp", +"bandai.fukushima.jp", +"date.fukushima.jp", +"fukushima.fukushima.jp", +"furudono.fukushima.jp", +"futaba.fukushima.jp", +"hanawa.fukushima.jp", +"higashi.fukushima.jp", +"hirata.fukushima.jp", +"hirono.fukushima.jp", +"iitate.fukushima.jp", +"inawashiro.fukushima.jp", +"ishikawa.fukushima.jp", +"iwaki.fukushima.jp", +"izumizaki.fukushima.jp", +"kagamiishi.fukushima.jp", +"kaneyama.fukushima.jp", +"kawamata.fukushima.jp", +"kitakata.fukushima.jp", +"kitashiobara.fukushima.jp", +"koori.fukushima.jp", +"koriyama.fukushima.jp", +"kunimi.fukushima.jp", +"miharu.fukushima.jp", +"mishima.fukushima.jp", +"namie.fukushima.jp", +"nango.fukushima.jp", +"nishiaizu.fukushima.jp", +"nishigo.fukushima.jp", +"okuma.fukushima.jp", +"omotego.fukushima.jp", +"ono.fukushima.jp", +"otama.fukushima.jp", +"samegawa.fukushima.jp", +"shimogo.fukushima.jp", +"shirakawa.fukushima.jp", +"showa.fukushima.jp", +"soma.fukushima.jp", +"sukagawa.fukushima.jp", +"taishin.fukushima.jp", +"tamakawa.fukushima.jp", +"tanagura.fukushima.jp", +"tenei.fukushima.jp", +"yabuki.fukushima.jp", +"yamato.fukushima.jp", +"yamatsuri.fukushima.jp", +"yanaizu.fukushima.jp", +"yugawa.fukushima.jp", +"anpachi.gifu.jp", +"ena.gifu.jp", +"gifu.gifu.jp", +"ginan.gifu.jp", +"godo.gifu.jp", +"gujo.gifu.jp", +"hashima.gifu.jp", +"hichiso.gifu.jp", +"hida.gifu.jp", +"higashishirakawa.gifu.jp", +"ibigawa.gifu.jp", +"ikeda.gifu.jp", +"kakamigahara.gifu.jp", +"kani.gifu.jp", +"kasahara.gifu.jp", +"kasamatsu.gifu.jp", +"kawaue.gifu.jp", +"kitagata.gifu.jp", +"mino.gifu.jp", +"minokamo.gifu.jp", +"mitake.gifu.jp", +"mizunami.gifu.jp", +"motosu.gifu.jp", +"nakatsugawa.gifu.jp", +"ogaki.gifu.jp", +"sakahogi.gifu.jp", +"seki.gifu.jp", +"sekigahara.gifu.jp", +"shirakawa.gifu.jp", +"tajimi.gifu.jp", +"takayama.gifu.jp", +"tarui.gifu.jp", +"toki.gifu.jp", +"tomika.gifu.jp", +"wanouchi.gifu.jp", +"yamagata.gifu.jp", +"yaotsu.gifu.jp", +"yoro.gifu.jp", +"annaka.gunma.jp", +"chiyoda.gunma.jp", +"fujioka.gunma.jp", +"higashiagatsuma.gunma.jp", +"isesaki.gunma.jp", +"itakura.gunma.jp", +"kanna.gunma.jp", +"kanra.gunma.jp", +"katashina.gunma.jp", +"kawaba.gunma.jp", +"kiryu.gunma.jp", +"kusatsu.gunma.jp", +"maebashi.gunma.jp", +"meiwa.gunma.jp", +"midori.gunma.jp", +"minakami.gunma.jp", +"naganohara.gunma.jp", +"nakanojo.gunma.jp", +"nanmoku.gunma.jp", +"numata.gunma.jp", +"oizumi.gunma.jp", +"ora.gunma.jp", +"ota.gunma.jp", +"shibukawa.gunma.jp", +"shimonita.gunma.jp", +"shinto.gunma.jp", +"showa.gunma.jp", +"takasaki.gunma.jp", +"takayama.gunma.jp", +"tamamura.gunma.jp", +"tatebayashi.gunma.jp", +"tomioka.gunma.jp", +"tsukiyono.gunma.jp", +"tsumagoi.gunma.jp", +"ueno.gunma.jp", +"yoshioka.gunma.jp", +"asaminami.hiroshima.jp", +"daiwa.hiroshima.jp", +"etajima.hiroshima.jp", +"fuchu.hiroshima.jp", +"fukuyama.hiroshima.jp", +"hatsukaichi.hiroshima.jp", +"higashihiroshima.hiroshima.jp", +"hongo.hiroshima.jp", +"jinsekikogen.hiroshima.jp", +"kaita.hiroshima.jp", +"kui.hiroshima.jp", +"kumano.hiroshima.jp", +"kure.hiroshima.jp", +"mihara.hiroshima.jp", +"miyoshi.hiroshima.jp", +"naka.hiroshima.jp", +"onomichi.hiroshima.jp", +"osakikamijima.hiroshima.jp", +"otake.hiroshima.jp", +"saka.hiroshima.jp", +"sera.hiroshima.jp", +"seranishi.hiroshima.jp", +"shinichi.hiroshima.jp", +"shobara.hiroshima.jp", +"takehara.hiroshima.jp", +"abashiri.hokkaido.jp", +"abira.hokkaido.jp", +"aibetsu.hokkaido.jp", +"akabira.hokkaido.jp", +"akkeshi.hokkaido.jp", +"asahikawa.hokkaido.jp", +"ashibetsu.hokkaido.jp", +"ashoro.hokkaido.jp", +"assabu.hokkaido.jp", +"atsuma.hokkaido.jp", +"bibai.hokkaido.jp", +"biei.hokkaido.jp", +"bifuka.hokkaido.jp", +"bihoro.hokkaido.jp", +"biratori.hokkaido.jp", +"chippubetsu.hokkaido.jp", +"chitose.hokkaido.jp", +"date.hokkaido.jp", +"ebetsu.hokkaido.jp", +"embetsu.hokkaido.jp", +"eniwa.hokkaido.jp", +"erimo.hokkaido.jp", +"esan.hokkaido.jp", +"esashi.hokkaido.jp", +"fukagawa.hokkaido.jp", +"fukushima.hokkaido.jp", +"furano.hokkaido.jp", +"furubira.hokkaido.jp", +"haboro.hokkaido.jp", +"hakodate.hokkaido.jp", +"hamatonbetsu.hokkaido.jp", +"hidaka.hokkaido.jp", +"higashikagura.hokkaido.jp", +"higashikawa.hokkaido.jp", +"hiroo.hokkaido.jp", +"hokuryu.hokkaido.jp", +"hokuto.hokkaido.jp", +"honbetsu.hokkaido.jp", +"horokanai.hokkaido.jp", +"horonobe.hokkaido.jp", +"ikeda.hokkaido.jp", +"imakane.hokkaido.jp", +"ishikari.hokkaido.jp", +"iwamizawa.hokkaido.jp", +"iwanai.hokkaido.jp", +"kamifurano.hokkaido.jp", +"kamikawa.hokkaido.jp", +"kamishihoro.hokkaido.jp", +"kamisunagawa.hokkaido.jp", +"kamoenai.hokkaido.jp", +"kayabe.hokkaido.jp", +"kembuchi.hokkaido.jp", +"kikonai.hokkaido.jp", +"kimobetsu.hokkaido.jp", +"kitahiroshima.hokkaido.jp", +"kitami.hokkaido.jp", +"kiyosato.hokkaido.jp", +"koshimizu.hokkaido.jp", +"kunneppu.hokkaido.jp", +"kuriyama.hokkaido.jp", +"kuromatsunai.hokkaido.jp", +"kushiro.hokkaido.jp", +"kutchan.hokkaido.jp", +"kyowa.hokkaido.jp", +"mashike.hokkaido.jp", +"matsumae.hokkaido.jp", +"mikasa.hokkaido.jp", +"minamifurano.hokkaido.jp", +"mombetsu.hokkaido.jp", +"moseushi.hokkaido.jp", +"mukawa.hokkaido.jp", +"muroran.hokkaido.jp", +"naie.hokkaido.jp", +"nakagawa.hokkaido.jp", +"nakasatsunai.hokkaido.jp", +"nakatombetsu.hokkaido.jp", +"nanae.hokkaido.jp", +"nanporo.hokkaido.jp", +"nayoro.hokkaido.jp", +"nemuro.hokkaido.jp", +"niikappu.hokkaido.jp", +"niki.hokkaido.jp", +"nishiokoppe.hokkaido.jp", +"noboribetsu.hokkaido.jp", +"numata.hokkaido.jp", +"obihiro.hokkaido.jp", +"obira.hokkaido.jp", +"oketo.hokkaido.jp", +"okoppe.hokkaido.jp", +"otaru.hokkaido.jp", +"otobe.hokkaido.jp", +"otofuke.hokkaido.jp", +"otoineppu.hokkaido.jp", +"oumu.hokkaido.jp", +"ozora.hokkaido.jp", +"pippu.hokkaido.jp", +"rankoshi.hokkaido.jp", +"rebun.hokkaido.jp", +"rikubetsu.hokkaido.jp", +"rishiri.hokkaido.jp", +"rishirifuji.hokkaido.jp", +"saroma.hokkaido.jp", +"sarufutsu.hokkaido.jp", +"shakotan.hokkaido.jp", +"shari.hokkaido.jp", +"shibecha.hokkaido.jp", +"shibetsu.hokkaido.jp", +"shikabe.hokkaido.jp", +"shikaoi.hokkaido.jp", +"shimamaki.hokkaido.jp", +"shimizu.hokkaido.jp", +"shimokawa.hokkaido.jp", +"shinshinotsu.hokkaido.jp", +"shintoku.hokkaido.jp", +"shiranuka.hokkaido.jp", +"shiraoi.hokkaido.jp", +"shiriuchi.hokkaido.jp", +"sobetsu.hokkaido.jp", +"sunagawa.hokkaido.jp", +"taiki.hokkaido.jp", +"takasu.hokkaido.jp", +"takikawa.hokkaido.jp", +"takinoue.hokkaido.jp", +"teshikaga.hokkaido.jp", +"tobetsu.hokkaido.jp", +"tohma.hokkaido.jp", +"tomakomai.hokkaido.jp", +"tomari.hokkaido.jp", +"toya.hokkaido.jp", +"toyako.hokkaido.jp", +"toyotomi.hokkaido.jp", +"toyoura.hokkaido.jp", +"tsubetsu.hokkaido.jp", +"tsukigata.hokkaido.jp", +"urakawa.hokkaido.jp", +"urausu.hokkaido.jp", +"uryu.hokkaido.jp", +"utashinai.hokkaido.jp", +"wakkanai.hokkaido.jp", +"wassamu.hokkaido.jp", +"yakumo.hokkaido.jp", +"yoichi.hokkaido.jp", +"aioi.hyogo.jp", +"akashi.hyogo.jp", +"ako.hyogo.jp", +"amagasaki.hyogo.jp", +"aogaki.hyogo.jp", +"asago.hyogo.jp", +"ashiya.hyogo.jp", +"awaji.hyogo.jp", +"fukusaki.hyogo.jp", +"goshiki.hyogo.jp", +"harima.hyogo.jp", +"himeji.hyogo.jp", +"ichikawa.hyogo.jp", +"inagawa.hyogo.jp", +"itami.hyogo.jp", +"kakogawa.hyogo.jp", +"kamigori.hyogo.jp", +"kamikawa.hyogo.jp", +"kasai.hyogo.jp", +"kasuga.hyogo.jp", +"kawanishi.hyogo.jp", +"miki.hyogo.jp", +"minamiawaji.hyogo.jp", +"nishinomiya.hyogo.jp", +"nishiwaki.hyogo.jp", +"ono.hyogo.jp", +"sanda.hyogo.jp", +"sannan.hyogo.jp", +"sasayama.hyogo.jp", +"sayo.hyogo.jp", +"shingu.hyogo.jp", +"shinonsen.hyogo.jp", +"shiso.hyogo.jp", +"sumoto.hyogo.jp", +"taishi.hyogo.jp", +"taka.hyogo.jp", +"takarazuka.hyogo.jp", +"takasago.hyogo.jp", +"takino.hyogo.jp", +"tamba.hyogo.jp", +"tatsuno.hyogo.jp", +"toyooka.hyogo.jp", +"yabu.hyogo.jp", +"yashiro.hyogo.jp", +"yoka.hyogo.jp", +"yokawa.hyogo.jp", +"ami.ibaraki.jp", +"asahi.ibaraki.jp", +"bando.ibaraki.jp", +"chikusei.ibaraki.jp", +"daigo.ibaraki.jp", +"fujishiro.ibaraki.jp", +"hitachi.ibaraki.jp", +"hitachinaka.ibaraki.jp", +"hitachiomiya.ibaraki.jp", +"hitachiota.ibaraki.jp", +"ibaraki.ibaraki.jp", +"ina.ibaraki.jp", +"inashiki.ibaraki.jp", +"itako.ibaraki.jp", +"iwama.ibaraki.jp", +"joso.ibaraki.jp", +"kamisu.ibaraki.jp", +"kasama.ibaraki.jp", +"kashima.ibaraki.jp", +"kasumigaura.ibaraki.jp", +"koga.ibaraki.jp", +"miho.ibaraki.jp", +"mito.ibaraki.jp", +"moriya.ibaraki.jp", +"naka.ibaraki.jp", +"namegata.ibaraki.jp", +"oarai.ibaraki.jp", +"ogawa.ibaraki.jp", +"omitama.ibaraki.jp", +"ryugasaki.ibaraki.jp", +"sakai.ibaraki.jp", +"sakuragawa.ibaraki.jp", +"shimodate.ibaraki.jp", +"shimotsuma.ibaraki.jp", +"shirosato.ibaraki.jp", +"sowa.ibaraki.jp", +"suifu.ibaraki.jp", +"takahagi.ibaraki.jp", +"tamatsukuri.ibaraki.jp", +"tokai.ibaraki.jp", +"tomobe.ibaraki.jp", +"tone.ibaraki.jp", +"toride.ibaraki.jp", +"tsuchiura.ibaraki.jp", +"tsukuba.ibaraki.jp", +"uchihara.ibaraki.jp", +"ushiku.ibaraki.jp", +"yachiyo.ibaraki.jp", +"yamagata.ibaraki.jp", +"yawara.ibaraki.jp", +"yuki.ibaraki.jp", +"anamizu.ishikawa.jp", +"hakui.ishikawa.jp", +"hakusan.ishikawa.jp", +"kaga.ishikawa.jp", +"kahoku.ishikawa.jp", +"kanazawa.ishikawa.jp", +"kawakita.ishikawa.jp", +"komatsu.ishikawa.jp", +"nakanoto.ishikawa.jp", +"nanao.ishikawa.jp", +"nomi.ishikawa.jp", +"nonoichi.ishikawa.jp", +"noto.ishikawa.jp", +"shika.ishikawa.jp", +"suzu.ishikawa.jp", +"tsubata.ishikawa.jp", +"tsurugi.ishikawa.jp", +"uchinada.ishikawa.jp", +"wajima.ishikawa.jp", +"fudai.iwate.jp", +"fujisawa.iwate.jp", +"hanamaki.iwate.jp", +"hiraizumi.iwate.jp", +"hirono.iwate.jp", +"ichinohe.iwate.jp", +"ichinoseki.iwate.jp", +"iwaizumi.iwate.jp", +"iwate.iwate.jp", +"joboji.iwate.jp", +"kamaishi.iwate.jp", +"kanegasaki.iwate.jp", +"karumai.iwate.jp", +"kawai.iwate.jp", +"kitakami.iwate.jp", +"kuji.iwate.jp", +"kunohe.iwate.jp", +"kuzumaki.iwate.jp", +"miyako.iwate.jp", +"mizusawa.iwate.jp", +"morioka.iwate.jp", +"ninohe.iwate.jp", +"noda.iwate.jp", +"ofunato.iwate.jp", +"oshu.iwate.jp", +"otsuchi.iwate.jp", +"rikuzentakata.iwate.jp", +"shiwa.iwate.jp", +"shizukuishi.iwate.jp", +"sumita.iwate.jp", +"tanohata.iwate.jp", +"tono.iwate.jp", +"yahaba.iwate.jp", +"yamada.iwate.jp", +"ayagawa.kagawa.jp", +"higashikagawa.kagawa.jp", +"kanonji.kagawa.jp", +"kotohira.kagawa.jp", +"manno.kagawa.jp", +"marugame.kagawa.jp", +"mitoyo.kagawa.jp", +"naoshima.kagawa.jp", +"sanuki.kagawa.jp", +"tadotsu.kagawa.jp", +"takamatsu.kagawa.jp", +"tonosho.kagawa.jp", +"uchinomi.kagawa.jp", +"utazu.kagawa.jp", +"zentsuji.kagawa.jp", +"akune.kagoshima.jp", +"amami.kagoshima.jp", +"hioki.kagoshima.jp", +"isa.kagoshima.jp", +"isen.kagoshima.jp", +"izumi.kagoshima.jp", +"kagoshima.kagoshima.jp", +"kanoya.kagoshima.jp", +"kawanabe.kagoshima.jp", +"kinko.kagoshima.jp", +"kouyama.kagoshima.jp", +"makurazaki.kagoshima.jp", +"matsumoto.kagoshima.jp", +"minamitane.kagoshima.jp", +"nakatane.kagoshima.jp", +"nishinoomote.kagoshima.jp", +"satsumasendai.kagoshima.jp", +"soo.kagoshima.jp", +"tarumizu.kagoshima.jp", +"yusui.kagoshima.jp", +"aikawa.kanagawa.jp", +"atsugi.kanagawa.jp", +"ayase.kanagawa.jp", +"chigasaki.kanagawa.jp", +"ebina.kanagawa.jp", +"fujisawa.kanagawa.jp", +"hadano.kanagawa.jp", +"hakone.kanagawa.jp", +"hiratsuka.kanagawa.jp", +"isehara.kanagawa.jp", +"kaisei.kanagawa.jp", +"kamakura.kanagawa.jp", +"kiyokawa.kanagawa.jp", +"matsuda.kanagawa.jp", +"minamiashigara.kanagawa.jp", +"miura.kanagawa.jp", +"nakai.kanagawa.jp", +"ninomiya.kanagawa.jp", +"odawara.kanagawa.jp", +"oi.kanagawa.jp", +"oiso.kanagawa.jp", +"sagamihara.kanagawa.jp", +"samukawa.kanagawa.jp", +"tsukui.kanagawa.jp", +"yamakita.kanagawa.jp", +"yamato.kanagawa.jp", +"yokosuka.kanagawa.jp", +"yugawara.kanagawa.jp", +"zama.kanagawa.jp", +"zushi.kanagawa.jp", +"aki.kochi.jp", +"geisei.kochi.jp", +"hidaka.kochi.jp", +"higashitsuno.kochi.jp", +"ino.kochi.jp", +"kagami.kochi.jp", +"kami.kochi.jp", +"kitagawa.kochi.jp", +"kochi.kochi.jp", +"mihara.kochi.jp", +"motoyama.kochi.jp", +"muroto.kochi.jp", +"nahari.kochi.jp", +"nakamura.kochi.jp", +"nankoku.kochi.jp", +"nishitosa.kochi.jp", +"niyodogawa.kochi.jp", +"ochi.kochi.jp", +"okawa.kochi.jp", +"otoyo.kochi.jp", +"otsuki.kochi.jp", +"sakawa.kochi.jp", +"sukumo.kochi.jp", +"susaki.kochi.jp", +"tosa.kochi.jp", +"tosashimizu.kochi.jp", +"toyo.kochi.jp", +"tsuno.kochi.jp", +"umaji.kochi.jp", +"yasuda.kochi.jp", +"yusuhara.kochi.jp", +"amakusa.kumamoto.jp", +"arao.kumamoto.jp", +"aso.kumamoto.jp", +"choyo.kumamoto.jp", +"gyokuto.kumamoto.jp", +"kamiamakusa.kumamoto.jp", +"kikuchi.kumamoto.jp", +"kumamoto.kumamoto.jp", +"mashiki.kumamoto.jp", +"mifune.kumamoto.jp", +"minamata.kumamoto.jp", +"minamioguni.kumamoto.jp", +"nagasu.kumamoto.jp", +"nishihara.kumamoto.jp", +"oguni.kumamoto.jp", +"ozu.kumamoto.jp", +"sumoto.kumamoto.jp", +"takamori.kumamoto.jp", +"uki.kumamoto.jp", +"uto.kumamoto.jp", +"yamaga.kumamoto.jp", +"yamato.kumamoto.jp", +"yatsushiro.kumamoto.jp", +"ayabe.kyoto.jp", +"fukuchiyama.kyoto.jp", +"higashiyama.kyoto.jp", +"ide.kyoto.jp", +"ine.kyoto.jp", +"joyo.kyoto.jp", +"kameoka.kyoto.jp", +"kamo.kyoto.jp", +"kita.kyoto.jp", +"kizu.kyoto.jp", +"kumiyama.kyoto.jp", +"kyotamba.kyoto.jp", +"kyotanabe.kyoto.jp", +"kyotango.kyoto.jp", +"maizuru.kyoto.jp", +"minami.kyoto.jp", +"minamiyamashiro.kyoto.jp", +"miyazu.kyoto.jp", +"muko.kyoto.jp", +"nagaokakyo.kyoto.jp", +"nakagyo.kyoto.jp", +"nantan.kyoto.jp", +"oyamazaki.kyoto.jp", +"sakyo.kyoto.jp", +"seika.kyoto.jp", +"tanabe.kyoto.jp", +"uji.kyoto.jp", +"ujitawara.kyoto.jp", +"wazuka.kyoto.jp", +"yamashina.kyoto.jp", +"yawata.kyoto.jp", +"asahi.mie.jp", +"inabe.mie.jp", +"ise.mie.jp", +"kameyama.mie.jp", +"kawagoe.mie.jp", +"kiho.mie.jp", +"kisosaki.mie.jp", +"kiwa.mie.jp", +"komono.mie.jp", +"kumano.mie.jp", +"kuwana.mie.jp", +"matsusaka.mie.jp", +"meiwa.mie.jp", +"mihama.mie.jp", +"minamiise.mie.jp", +"misugi.mie.jp", +"miyama.mie.jp", +"nabari.mie.jp", +"shima.mie.jp", +"suzuka.mie.jp", +"tado.mie.jp", +"taiki.mie.jp", +"taki.mie.jp", +"tamaki.mie.jp", +"toba.mie.jp", +"tsu.mie.jp", +"udono.mie.jp", +"ureshino.mie.jp", +"watarai.mie.jp", +"yokkaichi.mie.jp", +"furukawa.miyagi.jp", +"higashimatsushima.miyagi.jp", +"ishinomaki.miyagi.jp", +"iwanuma.miyagi.jp", +"kakuda.miyagi.jp", +"kami.miyagi.jp", +"kawasaki.miyagi.jp", +"marumori.miyagi.jp", +"matsushima.miyagi.jp", +"minamisanriku.miyagi.jp", +"misato.miyagi.jp", +"murata.miyagi.jp", +"natori.miyagi.jp", +"ogawara.miyagi.jp", +"ohira.miyagi.jp", +"onagawa.miyagi.jp", +"osaki.miyagi.jp", +"rifu.miyagi.jp", +"semine.miyagi.jp", +"shibata.miyagi.jp", +"shichikashuku.miyagi.jp", +"shikama.miyagi.jp", +"shiogama.miyagi.jp", +"shiroishi.miyagi.jp", +"tagajo.miyagi.jp", +"taiwa.miyagi.jp", +"tome.miyagi.jp", +"tomiya.miyagi.jp", +"wakuya.miyagi.jp", +"watari.miyagi.jp", +"yamamoto.miyagi.jp", +"zao.miyagi.jp", +"aya.miyazaki.jp", +"ebino.miyazaki.jp", +"gokase.miyazaki.jp", +"hyuga.miyazaki.jp", +"kadogawa.miyazaki.jp", +"kawaminami.miyazaki.jp", +"kijo.miyazaki.jp", +"kitagawa.miyazaki.jp", +"kitakata.miyazaki.jp", +"kitaura.miyazaki.jp", +"kobayashi.miyazaki.jp", +"kunitomi.miyazaki.jp", +"kushima.miyazaki.jp", +"mimata.miyazaki.jp", +"miyakonojo.miyazaki.jp", +"miyazaki.miyazaki.jp", +"morotsuka.miyazaki.jp", +"nichinan.miyazaki.jp", +"nishimera.miyazaki.jp", +"nobeoka.miyazaki.jp", +"saito.miyazaki.jp", +"shiiba.miyazaki.jp", +"shintomi.miyazaki.jp", +"takaharu.miyazaki.jp", +"takanabe.miyazaki.jp", +"takazaki.miyazaki.jp", +"tsuno.miyazaki.jp", +"achi.nagano.jp", +"agematsu.nagano.jp", +"anan.nagano.jp", +"aoki.nagano.jp", +"asahi.nagano.jp", +"azumino.nagano.jp", +"chikuhoku.nagano.jp", +"chikuma.nagano.jp", +"chino.nagano.jp", +"fujimi.nagano.jp", +"hakuba.nagano.jp", +"hara.nagano.jp", +"hiraya.nagano.jp", +"iida.nagano.jp", +"iijima.nagano.jp", +"iiyama.nagano.jp", +"iizuna.nagano.jp", +"ikeda.nagano.jp", +"ikusaka.nagano.jp", +"ina.nagano.jp", +"karuizawa.nagano.jp", +"kawakami.nagano.jp", +"kiso.nagano.jp", +"kisofukushima.nagano.jp", +"kitaaiki.nagano.jp", +"komagane.nagano.jp", +"komoro.nagano.jp", +"matsukawa.nagano.jp", +"matsumoto.nagano.jp", +"miasa.nagano.jp", +"minamiaiki.nagano.jp", +"minamimaki.nagano.jp", +"minamiminowa.nagano.jp", +"minowa.nagano.jp", +"miyada.nagano.jp", +"miyota.nagano.jp", +"mochizuki.nagano.jp", +"nagano.nagano.jp", +"nagawa.nagano.jp", +"nagiso.nagano.jp", +"nakagawa.nagano.jp", +"nakano.nagano.jp", +"nozawaonsen.nagano.jp", +"obuse.nagano.jp", +"ogawa.nagano.jp", +"okaya.nagano.jp", +"omachi.nagano.jp", +"omi.nagano.jp", +"ookuwa.nagano.jp", +"ooshika.nagano.jp", +"otaki.nagano.jp", +"otari.nagano.jp", +"sakae.nagano.jp", +"sakaki.nagano.jp", +"saku.nagano.jp", +"sakuho.nagano.jp", +"shimosuwa.nagano.jp", +"shinanomachi.nagano.jp", +"shiojiri.nagano.jp", +"suwa.nagano.jp", +"suzaka.nagano.jp", +"takagi.nagano.jp", +"takamori.nagano.jp", +"takayama.nagano.jp", +"tateshina.nagano.jp", +"tatsuno.nagano.jp", +"togakushi.nagano.jp", +"togura.nagano.jp", +"tomi.nagano.jp", +"ueda.nagano.jp", +"wada.nagano.jp", +"yamagata.nagano.jp", +"yamanouchi.nagano.jp", +"yasaka.nagano.jp", +"yasuoka.nagano.jp", +"chijiwa.nagasaki.jp", +"futsu.nagasaki.jp", +"goto.nagasaki.jp", +"hasami.nagasaki.jp", +"hirado.nagasaki.jp", +"iki.nagasaki.jp", +"isahaya.nagasaki.jp", +"kawatana.nagasaki.jp", +"kuchinotsu.nagasaki.jp", +"matsuura.nagasaki.jp", +"nagasaki.nagasaki.jp", +"obama.nagasaki.jp", +"omura.nagasaki.jp", +"oseto.nagasaki.jp", +"saikai.nagasaki.jp", +"sasebo.nagasaki.jp", +"seihi.nagasaki.jp", +"shimabara.nagasaki.jp", +"shinkamigoto.nagasaki.jp", +"togitsu.nagasaki.jp", +"tsushima.nagasaki.jp", +"unzen.nagasaki.jp", +"ando.nara.jp", +"gose.nara.jp", +"heguri.nara.jp", +"higashiyoshino.nara.jp", +"ikaruga.nara.jp", +"ikoma.nara.jp", +"kamikitayama.nara.jp", +"kanmaki.nara.jp", +"kashiba.nara.jp", +"kashihara.nara.jp", +"katsuragi.nara.jp", +"kawai.nara.jp", +"kawakami.nara.jp", +"kawanishi.nara.jp", +"koryo.nara.jp", +"kurotaki.nara.jp", +"mitsue.nara.jp", +"miyake.nara.jp", +"nara.nara.jp", +"nosegawa.nara.jp", +"oji.nara.jp", +"ouda.nara.jp", +"oyodo.nara.jp", +"sakurai.nara.jp", +"sango.nara.jp", +"shimoichi.nara.jp", +"shimokitayama.nara.jp", +"shinjo.nara.jp", +"soni.nara.jp", +"takatori.nara.jp", +"tawaramoto.nara.jp", +"tenkawa.nara.jp", +"tenri.nara.jp", +"uda.nara.jp", +"yamatokoriyama.nara.jp", +"yamatotakada.nara.jp", +"yamazoe.nara.jp", +"yoshino.nara.jp", +"aga.niigata.jp", +"agano.niigata.jp", +"gosen.niigata.jp", +"itoigawa.niigata.jp", +"izumozaki.niigata.jp", +"joetsu.niigata.jp", +"kamo.niigata.jp", +"kariwa.niigata.jp", +"kashiwazaki.niigata.jp", +"minamiuonuma.niigata.jp", +"mitsuke.niigata.jp", +"muika.niigata.jp", +"murakami.niigata.jp", +"myoko.niigata.jp", +"nagaoka.niigata.jp", +"niigata.niigata.jp", +"ojiya.niigata.jp", +"omi.niigata.jp", +"sado.niigata.jp", +"sanjo.niigata.jp", +"seiro.niigata.jp", +"seirou.niigata.jp", +"sekikawa.niigata.jp", +"shibata.niigata.jp", +"tagami.niigata.jp", +"tainai.niigata.jp", +"tochio.niigata.jp", +"tokamachi.niigata.jp", +"tsubame.niigata.jp", +"tsunan.niigata.jp", +"uonuma.niigata.jp", +"yahiko.niigata.jp", +"yoita.niigata.jp", +"yuzawa.niigata.jp", +"beppu.oita.jp", +"bungoono.oita.jp", +"bungotakada.oita.jp", +"hasama.oita.jp", +"hiji.oita.jp", +"himeshima.oita.jp", +"hita.oita.jp", +"kamitsue.oita.jp", +"kokonoe.oita.jp", +"kuju.oita.jp", +"kunisaki.oita.jp", +"kusu.oita.jp", +"oita.oita.jp", +"saiki.oita.jp", +"taketa.oita.jp", +"tsukumi.oita.jp", +"usa.oita.jp", +"usuki.oita.jp", +"yufu.oita.jp", +"akaiwa.okayama.jp", +"asakuchi.okayama.jp", +"bizen.okayama.jp", +"hayashima.okayama.jp", +"ibara.okayama.jp", +"kagamino.okayama.jp", +"kasaoka.okayama.jp", +"kibichuo.okayama.jp", +"kumenan.okayama.jp", +"kurashiki.okayama.jp", +"maniwa.okayama.jp", +"misaki.okayama.jp", +"nagi.okayama.jp", +"niimi.okayama.jp", +"nishiawakura.okayama.jp", +"okayama.okayama.jp", +"satosho.okayama.jp", +"setouchi.okayama.jp", +"shinjo.okayama.jp", +"shoo.okayama.jp", +"soja.okayama.jp", +"takahashi.okayama.jp", +"tamano.okayama.jp", +"tsuyama.okayama.jp", +"wake.okayama.jp", +"yakage.okayama.jp", +"aguni.okinawa.jp", +"ginowan.okinawa.jp", +"ginoza.okinawa.jp", +"gushikami.okinawa.jp", +"haebaru.okinawa.jp", +"higashi.okinawa.jp", +"hirara.okinawa.jp", +"iheya.okinawa.jp", +"ishigaki.okinawa.jp", +"ishikawa.okinawa.jp", +"itoman.okinawa.jp", +"izena.okinawa.jp", +"kadena.okinawa.jp", +"kin.okinawa.jp", +"kitadaito.okinawa.jp", +"kitanakagusuku.okinawa.jp", +"kumejima.okinawa.jp", +"kunigami.okinawa.jp", +"minamidaito.okinawa.jp", +"motobu.okinawa.jp", +"nago.okinawa.jp", +"naha.okinawa.jp", +"nakagusuku.okinawa.jp", +"nakijin.okinawa.jp", +"nanjo.okinawa.jp", +"nishihara.okinawa.jp", +"ogimi.okinawa.jp", +"okinawa.okinawa.jp", +"onna.okinawa.jp", +"shimoji.okinawa.jp", +"taketomi.okinawa.jp", +"tarama.okinawa.jp", +"tokashiki.okinawa.jp", +"tomigusuku.okinawa.jp", +"tonaki.okinawa.jp", +"urasoe.okinawa.jp", +"uruma.okinawa.jp", +"yaese.okinawa.jp", +"yomitan.okinawa.jp", +"yonabaru.okinawa.jp", +"yonaguni.okinawa.jp", +"zamami.okinawa.jp", +"abeno.osaka.jp", +"chihayaakasaka.osaka.jp", +"chuo.osaka.jp", +"daito.osaka.jp", +"fujiidera.osaka.jp", +"habikino.osaka.jp", +"hannan.osaka.jp", +"higashiosaka.osaka.jp", +"higashisumiyoshi.osaka.jp", +"higashiyodogawa.osaka.jp", +"hirakata.osaka.jp", +"ibaraki.osaka.jp", +"ikeda.osaka.jp", +"izumi.osaka.jp", +"izumiotsu.osaka.jp", +"izumisano.osaka.jp", +"kadoma.osaka.jp", +"kaizuka.osaka.jp", +"kanan.osaka.jp", +"kashiwara.osaka.jp", +"katano.osaka.jp", +"kawachinagano.osaka.jp", +"kishiwada.osaka.jp", +"kita.osaka.jp", +"kumatori.osaka.jp", +"matsubara.osaka.jp", +"minato.osaka.jp", +"minoh.osaka.jp", +"misaki.osaka.jp", +"moriguchi.osaka.jp", +"neyagawa.osaka.jp", +"nishi.osaka.jp", +"nose.osaka.jp", +"osakasayama.osaka.jp", +"sakai.osaka.jp", +"sayama.osaka.jp", +"sennan.osaka.jp", +"settsu.osaka.jp", +"shijonawate.osaka.jp", +"shimamoto.osaka.jp", +"suita.osaka.jp", +"tadaoka.osaka.jp", +"taishi.osaka.jp", +"tajiri.osaka.jp", +"takaishi.osaka.jp", +"takatsuki.osaka.jp", +"tondabayashi.osaka.jp", +"toyonaka.osaka.jp", +"toyono.osaka.jp", +"yao.osaka.jp", +"ariake.saga.jp", +"arita.saga.jp", +"fukudomi.saga.jp", +"genkai.saga.jp", +"hamatama.saga.jp", +"hizen.saga.jp", +"imari.saga.jp", +"kamimine.saga.jp", +"kanzaki.saga.jp", +"karatsu.saga.jp", +"kashima.saga.jp", +"kitagata.saga.jp", +"kitahata.saga.jp", +"kiyama.saga.jp", +"kouhoku.saga.jp", +"kyuragi.saga.jp", +"nishiarita.saga.jp", +"ogi.saga.jp", +"omachi.saga.jp", +"ouchi.saga.jp", +"saga.saga.jp", +"shiroishi.saga.jp", +"taku.saga.jp", +"tara.saga.jp", +"tosu.saga.jp", +"yoshinogari.saga.jp", +"arakawa.saitama.jp", +"asaka.saitama.jp", +"chichibu.saitama.jp", +"fujimi.saitama.jp", +"fujimino.saitama.jp", +"fukaya.saitama.jp", +"hanno.saitama.jp", +"hanyu.saitama.jp", +"hasuda.saitama.jp", +"hatogaya.saitama.jp", +"hatoyama.saitama.jp", +"hidaka.saitama.jp", +"higashichichibu.saitama.jp", +"higashimatsuyama.saitama.jp", +"honjo.saitama.jp", +"ina.saitama.jp", +"iruma.saitama.jp", +"iwatsuki.saitama.jp", +"kamiizumi.saitama.jp", +"kamikawa.saitama.jp", +"kamisato.saitama.jp", +"kasukabe.saitama.jp", +"kawagoe.saitama.jp", +"kawaguchi.saitama.jp", +"kawajima.saitama.jp", +"kazo.saitama.jp", +"kitamoto.saitama.jp", +"koshigaya.saitama.jp", +"kounosu.saitama.jp", +"kuki.saitama.jp", +"kumagaya.saitama.jp", +"matsubushi.saitama.jp", +"minano.saitama.jp", +"misato.saitama.jp", +"miyashiro.saitama.jp", +"miyoshi.saitama.jp", +"moroyama.saitama.jp", +"nagatoro.saitama.jp", +"namegawa.saitama.jp", +"niiza.saitama.jp", +"ogano.saitama.jp", +"ogawa.saitama.jp", +"ogose.saitama.jp", +"okegawa.saitama.jp", +"omiya.saitama.jp", +"otaki.saitama.jp", +"ranzan.saitama.jp", +"ryokami.saitama.jp", +"saitama.saitama.jp", +"sakado.saitama.jp", +"satte.saitama.jp", +"sayama.saitama.jp", +"shiki.saitama.jp", +"shiraoka.saitama.jp", +"soka.saitama.jp", +"sugito.saitama.jp", +"toda.saitama.jp", +"tokigawa.saitama.jp", +"tokorozawa.saitama.jp", +"tsurugashima.saitama.jp", +"urawa.saitama.jp", +"warabi.saitama.jp", +"yashio.saitama.jp", +"yokoze.saitama.jp", +"yono.saitama.jp", +"yorii.saitama.jp", +"yoshida.saitama.jp", +"yoshikawa.saitama.jp", +"yoshimi.saitama.jp", +"aisho.shiga.jp", +"gamo.shiga.jp", +"higashiomi.shiga.jp", +"hikone.shiga.jp", +"koka.shiga.jp", +"konan.shiga.jp", +"kosei.shiga.jp", +"koto.shiga.jp", +"kusatsu.shiga.jp", +"maibara.shiga.jp", +"moriyama.shiga.jp", +"nagahama.shiga.jp", +"nishiazai.shiga.jp", +"notogawa.shiga.jp", +"omihachiman.shiga.jp", +"otsu.shiga.jp", +"ritto.shiga.jp", +"ryuoh.shiga.jp", +"takashima.shiga.jp", +"takatsuki.shiga.jp", +"torahime.shiga.jp", +"toyosato.shiga.jp", +"yasu.shiga.jp", +"akagi.shimane.jp", +"ama.shimane.jp", +"gotsu.shimane.jp", +"hamada.shimane.jp", +"higashiizumo.shimane.jp", +"hikawa.shimane.jp", +"hikimi.shimane.jp", +"izumo.shimane.jp", +"kakinoki.shimane.jp", +"masuda.shimane.jp", +"matsue.shimane.jp", +"misato.shimane.jp", +"nishinoshima.shimane.jp", +"ohda.shimane.jp", +"okinoshima.shimane.jp", +"okuizumo.shimane.jp", +"shimane.shimane.jp", +"tamayu.shimane.jp", +"tsuwano.shimane.jp", +"unnan.shimane.jp", +"yakumo.shimane.jp", +"yasugi.shimane.jp", +"yatsuka.shimane.jp", +"arai.shizuoka.jp", +"atami.shizuoka.jp", +"fuji.shizuoka.jp", +"fujieda.shizuoka.jp", +"fujikawa.shizuoka.jp", +"fujinomiya.shizuoka.jp", +"fukuroi.shizuoka.jp", +"gotemba.shizuoka.jp", +"haibara.shizuoka.jp", +"hamamatsu.shizuoka.jp", +"higashiizu.shizuoka.jp", +"ito.shizuoka.jp", +"iwata.shizuoka.jp", +"izu.shizuoka.jp", +"izunokuni.shizuoka.jp", +"kakegawa.shizuoka.jp", +"kannami.shizuoka.jp", +"kawanehon.shizuoka.jp", +"kawazu.shizuoka.jp", +"kikugawa.shizuoka.jp", +"kosai.shizuoka.jp", +"makinohara.shizuoka.jp", +"matsuzaki.shizuoka.jp", +"minamiizu.shizuoka.jp", +"mishima.shizuoka.jp", +"morimachi.shizuoka.jp", +"nishiizu.shizuoka.jp", +"numazu.shizuoka.jp", +"omaezaki.shizuoka.jp", +"shimada.shizuoka.jp", +"shimizu.shizuoka.jp", +"shimoda.shizuoka.jp", +"shizuoka.shizuoka.jp", +"susono.shizuoka.jp", +"yaizu.shizuoka.jp", +"yoshida.shizuoka.jp", +"ashikaga.tochigi.jp", +"bato.tochigi.jp", +"haga.tochigi.jp", +"ichikai.tochigi.jp", +"iwafune.tochigi.jp", +"kaminokawa.tochigi.jp", +"kanuma.tochigi.jp", +"karasuyama.tochigi.jp", +"kuroiso.tochigi.jp", +"mashiko.tochigi.jp", +"mibu.tochigi.jp", +"moka.tochigi.jp", +"motegi.tochigi.jp", +"nasu.tochigi.jp", +"nasushiobara.tochigi.jp", +"nikko.tochigi.jp", +"nishikata.tochigi.jp", +"nogi.tochigi.jp", +"ohira.tochigi.jp", +"ohtawara.tochigi.jp", +"oyama.tochigi.jp", +"sakura.tochigi.jp", +"sano.tochigi.jp", +"shimotsuke.tochigi.jp", +"shioya.tochigi.jp", +"takanezawa.tochigi.jp", +"tochigi.tochigi.jp", +"tsuga.tochigi.jp", +"ujiie.tochigi.jp", +"utsunomiya.tochigi.jp", +"yaita.tochigi.jp", +"aizumi.tokushima.jp", +"anan.tokushima.jp", +"ichiba.tokushima.jp", +"itano.tokushima.jp", +"kainan.tokushima.jp", +"komatsushima.tokushima.jp", +"matsushige.tokushima.jp", +"mima.tokushima.jp", +"minami.tokushima.jp", +"miyoshi.tokushima.jp", +"mugi.tokushima.jp", +"nakagawa.tokushima.jp", +"naruto.tokushima.jp", +"sanagochi.tokushima.jp", +"shishikui.tokushima.jp", +"tokushima.tokushima.jp", +"wajiki.tokushima.jp", +"adachi.tokyo.jp", +"akiruno.tokyo.jp", +"akishima.tokyo.jp", +"aogashima.tokyo.jp", +"arakawa.tokyo.jp", +"bunkyo.tokyo.jp", +"chiyoda.tokyo.jp", +"chofu.tokyo.jp", +"chuo.tokyo.jp", +"edogawa.tokyo.jp", +"fuchu.tokyo.jp", +"fussa.tokyo.jp", +"hachijo.tokyo.jp", +"hachioji.tokyo.jp", +"hamura.tokyo.jp", +"higashikurume.tokyo.jp", +"higashimurayama.tokyo.jp", +"higashiyamato.tokyo.jp", +"hino.tokyo.jp", +"hinode.tokyo.jp", +"hinohara.tokyo.jp", +"inagi.tokyo.jp", +"itabashi.tokyo.jp", +"katsushika.tokyo.jp", +"kita.tokyo.jp", +"kiyose.tokyo.jp", +"kodaira.tokyo.jp", +"koganei.tokyo.jp", +"kokubunji.tokyo.jp", +"komae.tokyo.jp", +"koto.tokyo.jp", +"kouzushima.tokyo.jp", +"kunitachi.tokyo.jp", +"machida.tokyo.jp", +"meguro.tokyo.jp", +"minato.tokyo.jp", +"mitaka.tokyo.jp", +"mizuho.tokyo.jp", +"musashimurayama.tokyo.jp", +"musashino.tokyo.jp", +"nakano.tokyo.jp", +"nerima.tokyo.jp", +"ogasawara.tokyo.jp", +"okutama.tokyo.jp", +"ome.tokyo.jp", +"oshima.tokyo.jp", +"ota.tokyo.jp", +"setagaya.tokyo.jp", +"shibuya.tokyo.jp", +"shinagawa.tokyo.jp", +"shinjuku.tokyo.jp", +"suginami.tokyo.jp", +"sumida.tokyo.jp", +"tachikawa.tokyo.jp", +"taito.tokyo.jp", +"tama.tokyo.jp", +"toshima.tokyo.jp", +"chizu.tottori.jp", +"hino.tottori.jp", +"kawahara.tottori.jp", +"koge.tottori.jp", +"kotoura.tottori.jp", +"misasa.tottori.jp", +"nanbu.tottori.jp", +"nichinan.tottori.jp", +"sakaiminato.tottori.jp", +"tottori.tottori.jp", +"wakasa.tottori.jp", +"yazu.tottori.jp", +"yonago.tottori.jp", +"asahi.toyama.jp", +"fuchu.toyama.jp", +"fukumitsu.toyama.jp", +"funahashi.toyama.jp", +"himi.toyama.jp", +"imizu.toyama.jp", +"inami.toyama.jp", +"johana.toyama.jp", +"kamiichi.toyama.jp", +"kurobe.toyama.jp", +"nakaniikawa.toyama.jp", +"namerikawa.toyama.jp", +"nanto.toyama.jp", +"nyuzen.toyama.jp", +"oyabe.toyama.jp", +"taira.toyama.jp", +"takaoka.toyama.jp", +"tateyama.toyama.jp", +"toga.toyama.jp", +"tonami.toyama.jp", +"toyama.toyama.jp", +"unazuki.toyama.jp", +"uozu.toyama.jp", +"yamada.toyama.jp", +"arida.wakayama.jp", +"aridagawa.wakayama.jp", +"gobo.wakayama.jp", +"hashimoto.wakayama.jp", +"hidaka.wakayama.jp", +"hirogawa.wakayama.jp", +"inami.wakayama.jp", +"iwade.wakayama.jp", +"kainan.wakayama.jp", +"kamitonda.wakayama.jp", +"katsuragi.wakayama.jp", +"kimino.wakayama.jp", +"kinokawa.wakayama.jp", +"kitayama.wakayama.jp", +"koya.wakayama.jp", +"koza.wakayama.jp", +"kozagawa.wakayama.jp", +"kudoyama.wakayama.jp", +"kushimoto.wakayama.jp", +"mihama.wakayama.jp", +"misato.wakayama.jp", +"nachikatsuura.wakayama.jp", +"shingu.wakayama.jp", +"shirahama.wakayama.jp", +"taiji.wakayama.jp", +"tanabe.wakayama.jp", +"wakayama.wakayama.jp", +"yuasa.wakayama.jp", +"yura.wakayama.jp", +"asahi.yamagata.jp", +"funagata.yamagata.jp", +"higashine.yamagata.jp", +"iide.yamagata.jp", +"kahoku.yamagata.jp", +"kaminoyama.yamagata.jp", +"kaneyama.yamagata.jp", +"kawanishi.yamagata.jp", +"mamurogawa.yamagata.jp", +"mikawa.yamagata.jp", +"murayama.yamagata.jp", +"nagai.yamagata.jp", +"nakayama.yamagata.jp", +"nanyo.yamagata.jp", +"nishikawa.yamagata.jp", +"obanazawa.yamagata.jp", +"oe.yamagata.jp", +"oguni.yamagata.jp", +"ohkura.yamagata.jp", +"oishida.yamagata.jp", +"sagae.yamagata.jp", +"sakata.yamagata.jp", +"sakegawa.yamagata.jp", +"shinjo.yamagata.jp", +"shirataka.yamagata.jp", +"shonai.yamagata.jp", +"takahata.yamagata.jp", +"tendo.yamagata.jp", +"tozawa.yamagata.jp", +"tsuruoka.yamagata.jp", +"yamagata.yamagata.jp", +"yamanobe.yamagata.jp", +"yonezawa.yamagata.jp", +"yuza.yamagata.jp", +"abu.yamaguchi.jp", +"hagi.yamaguchi.jp", +"hikari.yamaguchi.jp", +"hofu.yamaguchi.jp", +"iwakuni.yamaguchi.jp", +"kudamatsu.yamaguchi.jp", +"mitou.yamaguchi.jp", +"nagato.yamaguchi.jp", +"oshima.yamaguchi.jp", +"shimonoseki.yamaguchi.jp", +"shunan.yamaguchi.jp", +"tabuse.yamaguchi.jp", +"tokuyama.yamaguchi.jp", +"toyota.yamaguchi.jp", +"ube.yamaguchi.jp", +"yuu.yamaguchi.jp", +"chuo.yamanashi.jp", +"doshi.yamanashi.jp", +"fuefuki.yamanashi.jp", +"fujikawa.yamanashi.jp", +"fujikawaguchiko.yamanashi.jp", +"fujiyoshida.yamanashi.jp", +"hayakawa.yamanashi.jp", +"hokuto.yamanashi.jp", +"ichikawamisato.yamanashi.jp", +"kai.yamanashi.jp", +"kofu.yamanashi.jp", +"koshu.yamanashi.jp", +"kosuge.yamanashi.jp", +"minami-alps.yamanashi.jp", +"minobu.yamanashi.jp", +"nakamichi.yamanashi.jp", +"nanbu.yamanashi.jp", +"narusawa.yamanashi.jp", +"nirasaki.yamanashi.jp", +"nishikatsura.yamanashi.jp", +"oshino.yamanashi.jp", +"otsuki.yamanashi.jp", +"showa.yamanashi.jp", +"tabayama.yamanashi.jp", +"tsuru.yamanashi.jp", +"uenohara.yamanashi.jp", +"yamanakako.yamanashi.jp", +"yamanashi.yamanashi.jp", +"ke", +"ac.ke", +"co.ke", +"go.ke", +"info.ke", +"me.ke", +"mobi.ke", +"ne.ke", +"or.ke", +"sc.ke", +"kg", +"org.kg", +"net.kg", +"com.kg", +"edu.kg", +"gov.kg", +"mil.kg", +"*.kh", +"ki", +"edu.ki", +"biz.ki", +"net.ki", +"org.ki", +"gov.ki", +"info.ki", +"com.ki", +"km", +"org.km", +"nom.km", +"gov.km", +"prd.km", +"tm.km", +"edu.km", +"mil.km", +"ass.km", +"com.km", +"coop.km", +"asso.km", +"presse.km", +"medecin.km", +"notaires.km", +"pharmaciens.km", +"veterinaire.km", +"gouv.km", +"kn", +"net.kn", +"org.kn", +"edu.kn", +"gov.kn", +"kp", +"com.kp", +"edu.kp", +"gov.kp", +"org.kp", +"rep.kp", +"tra.kp", +"kr", +"ac.kr", +"co.kr", +"es.kr", +"go.kr", +"hs.kr", +"kg.kr", +"mil.kr", +"ms.kr", +"ne.kr", +"or.kr", +"pe.kr", +"re.kr", +"sc.kr", +"busan.kr", +"chungbuk.kr", +"chungnam.kr", +"daegu.kr", +"daejeon.kr", +"gangwon.kr", +"gwangju.kr", +"gyeongbuk.kr", +"gyeonggi.kr", +"gyeongnam.kr", +"incheon.kr", +"jeju.kr", +"jeonbuk.kr", +"jeonnam.kr", +"seoul.kr", +"ulsan.kr", +"kw", +"com.kw", +"edu.kw", +"emb.kw", +"gov.kw", +"ind.kw", +"net.kw", +"org.kw", +"ky", +"com.ky", +"edu.ky", +"net.ky", +"org.ky", +"kz", +"org.kz", +"edu.kz", +"net.kz", +"gov.kz", +"mil.kz", +"com.kz", +"la", +"int.la", +"net.la", +"info.la", +"edu.la", +"gov.la", +"per.la", +"com.la", +"org.la", +"lb", +"com.lb", +"edu.lb", +"gov.lb", +"net.lb", +"org.lb", +"lc", +"com.lc", +"net.lc", +"co.lc", +"org.lc", +"edu.lc", +"gov.lc", +"li", +"lk", +"gov.lk", +"sch.lk", +"net.lk", +"int.lk", +"com.lk", +"org.lk", +"edu.lk", +"ngo.lk", +"soc.lk", +"web.lk", +"ltd.lk", +"assn.lk", +"grp.lk", +"hotel.lk", +"ac.lk", +"lr", +"com.lr", +"edu.lr", +"gov.lr", +"org.lr", +"net.lr", +"ls", +"ac.ls", +"biz.ls", +"co.ls", +"edu.ls", +"gov.ls", +"info.ls", +"net.ls", +"org.ls", +"sc.ls", +"lt", +"gov.lt", +"lu", +"lv", +"com.lv", +"edu.lv", +"gov.lv", +"org.lv", +"mil.lv", +"id.lv", +"net.lv", +"asn.lv", +"conf.lv", +"ly", +"com.ly", +"net.ly", +"gov.ly", +"plc.ly", +"edu.ly", +"sch.ly", +"med.ly", +"org.ly", +"id.ly", +"ma", +"co.ma", +"net.ma", +"gov.ma", +"org.ma", +"ac.ma", +"press.ma", +"mc", +"tm.mc", +"asso.mc", +"md", +"me", +"co.me", +"net.me", +"org.me", +"edu.me", +"ac.me", +"gov.me", +"its.me", +"priv.me", +"mg", +"org.mg", +"nom.mg", +"gov.mg", +"prd.mg", +"tm.mg", +"edu.mg", +"mil.mg", +"com.mg", +"co.mg", +"mh", +"mil", +"mk", +"com.mk", +"org.mk", +"net.mk", +"edu.mk", +"gov.mk", +"inf.mk", +"name.mk", +"ml", +"com.ml", +"edu.ml", +"gouv.ml", +"gov.ml", +"net.ml", +"org.ml", +"presse.ml", +"*.mm", +"mn", +"gov.mn", +"edu.mn", +"org.mn", +"mo", +"com.mo", +"net.mo", +"org.mo", +"edu.mo", +"gov.mo", +"mobi", +"mp", +"mq", +"mr", +"gov.mr", +"ms", +"com.ms", +"edu.ms", +"gov.ms", +"net.ms", +"org.ms", +"mt", +"com.mt", +"edu.mt", +"net.mt", +"org.mt", +"mu", +"com.mu", +"net.mu", +"org.mu", +"gov.mu", +"ac.mu", +"co.mu", +"or.mu", +"museum", +"academy.museum", +"agriculture.museum", +"air.museum", +"airguard.museum", +"alabama.museum", +"alaska.museum", +"amber.museum", +"ambulance.museum", +"american.museum", +"americana.museum", +"americanantiques.museum", +"americanart.museum", +"amsterdam.museum", +"and.museum", +"annefrank.museum", +"anthro.museum", +"anthropology.museum", +"antiques.museum", +"aquarium.museum", +"arboretum.museum", +"archaeological.museum", +"archaeology.museum", +"architecture.museum", +"art.museum", +"artanddesign.museum", +"artcenter.museum", +"artdeco.museum", +"arteducation.museum", +"artgallery.museum", +"arts.museum", +"artsandcrafts.museum", +"asmatart.museum", +"assassination.museum", +"assisi.museum", +"association.museum", +"astronomy.museum", +"atlanta.museum", +"austin.museum", +"australia.museum", +"automotive.museum", +"aviation.museum", +"axis.museum", +"badajoz.museum", +"baghdad.museum", +"bahn.museum", +"bale.museum", +"baltimore.museum", +"barcelona.museum", +"baseball.museum", +"basel.museum", +"baths.museum", +"bauern.museum", +"beauxarts.museum", +"beeldengeluid.museum", +"bellevue.museum", +"bergbau.museum", +"berkeley.museum", +"berlin.museum", +"bern.museum", +"bible.museum", +"bilbao.museum", +"bill.museum", +"birdart.museum", +"birthplace.museum", +"bonn.museum", +"boston.museum", +"botanical.museum", +"botanicalgarden.museum", +"botanicgarden.museum", +"botany.museum", +"brandywinevalley.museum", +"brasil.museum", +"bristol.museum", +"british.museum", +"britishcolumbia.museum", +"broadcast.museum", +"brunel.museum", +"brussel.museum", +"brussels.museum", +"bruxelles.museum", +"building.museum", +"burghof.museum", +"bus.museum", +"bushey.museum", +"cadaques.museum", +"california.museum", +"cambridge.museum", +"can.museum", +"canada.museum", +"capebreton.museum", +"carrier.museum", +"cartoonart.museum", +"casadelamoneda.museum", +"castle.museum", +"castres.museum", +"celtic.museum", +"center.museum", +"chattanooga.museum", +"cheltenham.museum", +"chesapeakebay.museum", +"chicago.museum", +"children.museum", +"childrens.museum", +"childrensgarden.museum", +"chiropractic.museum", +"chocolate.museum", +"christiansburg.museum", +"cincinnati.museum", +"cinema.museum", +"circus.museum", +"civilisation.museum", +"civilization.museum", +"civilwar.museum", +"clinton.museum", +"clock.museum", +"coal.museum", +"coastaldefence.museum", +"cody.museum", +"coldwar.museum", +"collection.museum", +"colonialwilliamsburg.museum", +"coloradoplateau.museum", +"columbia.museum", +"columbus.museum", +"communication.museum", +"communications.museum", +"community.museum", +"computer.museum", +"computerhistory.museum", +"comunicações.museum", +"contemporary.museum", +"contemporaryart.museum", +"convent.museum", +"copenhagen.museum", +"corporation.museum", +"correios-e-telecomunicações.museum", +"corvette.museum", +"costume.museum", +"countryestate.museum", +"county.museum", +"crafts.museum", +"cranbrook.museum", +"creation.museum", +"cultural.museum", +"culturalcenter.museum", +"culture.museum", +"cyber.museum", +"cymru.museum", +"dali.museum", +"dallas.museum", +"database.museum", +"ddr.museum", +"decorativearts.museum", +"delaware.museum", +"delmenhorst.museum", +"denmark.museum", +"depot.museum", +"design.museum", +"detroit.museum", +"dinosaur.museum", +"discovery.museum", +"dolls.museum", +"donostia.museum", +"durham.museum", +"eastafrica.museum", +"eastcoast.museum", +"education.museum", +"educational.museum", +"egyptian.museum", +"eisenbahn.museum", +"elburg.museum", +"elvendrell.museum", +"embroidery.museum", +"encyclopedic.museum", +"england.museum", +"entomology.museum", +"environment.museum", +"environmentalconservation.museum", +"epilepsy.museum", +"essex.museum", +"estate.museum", +"ethnology.museum", +"exeter.museum", +"exhibition.museum", +"family.museum", +"farm.museum", +"farmequipment.museum", +"farmers.museum", +"farmstead.museum", +"field.museum", +"figueres.museum", +"filatelia.museum", +"film.museum", +"fineart.museum", +"finearts.museum", +"finland.museum", +"flanders.museum", +"florida.museum", +"force.museum", +"fortmissoula.museum", +"fortworth.museum", +"foundation.museum", +"francaise.museum", +"frankfurt.museum", +"franziskaner.museum", +"freemasonry.museum", +"freiburg.museum", +"fribourg.museum", +"frog.museum", +"fundacio.museum", +"furniture.museum", +"gallery.museum", +"garden.museum", +"gateway.museum", +"geelvinck.museum", +"gemological.museum", +"geology.museum", +"georgia.museum", +"giessen.museum", +"glas.museum", +"glass.museum", +"gorge.museum", +"grandrapids.museum", +"graz.museum", +"guernsey.museum", +"halloffame.museum", +"hamburg.museum", +"handson.museum", +"harvestcelebration.museum", +"hawaii.museum", +"health.museum", +"heimatunduhren.museum", +"hellas.museum", +"helsinki.museum", +"hembygdsforbund.museum", +"heritage.museum", +"histoire.museum", +"historical.museum", +"historicalsociety.museum", +"historichouses.museum", +"historisch.museum", +"historisches.museum", +"history.museum", +"historyofscience.museum", +"horology.museum", +"house.museum", +"humanities.museum", +"illustration.museum", +"imageandsound.museum", +"indian.museum", +"indiana.museum", +"indianapolis.museum", +"indianmarket.museum", +"intelligence.museum", +"interactive.museum", +"iraq.museum", +"iron.museum", +"isleofman.museum", +"jamison.museum", +"jefferson.museum", +"jerusalem.museum", +"jewelry.museum", +"jewish.museum", +"jewishart.museum", +"jfk.museum", +"journalism.museum", +"judaica.museum", +"judygarland.museum", +"juedisches.museum", +"juif.museum", +"karate.museum", +"karikatur.museum", +"kids.museum", +"koebenhavn.museum", +"koeln.museum", +"kunst.museum", +"kunstsammlung.museum", +"kunstunddesign.museum", +"labor.museum", +"labour.museum", +"lajolla.museum", +"lancashire.museum", +"landes.museum", +"lans.museum", +"läns.museum", +"larsson.museum", +"lewismiller.museum", +"lincoln.museum", +"linz.museum", +"living.museum", +"livinghistory.museum", +"localhistory.museum", +"london.museum", +"losangeles.museum", +"louvre.museum", +"loyalist.museum", +"lucerne.museum", +"luxembourg.museum", +"luzern.museum", +"mad.museum", +"madrid.museum", +"mallorca.museum", +"manchester.museum", +"mansion.museum", +"mansions.museum", +"manx.museum", +"marburg.museum", +"maritime.museum", +"maritimo.museum", +"maryland.museum", +"marylhurst.museum", +"media.museum", +"medical.museum", +"medizinhistorisches.museum", +"meeres.museum", +"memorial.museum", +"mesaverde.museum", +"michigan.museum", +"midatlantic.museum", +"military.museum", +"mill.museum", +"miners.museum", +"mining.museum", +"minnesota.museum", +"missile.museum", +"missoula.museum", +"modern.museum", +"moma.museum", +"money.museum", +"monmouth.museum", +"monticello.museum", +"montreal.museum", +"moscow.museum", +"motorcycle.museum", +"muenchen.museum", +"muenster.museum", +"mulhouse.museum", +"muncie.museum", +"museet.museum", +"museumcenter.museum", +"museumvereniging.museum", +"music.museum", +"national.museum", +"nationalfirearms.museum", +"nationalheritage.museum", +"nativeamerican.museum", +"naturalhistory.museum", +"naturalhistorymuseum.museum", +"naturalsciences.museum", +"nature.museum", +"naturhistorisches.museum", +"natuurwetenschappen.museum", +"naumburg.museum", +"naval.museum", +"nebraska.museum", +"neues.museum", +"newhampshire.museum", +"newjersey.museum", +"newmexico.museum", +"newport.museum", +"newspaper.museum", +"newyork.museum", +"niepce.museum", +"norfolk.museum", +"north.museum", +"nrw.museum", +"nyc.museum", +"nyny.museum", +"oceanographic.museum", +"oceanographique.museum", +"omaha.museum", +"online.museum", +"ontario.museum", +"openair.museum", +"oregon.museum", +"oregontrail.museum", +"otago.museum", +"oxford.museum", +"pacific.museum", +"paderborn.museum", +"palace.museum", +"paleo.museum", +"palmsprings.museum", +"panama.museum", +"paris.museum", +"pasadena.museum", +"pharmacy.museum", +"philadelphia.museum", +"philadelphiaarea.museum", +"philately.museum", +"phoenix.museum", +"photography.museum", +"pilots.museum", +"pittsburgh.museum", +"planetarium.museum", +"plantation.museum", +"plants.museum", +"plaza.museum", +"portal.museum", +"portland.museum", +"portlligat.museum", +"posts-and-telecommunications.museum", +"preservation.museum", +"presidio.museum", +"press.museum", +"project.museum", +"public.museum", +"pubol.museum", +"quebec.museum", +"railroad.museum", +"railway.museum", +"research.museum", +"resistance.museum", +"riodejaneiro.museum", +"rochester.museum", +"rockart.museum", +"roma.museum", +"russia.museum", +"saintlouis.museum", +"salem.museum", +"salvadordali.museum", +"salzburg.museum", +"sandiego.museum", +"sanfrancisco.museum", +"santabarbara.museum", +"santacruz.museum", +"santafe.museum", +"saskatchewan.museum", +"satx.museum", +"savannahga.museum", +"schlesisches.museum", +"schoenbrunn.museum", +"schokoladen.museum", +"school.museum", +"schweiz.museum", +"science.museum", +"scienceandhistory.museum", +"scienceandindustry.museum", +"sciencecenter.museum", +"sciencecenters.museum", +"science-fiction.museum", +"sciencehistory.museum", +"sciences.museum", +"sciencesnaturelles.museum", +"scotland.museum", +"seaport.museum", +"settlement.museum", +"settlers.museum", +"shell.museum", +"sherbrooke.museum", +"sibenik.museum", +"silk.museum", +"ski.museum", +"skole.museum", +"society.museum", +"sologne.museum", +"soundandvision.museum", +"southcarolina.museum", +"southwest.museum", +"space.museum", +"spy.museum", +"square.museum", +"stadt.museum", +"stalbans.museum", +"starnberg.museum", +"state.museum", +"stateofdelaware.museum", +"station.museum", +"steam.museum", +"steiermark.museum", +"stjohn.museum", +"stockholm.museum", +"stpetersburg.museum", +"stuttgart.museum", +"suisse.museum", +"surgeonshall.museum", +"surrey.museum", +"svizzera.museum", +"sweden.museum", +"sydney.museum", +"tank.museum", +"tcm.museum", +"technology.museum", +"telekommunikation.museum", +"television.museum", +"texas.museum", +"textile.museum", +"theater.museum", +"time.museum", +"timekeeping.museum", +"topology.museum", +"torino.museum", +"touch.museum", +"town.museum", +"transport.museum", +"tree.museum", +"trolley.museum", +"trust.museum", +"trustee.museum", +"uhren.museum", +"ulm.museum", +"undersea.museum", +"university.museum", +"usa.museum", +"usantiques.museum", +"usarts.museum", +"uscountryestate.museum", +"usculture.museum", +"usdecorativearts.museum", +"usgarden.museum", +"ushistory.museum", +"ushuaia.museum", +"uslivinghistory.museum", +"utah.museum", +"uvic.museum", +"valley.museum", +"vantaa.museum", +"versailles.museum", +"viking.museum", +"village.museum", +"virginia.museum", +"virtual.museum", +"virtuel.museum", +"vlaanderen.museum", +"volkenkunde.museum", +"wales.museum", +"wallonie.museum", +"war.museum", +"washingtondc.museum", +"watchandclock.museum", +"watch-and-clock.museum", +"western.museum", +"westfalen.museum", +"whaling.museum", +"wildlife.museum", +"williamsburg.museum", +"windmill.museum", +"workshop.museum", +"york.museum", +"yorkshire.museum", +"yosemite.museum", +"youth.museum", +"zoological.museum", +"zoology.museum", +"ירושלים.museum", +"иком.museum", +"mv", +"aero.mv", +"biz.mv", +"com.mv", +"coop.mv", +"edu.mv", +"gov.mv", +"info.mv", +"int.mv", +"mil.mv", +"museum.mv", +"name.mv", +"net.mv", +"org.mv", +"pro.mv", +"mw", +"ac.mw", +"biz.mw", +"co.mw", +"com.mw", +"coop.mw", +"edu.mw", +"gov.mw", +"int.mw", +"museum.mw", +"net.mw", +"org.mw", +"mx", +"com.mx", +"org.mx", +"gob.mx", +"edu.mx", +"net.mx", +"my", +"biz.my", +"com.my", +"edu.my", +"gov.my", +"mil.my", +"name.my", +"net.my", +"org.my", +"mz", +"ac.mz", +"adv.mz", +"co.mz", +"edu.mz", +"gov.mz", +"mil.mz", +"net.mz", +"org.mz", +"na", +"info.na", +"pro.na", +"name.na", +"school.na", +"or.na", +"dr.na", +"us.na", +"mx.na", +"ca.na", +"in.na", +"cc.na", +"tv.na", +"ws.na", +"mobi.na", +"co.na", +"com.na", +"org.na", +"name", +"nc", +"asso.nc", +"nom.nc", +"ne", +"net", +"nf", +"com.nf", +"net.nf", +"per.nf", +"rec.nf", +"web.nf", +"arts.nf", +"firm.nf", +"info.nf", +"other.nf", +"store.nf", +"ng", +"com.ng", +"edu.ng", +"gov.ng", +"i.ng", +"mil.ng", +"mobi.ng", +"name.ng", +"net.ng", +"org.ng", +"sch.ng", +"ni", +"ac.ni", +"biz.ni", +"co.ni", +"com.ni", +"edu.ni", +"gob.ni", +"in.ni", +"info.ni", +"int.ni", +"mil.ni", +"net.ni", +"nom.ni", +"org.ni", +"web.ni", +"nl", +"no", +"fhs.no", +"vgs.no", +"fylkesbibl.no", +"folkebibl.no", +"museum.no", +"idrett.no", +"priv.no", +"mil.no", +"stat.no", +"dep.no", +"kommune.no", +"herad.no", +"aa.no", +"ah.no", +"bu.no", +"fm.no", +"hl.no", +"hm.no", +"jan-mayen.no", +"mr.no", +"nl.no", +"nt.no", +"of.no", +"ol.no", +"oslo.no", +"rl.no", +"sf.no", +"st.no", +"svalbard.no", +"tm.no", +"tr.no", +"va.no", +"vf.no", +"gs.aa.no", +"gs.ah.no", +"gs.bu.no", +"gs.fm.no", +"gs.hl.no", +"gs.hm.no", +"gs.jan-mayen.no", +"gs.mr.no", +"gs.nl.no", +"gs.nt.no", +"gs.of.no", +"gs.ol.no", +"gs.oslo.no", +"gs.rl.no", +"gs.sf.no", +"gs.st.no", +"gs.svalbard.no", +"gs.tm.no", +"gs.tr.no", +"gs.va.no", +"gs.vf.no", +"akrehamn.no", +"åkrehamn.no", +"algard.no", +"ålgård.no", +"arna.no", +"brumunddal.no", +"bryne.no", +"bronnoysund.no", +"brønnøysund.no", +"drobak.no", +"drøbak.no", +"egersund.no", +"fetsund.no", +"floro.no", +"florø.no", +"fredrikstad.no", +"hokksund.no", +"honefoss.no", +"hønefoss.no", +"jessheim.no", +"jorpeland.no", +"jørpeland.no", +"kirkenes.no", +"kopervik.no", +"krokstadelva.no", +"langevag.no", +"langevåg.no", +"leirvik.no", +"mjondalen.no", +"mjøndalen.no", +"mo-i-rana.no", +"mosjoen.no", +"mosjøen.no", +"nesoddtangen.no", +"orkanger.no", +"osoyro.no", +"osøyro.no", +"raholt.no", +"råholt.no", +"sandnessjoen.no", +"sandnessjøen.no", +"skedsmokorset.no", +"slattum.no", +"spjelkavik.no", +"stathelle.no", +"stavern.no", +"stjordalshalsen.no", +"stjørdalshalsen.no", +"tananger.no", +"tranby.no", +"vossevangen.no", +"afjord.no", +"åfjord.no", +"agdenes.no", +"al.no", +"ål.no", +"alesund.no", +"ålesund.no", +"alstahaug.no", +"alta.no", +"áltá.no", +"alaheadju.no", +"álaheadju.no", +"alvdal.no", +"amli.no", +"åmli.no", +"amot.no", +"åmot.no", +"andebu.no", +"andoy.no", +"andøy.no", +"andasuolo.no", +"ardal.no", +"årdal.no", +"aremark.no", +"arendal.no", +"ås.no", +"aseral.no", +"åseral.no", +"asker.no", +"askim.no", +"askvoll.no", +"askoy.no", +"askøy.no", +"asnes.no", +"åsnes.no", +"audnedaln.no", +"aukra.no", +"aure.no", +"aurland.no", +"aurskog-holand.no", +"aurskog-høland.no", +"austevoll.no", +"austrheim.no", +"averoy.no", +"averøy.no", +"balestrand.no", +"ballangen.no", +"balat.no", +"bálát.no", +"balsfjord.no", +"bahccavuotna.no", +"báhccavuotna.no", +"bamble.no", +"bardu.no", +"beardu.no", +"beiarn.no", +"bajddar.no", +"bájddar.no", +"baidar.no", +"báidár.no", +"berg.no", +"bergen.no", +"berlevag.no", +"berlevåg.no", +"bearalvahki.no", +"bearalváhki.no", +"bindal.no", +"birkenes.no", +"bjarkoy.no", +"bjarkøy.no", +"bjerkreim.no", +"bjugn.no", +"bodo.no", +"bodø.no", +"badaddja.no", +"bådåddjå.no", +"budejju.no", +"bokn.no", +"bremanger.no", +"bronnoy.no", +"brønnøy.no", +"bygland.no", +"bykle.no", +"barum.no", +"bærum.no", +"bo.telemark.no", +"bø.telemark.no", +"bo.nordland.no", +"bø.nordland.no", +"bievat.no", +"bievát.no", +"bomlo.no", +"bømlo.no", +"batsfjord.no", +"båtsfjord.no", +"bahcavuotna.no", +"báhcavuotna.no", +"dovre.no", +"drammen.no", +"drangedal.no", +"dyroy.no", +"dyrøy.no", +"donna.no", +"dønna.no", +"eid.no", +"eidfjord.no", +"eidsberg.no", +"eidskog.no", +"eidsvoll.no", +"eigersund.no", +"elverum.no", +"enebakk.no", +"engerdal.no", +"etne.no", +"etnedal.no", +"evenes.no", +"evenassi.no", +"evenášši.no", +"evje-og-hornnes.no", +"farsund.no", +"fauske.no", +"fuossko.no", +"fuoisku.no", +"fedje.no", +"fet.no", +"finnoy.no", +"finnøy.no", +"fitjar.no", +"fjaler.no", +"fjell.no", +"flakstad.no", +"flatanger.no", +"flekkefjord.no", +"flesberg.no", +"flora.no", +"fla.no", +"flå.no", +"folldal.no", +"forsand.no", +"fosnes.no", +"frei.no", +"frogn.no", +"froland.no", +"frosta.no", +"frana.no", +"fræna.no", +"froya.no", +"frøya.no", +"fusa.no", +"fyresdal.no", +"forde.no", +"førde.no", +"gamvik.no", +"gangaviika.no", +"gáŋgaviika.no", +"gaular.no", +"gausdal.no", +"gildeskal.no", +"gildeskål.no", +"giske.no", +"gjemnes.no", +"gjerdrum.no", +"gjerstad.no", +"gjesdal.no", +"gjovik.no", +"gjøvik.no", +"gloppen.no", +"gol.no", +"gran.no", +"grane.no", +"granvin.no", +"gratangen.no", +"grimstad.no", +"grong.no", +"kraanghke.no", +"kråanghke.no", +"grue.no", +"gulen.no", +"hadsel.no", +"halden.no", +"halsa.no", +"hamar.no", +"hamaroy.no", +"habmer.no", +"hábmer.no", +"hapmir.no", +"hápmir.no", +"hammerfest.no", +"hammarfeasta.no", +"hámmárfeasta.no", +"haram.no", +"hareid.no", +"harstad.no", +"hasvik.no", +"aknoluokta.no", +"ákŋoluokta.no", +"hattfjelldal.no", +"aarborte.no", +"haugesund.no", +"hemne.no", +"hemnes.no", +"hemsedal.no", +"heroy.more-og-romsdal.no", +"herøy.møre-og-romsdal.no", +"heroy.nordland.no", +"herøy.nordland.no", +"hitra.no", +"hjartdal.no", +"hjelmeland.no", +"hobol.no", +"hobøl.no", +"hof.no", +"hol.no", +"hole.no", +"holmestrand.no", +"holtalen.no", +"holtålen.no", +"hornindal.no", +"horten.no", +"hurdal.no", +"hurum.no", +"hvaler.no", +"hyllestad.no", +"hagebostad.no", +"hægebostad.no", +"hoyanger.no", +"høyanger.no", +"hoylandet.no", +"høylandet.no", +"ha.no", +"hå.no", +"ibestad.no", +"inderoy.no", +"inderøy.no", +"iveland.no", +"jevnaker.no", +"jondal.no", +"jolster.no", +"jølster.no", +"karasjok.no", +"karasjohka.no", +"kárášjohka.no", +"karlsoy.no", +"galsa.no", +"gálsá.no", +"karmoy.no", +"karmøy.no", +"kautokeino.no", +"guovdageaidnu.no", +"klepp.no", +"klabu.no", +"klæbu.no", +"kongsberg.no", +"kongsvinger.no", +"kragero.no", +"kragerø.no", +"kristiansand.no", +"kristiansund.no", +"krodsherad.no", +"krødsherad.no", +"kvalsund.no", +"rahkkeravju.no", +"ráhkkerávju.no", +"kvam.no", +"kvinesdal.no", +"kvinnherad.no", +"kviteseid.no", +"kvitsoy.no", +"kvitsøy.no", +"kvafjord.no", +"kvæfjord.no", +"giehtavuoatna.no", +"kvanangen.no", +"kvænangen.no", +"navuotna.no", +"návuotna.no", +"kafjord.no", +"kåfjord.no", +"gaivuotna.no", +"gáivuotna.no", +"larvik.no", +"lavangen.no", +"lavagis.no", +"loabat.no", +"loabát.no", +"lebesby.no", +"davvesiida.no", +"leikanger.no", +"leirfjord.no", +"leka.no", +"leksvik.no", +"lenvik.no", +"leangaviika.no", +"leaŋgaviika.no", +"lesja.no", +"levanger.no", +"lier.no", +"lierne.no", +"lillehammer.no", +"lillesand.no", +"lindesnes.no", +"lindas.no", +"lindås.no", +"lom.no", +"loppa.no", +"lahppi.no", +"láhppi.no", +"lund.no", +"lunner.no", +"luroy.no", +"lurøy.no", +"luster.no", +"lyngdal.no", +"lyngen.no", +"ivgu.no", +"lardal.no", +"lerdal.no", +"lærdal.no", +"lodingen.no", +"lødingen.no", +"lorenskog.no", +"lørenskog.no", +"loten.no", +"løten.no", +"malvik.no", +"masoy.no", +"måsøy.no", +"muosat.no", +"muosát.no", +"mandal.no", +"marker.no", +"marnardal.no", +"masfjorden.no", +"meland.no", +"meldal.no", +"melhus.no", +"meloy.no", +"meløy.no", +"meraker.no", +"meråker.no", +"moareke.no", +"moåreke.no", +"midsund.no", +"midtre-gauldal.no", +"modalen.no", +"modum.no", +"molde.no", +"moskenes.no", +"moss.no", +"mosvik.no", +"malselv.no", +"målselv.no", +"malatvuopmi.no", +"málatvuopmi.no", +"namdalseid.no", +"aejrie.no", +"namsos.no", +"namsskogan.no", +"naamesjevuemie.no", +"nååmesjevuemie.no", +"laakesvuemie.no", +"nannestad.no", +"narvik.no", +"narviika.no", +"naustdal.no", +"nedre-eiker.no", +"nes.akershus.no", +"nes.buskerud.no", +"nesna.no", +"nesodden.no", +"nesseby.no", +"unjarga.no", +"unjárga.no", +"nesset.no", +"nissedal.no", +"nittedal.no", +"nord-aurdal.no", +"nord-fron.no", +"nord-odal.no", +"norddal.no", +"nordkapp.no", +"davvenjarga.no", +"davvenjárga.no", +"nordre-land.no", +"nordreisa.no", +"raisa.no", +"ráisa.no", +"nore-og-uvdal.no", +"notodden.no", +"naroy.no", +"nærøy.no", +"notteroy.no", +"nøtterøy.no", +"odda.no", +"oksnes.no", +"øksnes.no", +"oppdal.no", +"oppegard.no", +"oppegård.no", +"orkdal.no", +"orland.no", +"ørland.no", +"orskog.no", +"ørskog.no", +"orsta.no", +"ørsta.no", +"os.hedmark.no", +"os.hordaland.no", +"osen.no", +"osteroy.no", +"osterøy.no", +"ostre-toten.no", +"østre-toten.no", +"overhalla.no", +"ovre-eiker.no", +"øvre-eiker.no", +"oyer.no", +"øyer.no", +"oygarden.no", +"øygarden.no", +"oystre-slidre.no", +"øystre-slidre.no", +"porsanger.no", +"porsangu.no", +"porsáŋgu.no", +"porsgrunn.no", +"radoy.no", +"radøy.no", +"rakkestad.no", +"rana.no", +"ruovat.no", +"randaberg.no", +"rauma.no", +"rendalen.no", +"rennebu.no", +"rennesoy.no", +"rennesøy.no", +"rindal.no", +"ringebu.no", +"ringerike.no", +"ringsaker.no", +"rissa.no", +"risor.no", +"risør.no", +"roan.no", +"rollag.no", +"rygge.no", +"ralingen.no", +"rælingen.no", +"rodoy.no", +"rødøy.no", +"romskog.no", +"rømskog.no", +"roros.no", +"røros.no", +"rost.no", +"røst.no", +"royken.no", +"røyken.no", +"royrvik.no", +"røyrvik.no", +"rade.no", +"råde.no", +"salangen.no", +"siellak.no", +"saltdal.no", +"salat.no", +"sálát.no", +"sálat.no", +"samnanger.no", +"sande.more-og-romsdal.no", +"sande.møre-og-romsdal.no", +"sande.vestfold.no", +"sandefjord.no", +"sandnes.no", +"sandoy.no", +"sandøy.no", +"sarpsborg.no", +"sauda.no", +"sauherad.no", +"sel.no", +"selbu.no", +"selje.no", +"seljord.no", +"sigdal.no", +"siljan.no", +"sirdal.no", +"skaun.no", +"skedsmo.no", +"ski.no", +"skien.no", +"skiptvet.no", +"skjervoy.no", +"skjervøy.no", +"skierva.no", +"skiervá.no", +"skjak.no", +"skjåk.no", +"skodje.no", +"skanland.no", +"skånland.no", +"skanit.no", +"skánit.no", +"smola.no", +"smøla.no", +"snillfjord.no", +"snasa.no", +"snåsa.no", +"snoasa.no", +"snaase.no", +"snåase.no", +"sogndal.no", +"sokndal.no", +"sola.no", +"solund.no", +"songdalen.no", +"sortland.no", +"spydeberg.no", +"stange.no", +"stavanger.no", +"steigen.no", +"steinkjer.no", +"stjordal.no", +"stjørdal.no", +"stokke.no", +"stor-elvdal.no", +"stord.no", +"stordal.no", +"storfjord.no", +"omasvuotna.no", +"strand.no", +"stranda.no", +"stryn.no", +"sula.no", +"suldal.no", +"sund.no", +"sunndal.no", +"surnadal.no", +"sveio.no", +"svelvik.no", +"sykkylven.no", +"sogne.no", +"søgne.no", +"somna.no", +"sømna.no", +"sondre-land.no", +"søndre-land.no", +"sor-aurdal.no", +"sør-aurdal.no", +"sor-fron.no", +"sør-fron.no", +"sor-odal.no", +"sør-odal.no", +"sor-varanger.no", +"sør-varanger.no", +"matta-varjjat.no", +"mátta-várjjat.no", +"sorfold.no", +"sørfold.no", +"sorreisa.no", +"sørreisa.no", +"sorum.no", +"sørum.no", +"tana.no", +"deatnu.no", +"time.no", +"tingvoll.no", +"tinn.no", +"tjeldsund.no", +"dielddanuorri.no", +"tjome.no", +"tjøme.no", +"tokke.no", +"tolga.no", +"torsken.no", +"tranoy.no", +"tranøy.no", +"tromso.no", +"tromsø.no", +"tromsa.no", +"romsa.no", +"trondheim.no", +"troandin.no", +"trysil.no", +"trana.no", +"træna.no", +"trogstad.no", +"trøgstad.no", +"tvedestrand.no", +"tydal.no", +"tynset.no", +"tysfjord.no", +"divtasvuodna.no", +"divttasvuotna.no", +"tysnes.no", +"tysvar.no", +"tysvær.no", +"tonsberg.no", +"tønsberg.no", +"ullensaker.no", +"ullensvang.no", +"ulvik.no", +"utsira.no", +"vadso.no", +"vadsø.no", +"cahcesuolo.no", +"čáhcesuolo.no", +"vaksdal.no", +"valle.no", +"vang.no", +"vanylven.no", +"vardo.no", +"vardø.no", +"varggat.no", +"várggát.no", +"vefsn.no", +"vaapste.no", +"vega.no", +"vegarshei.no", +"vegårshei.no", +"vennesla.no", +"verdal.no", +"verran.no", +"vestby.no", +"vestnes.no", +"vestre-slidre.no", +"vestre-toten.no", +"vestvagoy.no", +"vestvågøy.no", +"vevelstad.no", +"vik.no", +"vikna.no", +"vindafjord.no", +"volda.no", +"voss.no", +"varoy.no", +"værøy.no", +"vagan.no", +"vågan.no", +"voagat.no", +"vagsoy.no", +"vågsøy.no", +"vaga.no", +"vågå.no", +"valer.ostfold.no", +"våler.østfold.no", +"valer.hedmark.no", +"våler.hedmark.no", +"*.np", +"nr", +"biz.nr", +"info.nr", +"gov.nr", +"edu.nr", +"org.nr", +"net.nr", +"com.nr", +"nu", +"nz", +"ac.nz", +"co.nz", +"cri.nz", +"geek.nz", +"gen.nz", +"govt.nz", +"health.nz", +"iwi.nz", +"kiwi.nz", +"maori.nz", +"mil.nz", +"māori.nz", +"net.nz", +"org.nz", +"parliament.nz", +"school.nz", +"om", +"co.om", +"com.om", +"edu.om", +"gov.om", +"med.om", +"museum.om", +"net.om", +"org.om", +"pro.om", +"onion", +"org", +"pa", +"ac.pa", +"gob.pa", +"com.pa", +"org.pa", +"sld.pa", +"edu.pa", +"net.pa", +"ing.pa", +"abo.pa", +"med.pa", +"nom.pa", +"pe", +"edu.pe", +"gob.pe", +"nom.pe", +"mil.pe", +"org.pe", +"com.pe", +"net.pe", +"pf", +"com.pf", +"org.pf", +"edu.pf", +"*.pg", +"ph", +"com.ph", +"net.ph", +"org.ph", +"gov.ph", +"edu.ph", +"ngo.ph", +"mil.ph", +"i.ph", +"pk", +"com.pk", +"net.pk", +"edu.pk", +"org.pk", +"fam.pk", +"biz.pk", +"web.pk", +"gov.pk", +"gob.pk", +"gok.pk", +"gon.pk", +"gop.pk", +"gos.pk", +"info.pk", +"pl", +"com.pl", +"net.pl", +"org.pl", +"aid.pl", +"agro.pl", +"atm.pl", +"auto.pl", +"biz.pl", +"edu.pl", +"gmina.pl", +"gsm.pl", +"info.pl", +"mail.pl", +"miasta.pl", +"media.pl", +"mil.pl", +"nieruchomosci.pl", +"nom.pl", +"pc.pl", +"powiat.pl", +"priv.pl", +"realestate.pl", +"rel.pl", +"sex.pl", +"shop.pl", +"sklep.pl", +"sos.pl", +"szkola.pl", +"targi.pl", +"tm.pl", +"tourism.pl", +"travel.pl", +"turystyka.pl", +"gov.pl", +"ap.gov.pl", +"ic.gov.pl", +"is.gov.pl", +"us.gov.pl", +"kmpsp.gov.pl", +"kppsp.gov.pl", +"kwpsp.gov.pl", +"psp.gov.pl", +"wskr.gov.pl", +"kwp.gov.pl", +"mw.gov.pl", +"ug.gov.pl", +"um.gov.pl", +"umig.gov.pl", +"ugim.gov.pl", +"upow.gov.pl", +"uw.gov.pl", +"starostwo.gov.pl", +"pa.gov.pl", +"po.gov.pl", +"psse.gov.pl", +"pup.gov.pl", +"rzgw.gov.pl", +"sa.gov.pl", +"so.gov.pl", +"sr.gov.pl", +"wsa.gov.pl", +"sko.gov.pl", +"uzs.gov.pl", +"wiih.gov.pl", +"winb.gov.pl", +"pinb.gov.pl", +"wios.gov.pl", +"witd.gov.pl", +"wzmiuw.gov.pl", +"piw.gov.pl", +"wiw.gov.pl", +"griw.gov.pl", +"wif.gov.pl", +"oum.gov.pl", +"sdn.gov.pl", +"zp.gov.pl", +"uppo.gov.pl", +"mup.gov.pl", +"wuoz.gov.pl", +"konsulat.gov.pl", +"oirm.gov.pl", +"augustow.pl", +"babia-gora.pl", +"bedzin.pl", +"beskidy.pl", +"bialowieza.pl", +"bialystok.pl", +"bielawa.pl", +"bieszczady.pl", +"boleslawiec.pl", +"bydgoszcz.pl", +"bytom.pl", +"cieszyn.pl", +"czeladz.pl", +"czest.pl", +"dlugoleka.pl", +"elblag.pl", +"elk.pl", +"glogow.pl", +"gniezno.pl", +"gorlice.pl", +"grajewo.pl", +"ilawa.pl", +"jaworzno.pl", +"jelenia-gora.pl", +"jgora.pl", +"kalisz.pl", +"kazimierz-dolny.pl", +"karpacz.pl", +"kartuzy.pl", +"kaszuby.pl", +"katowice.pl", +"kepno.pl", +"ketrzyn.pl", +"klodzko.pl", +"kobierzyce.pl", +"kolobrzeg.pl", +"konin.pl", +"konskowola.pl", +"kutno.pl", +"lapy.pl", +"lebork.pl", +"legnica.pl", +"lezajsk.pl", +"limanowa.pl", +"lomza.pl", +"lowicz.pl", +"lubin.pl", +"lukow.pl", +"malbork.pl", +"malopolska.pl", +"mazowsze.pl", +"mazury.pl", +"mielec.pl", +"mielno.pl", +"mragowo.pl", +"naklo.pl", +"nowaruda.pl", +"nysa.pl", +"olawa.pl", +"olecko.pl", +"olkusz.pl", +"olsztyn.pl", +"opoczno.pl", +"opole.pl", +"ostroda.pl", +"ostroleka.pl", +"ostrowiec.pl", +"ostrowwlkp.pl", +"pila.pl", +"pisz.pl", +"podhale.pl", +"podlasie.pl", +"polkowice.pl", +"pomorze.pl", +"pomorskie.pl", +"prochowice.pl", +"pruszkow.pl", +"przeworsk.pl", +"pulawy.pl", +"radom.pl", +"rawa-maz.pl", +"rybnik.pl", +"rzeszow.pl", +"sanok.pl", +"sejny.pl", +"slask.pl", +"slupsk.pl", +"sosnowiec.pl", +"stalowa-wola.pl", +"skoczow.pl", +"starachowice.pl", +"stargard.pl", +"suwalki.pl", +"swidnica.pl", +"swiebodzin.pl", +"swinoujscie.pl", +"szczecin.pl", +"szczytno.pl", +"tarnobrzeg.pl", +"tgory.pl", +"turek.pl", +"tychy.pl", +"ustka.pl", +"walbrzych.pl", +"warmia.pl", +"warszawa.pl", +"waw.pl", +"wegrow.pl", +"wielun.pl", +"wlocl.pl", +"wloclawek.pl", +"wodzislaw.pl", +"wolomin.pl", +"wroclaw.pl", +"zachpomor.pl", +"zagan.pl", +"zarow.pl", +"zgora.pl", +"zgorzelec.pl", +"pm", +"pn", +"gov.pn", +"co.pn", +"org.pn", +"edu.pn", +"net.pn", +"post", +"pr", +"com.pr", +"net.pr", +"org.pr", +"gov.pr", +"edu.pr", +"isla.pr", +"pro.pr", +"biz.pr", +"info.pr", +"name.pr", +"est.pr", +"prof.pr", +"ac.pr", +"pro", +"aaa.pro", +"aca.pro", +"acct.pro", +"avocat.pro", +"bar.pro", +"cpa.pro", +"eng.pro", +"jur.pro", +"law.pro", +"med.pro", +"recht.pro", +"ps", +"edu.ps", +"gov.ps", +"sec.ps", +"plo.ps", +"com.ps", +"org.ps", +"net.ps", +"pt", +"net.pt", +"gov.pt", +"org.pt", +"edu.pt", +"int.pt", +"publ.pt", +"com.pt", +"nome.pt", +"pw", +"co.pw", +"ne.pw", +"or.pw", +"ed.pw", +"go.pw", +"belau.pw", +"py", +"com.py", +"coop.py", +"edu.py", +"gov.py", +"mil.py", +"net.py", +"org.py", +"qa", +"com.qa", +"edu.qa", +"gov.qa", +"mil.qa", +"name.qa", +"net.qa", +"org.qa", +"sch.qa", +"re", +"asso.re", +"com.re", +"nom.re", +"ro", +"arts.ro", +"com.ro", +"firm.ro", +"info.ro", +"nom.ro", +"nt.ro", +"org.ro", +"rec.ro", +"store.ro", +"tm.ro", +"www.ro", +"rs", +"ac.rs", +"co.rs", +"edu.rs", +"gov.rs", +"in.rs", +"org.rs", +"ru", +"rw", +"ac.rw", +"co.rw", +"coop.rw", +"gov.rw", +"mil.rw", +"net.rw", +"org.rw", +"sa", +"com.sa", +"net.sa", +"org.sa", +"gov.sa", +"med.sa", +"pub.sa", +"edu.sa", +"sch.sa", +"sb", +"com.sb", +"edu.sb", +"gov.sb", +"net.sb", +"org.sb", +"sc", +"com.sc", +"gov.sc", +"net.sc", +"org.sc", +"edu.sc", +"sd", +"com.sd", +"net.sd", +"org.sd", +"edu.sd", +"med.sd", +"tv.sd", +"gov.sd", +"info.sd", +"se", +"a.se", +"ac.se", +"b.se", +"bd.se", +"brand.se", +"c.se", +"d.se", +"e.se", +"f.se", +"fh.se", +"fhsk.se", +"fhv.se", +"g.se", +"h.se", +"i.se", +"k.se", +"komforb.se", +"kommunalforbund.se", +"komvux.se", +"l.se", +"lanbib.se", +"m.se", +"n.se", +"naturbruksgymn.se", +"o.se", +"org.se", +"p.se", +"parti.se", +"pp.se", +"press.se", +"r.se", +"s.se", +"t.se", +"tm.se", +"u.se", +"w.se", +"x.se", +"y.se", +"z.se", +"sg", +"com.sg", +"net.sg", +"org.sg", +"gov.sg", +"edu.sg", +"per.sg", +"sh", +"com.sh", +"net.sh", +"gov.sh", +"org.sh", +"mil.sh", +"si", +"sj", +"sk", +"sl", +"com.sl", +"net.sl", +"edu.sl", +"gov.sl", +"org.sl", +"sm", +"sn", +"art.sn", +"com.sn", +"edu.sn", +"gouv.sn", +"org.sn", +"perso.sn", +"univ.sn", +"so", +"com.so", +"edu.so", +"gov.so", +"me.so", +"net.so", +"org.so", +"sr", +"ss", +"biz.ss", +"com.ss", +"edu.ss", +"gov.ss", +"me.ss", +"net.ss", +"org.ss", +"sch.ss", +"st", +"co.st", +"com.st", +"consulado.st", +"edu.st", +"embaixada.st", +"mil.st", +"net.st", +"org.st", +"principe.st", +"saotome.st", +"store.st", +"su", +"sv", +"com.sv", +"edu.sv", +"gob.sv", +"org.sv", +"red.sv", +"sx", +"gov.sx", +"sy", +"edu.sy", +"gov.sy", +"net.sy", +"mil.sy", +"com.sy", +"org.sy", +"sz", +"co.sz", +"ac.sz", +"org.sz", +"tc", +"td", +"tel", +"tf", +"tg", +"th", +"ac.th", +"co.th", +"go.th", +"in.th", +"mi.th", +"net.th", +"or.th", +"tj", +"ac.tj", +"biz.tj", +"co.tj", +"com.tj", +"edu.tj", +"go.tj", +"gov.tj", +"int.tj", +"mil.tj", +"name.tj", +"net.tj", +"nic.tj", +"org.tj", +"test.tj", +"web.tj", +"tk", +"tl", +"gov.tl", +"tm", +"com.tm", +"co.tm", +"org.tm", +"net.tm", +"nom.tm", +"gov.tm", +"mil.tm", +"edu.tm", +"tn", +"com.tn", +"ens.tn", +"fin.tn", +"gov.tn", +"ind.tn", +"info.tn", +"intl.tn", +"mincom.tn", +"nat.tn", +"net.tn", +"org.tn", +"perso.tn", +"tourism.tn", +"to", +"com.to", +"gov.to", +"net.to", +"org.to", +"edu.to", +"mil.to", +"tr", +"av.tr", +"bbs.tr", +"bel.tr", +"biz.tr", +"com.tr", +"dr.tr", +"edu.tr", +"gen.tr", +"gov.tr", +"info.tr", +"mil.tr", +"k12.tr", +"kep.tr", +"name.tr", +"net.tr", +"org.tr", +"pol.tr", +"tel.tr", +"tsk.tr", +"tv.tr", +"web.tr", +"nc.tr", +"gov.nc.tr", +"tt", +"co.tt", +"com.tt", +"org.tt", +"net.tt", +"biz.tt", +"info.tt", +"pro.tt", +"int.tt", +"coop.tt", +"jobs.tt", +"mobi.tt", +"travel.tt", +"museum.tt", +"aero.tt", +"name.tt", +"gov.tt", +"edu.tt", +"tv", +"tw", +"edu.tw", +"gov.tw", +"mil.tw", +"com.tw", +"net.tw", +"org.tw", +"idv.tw", +"game.tw", +"ebiz.tw", +"club.tw", +"網路.tw", +"組織.tw", +"商業.tw", +"tz", +"ac.tz", +"co.tz", +"go.tz", +"hotel.tz", +"info.tz", +"me.tz", +"mil.tz", +"mobi.tz", +"ne.tz", +"or.tz", +"sc.tz", +"tv.tz", +"ua", +"com.ua", +"edu.ua", +"gov.ua", +"in.ua", +"net.ua", +"org.ua", +"cherkassy.ua", +"cherkasy.ua", +"chernigov.ua", +"chernihiv.ua", +"chernivtsi.ua", +"chernovtsy.ua", +"ck.ua", +"cn.ua", +"cr.ua", +"crimea.ua", +"cv.ua", +"dn.ua", +"dnepropetrovsk.ua", +"dnipropetrovsk.ua", +"donetsk.ua", +"dp.ua", +"if.ua", +"ivano-frankivsk.ua", +"kh.ua", +"kharkiv.ua", +"kharkov.ua", +"kherson.ua", +"khmelnitskiy.ua", +"khmelnytskyi.ua", +"kiev.ua", +"kirovograd.ua", +"km.ua", +"kr.ua", +"krym.ua", +"ks.ua", +"kv.ua", +"kyiv.ua", +"lg.ua", +"lt.ua", +"lugansk.ua", +"lutsk.ua", +"lv.ua", +"lviv.ua", +"mk.ua", +"mykolaiv.ua", +"nikolaev.ua", +"od.ua", +"odesa.ua", +"odessa.ua", +"pl.ua", +"poltava.ua", +"rivne.ua", +"rovno.ua", +"rv.ua", +"sb.ua", +"sebastopol.ua", +"sevastopol.ua", +"sm.ua", +"sumy.ua", +"te.ua", +"ternopil.ua", +"uz.ua", +"uzhgorod.ua", +"vinnica.ua", +"vinnytsia.ua", +"vn.ua", +"volyn.ua", +"yalta.ua", +"zaporizhzhe.ua", +"zaporizhzhia.ua", +"zhitomir.ua", +"zhytomyr.ua", +"zp.ua", +"zt.ua", +"ug", +"co.ug", +"or.ug", +"ac.ug", +"sc.ug", +"go.ug", +"ne.ug", +"com.ug", +"org.ug", +"uk", +"ac.uk", +"co.uk", +"gov.uk", +"ltd.uk", +"me.uk", +"net.uk", +"nhs.uk", +"org.uk", +"plc.uk", +"police.uk", +"*.sch.uk", +"us", +"dni.us", +"fed.us", +"isa.us", +"kids.us", +"nsn.us", +"ak.us", +"al.us", +"ar.us", +"as.us", +"az.us", +"ca.us", +"co.us", +"ct.us", +"dc.us", +"de.us", +"fl.us", +"ga.us", +"gu.us", +"hi.us", +"ia.us", +"id.us", +"il.us", +"in.us", +"ks.us", +"ky.us", +"la.us", +"ma.us", +"md.us", +"me.us", +"mi.us", +"mn.us", +"mo.us", +"ms.us", +"mt.us", +"nc.us", +"nd.us", +"ne.us", +"nh.us", +"nj.us", +"nm.us", +"nv.us", +"ny.us", +"oh.us", +"ok.us", +"or.us", +"pa.us", +"pr.us", +"ri.us", +"sc.us", +"sd.us", +"tn.us", +"tx.us", +"ut.us", +"vi.us", +"vt.us", +"va.us", +"wa.us", +"wi.us", +"wv.us", +"wy.us", +"k12.ak.us", +"k12.al.us", +"k12.ar.us", +"k12.as.us", +"k12.az.us", +"k12.ca.us", +"k12.co.us", +"k12.ct.us", +"k12.dc.us", +"k12.de.us", +"k12.fl.us", +"k12.ga.us", +"k12.gu.us", +"k12.ia.us", +"k12.id.us", +"k12.il.us", +"k12.in.us", +"k12.ks.us", +"k12.ky.us", +"k12.la.us", +"k12.ma.us", +"k12.md.us", +"k12.me.us", +"k12.mi.us", +"k12.mn.us", +"k12.mo.us", +"k12.ms.us", +"k12.mt.us", +"k12.nc.us", +"k12.ne.us", +"k12.nh.us", +"k12.nj.us", +"k12.nm.us", +"k12.nv.us", +"k12.ny.us", +"k12.oh.us", +"k12.ok.us", +"k12.or.us", +"k12.pa.us", +"k12.pr.us", +"k12.sc.us", +"k12.tn.us", +"k12.tx.us", +"k12.ut.us", +"k12.vi.us", +"k12.vt.us", +"k12.va.us", +"k12.wa.us", +"k12.wi.us", +"k12.wy.us", +"cc.ak.us", +"cc.al.us", +"cc.ar.us", +"cc.as.us", +"cc.az.us", +"cc.ca.us", +"cc.co.us", +"cc.ct.us", +"cc.dc.us", +"cc.de.us", +"cc.fl.us", +"cc.ga.us", +"cc.gu.us", +"cc.hi.us", +"cc.ia.us", +"cc.id.us", +"cc.il.us", +"cc.in.us", +"cc.ks.us", +"cc.ky.us", +"cc.la.us", +"cc.ma.us", +"cc.md.us", +"cc.me.us", +"cc.mi.us", +"cc.mn.us", +"cc.mo.us", +"cc.ms.us", +"cc.mt.us", +"cc.nc.us", +"cc.nd.us", +"cc.ne.us", +"cc.nh.us", +"cc.nj.us", +"cc.nm.us", +"cc.nv.us", +"cc.ny.us", +"cc.oh.us", +"cc.ok.us", +"cc.or.us", +"cc.pa.us", +"cc.pr.us", +"cc.ri.us", +"cc.sc.us", +"cc.sd.us", +"cc.tn.us", +"cc.tx.us", +"cc.ut.us", +"cc.vi.us", +"cc.vt.us", +"cc.va.us", +"cc.wa.us", +"cc.wi.us", +"cc.wv.us", +"cc.wy.us", +"lib.ak.us", +"lib.al.us", +"lib.ar.us", +"lib.as.us", +"lib.az.us", +"lib.ca.us", +"lib.co.us", +"lib.ct.us", +"lib.dc.us", +"lib.fl.us", +"lib.ga.us", +"lib.gu.us", +"lib.hi.us", +"lib.ia.us", +"lib.id.us", +"lib.il.us", +"lib.in.us", +"lib.ks.us", +"lib.ky.us", +"lib.la.us", +"lib.ma.us", +"lib.md.us", +"lib.me.us", +"lib.mi.us", +"lib.mn.us", +"lib.mo.us", +"lib.ms.us", +"lib.mt.us", +"lib.nc.us", +"lib.nd.us", +"lib.ne.us", +"lib.nh.us", +"lib.nj.us", +"lib.nm.us", +"lib.nv.us", +"lib.ny.us", +"lib.oh.us", +"lib.ok.us", +"lib.or.us", +"lib.pa.us", +"lib.pr.us", +"lib.ri.us", +"lib.sc.us", +"lib.sd.us", +"lib.tn.us", +"lib.tx.us", +"lib.ut.us", +"lib.vi.us", +"lib.vt.us", +"lib.va.us", +"lib.wa.us", +"lib.wi.us", +"lib.wy.us", +"pvt.k12.ma.us", +"chtr.k12.ma.us", +"paroch.k12.ma.us", +"ann-arbor.mi.us", +"cog.mi.us", +"dst.mi.us", +"eaton.mi.us", +"gen.mi.us", +"mus.mi.us", +"tec.mi.us", +"washtenaw.mi.us", +"uy", +"com.uy", +"edu.uy", +"gub.uy", +"mil.uy", +"net.uy", +"org.uy", +"uz", +"co.uz", +"com.uz", +"net.uz", +"org.uz", +"va", +"vc", +"com.vc", +"net.vc", +"org.vc", +"gov.vc", +"mil.vc", +"edu.vc", +"ve", +"arts.ve", +"bib.ve", +"co.ve", +"com.ve", +"e12.ve", +"edu.ve", +"firm.ve", +"gob.ve", +"gov.ve", +"info.ve", +"int.ve", +"mil.ve", +"net.ve", +"nom.ve", +"org.ve", +"rar.ve", +"rec.ve", +"store.ve", +"tec.ve", +"web.ve", +"vg", +"vi", +"co.vi", +"com.vi", +"k12.vi", +"net.vi", +"org.vi", +"vn", +"com.vn", +"net.vn", +"org.vn", +"edu.vn", +"gov.vn", +"int.vn", +"ac.vn", +"biz.vn", +"info.vn", +"name.vn", +"pro.vn", +"health.vn", +"vu", +"com.vu", +"edu.vu", +"net.vu", +"org.vu", +"wf", +"ws", +"com.ws", +"net.ws", +"org.ws", +"gov.ws", +"edu.ws", +"yt", +"امارات", +"հայ", +"বাংলা", +"бг", +"البحرين", +"бел", +"中国", +"中國", +"الجزائر", +"مصر", +"ею", +"ευ", +"موريتانيا", +"გე", +"ελ", +"香港", +"公司.香港", +"教育.香港", +"政府.香港", +"個人.香港", +"網絡.香港", +"組織.香港", +"ಭಾರತ", +"ଭାରତ", +"ভাৰত", +"भारतम्", +"भारोत", +"ڀارت", +"ഭാരതം", +"भारत", +"بارت", +"بھارت", +"భారత్", +"ભારત", +"ਭਾਰਤ", +"ভারত", +"இந்தியா", +"ایران", +"ايران", +"عراق", +"الاردن", +"한국", +"қаз", +"ລາວ", +"ලංකා", +"இலங்கை", +"المغرب", +"мкд", +"мон", +"澳門", +"澳门", +"مليسيا", +"عمان", +"پاکستان", +"پاكستان", +"فلسطين", +"срб", +"пр.срб", +"орг.срб", +"обр.срб", +"од.срб", +"упр.срб", +"ак.срб", +"рф", +"قطر", +"السعودية", +"السعودیة", +"السعودیۃ", +"السعوديه", +"سودان", +"新加坡", +"சிங்கப்பூர்", +"سورية", +"سوريا", +"ไทย", +"ศึกษา.ไทย", +"ธุรกิจ.ไทย", +"รัฐบาล.ไทย", +"ทหาร.ไทย", +"เน็ต.ไทย", +"องค์กร.ไทย", +"تونس", +"台灣", +"台湾", +"臺灣", +"укр", +"اليمن", +"xxx", +"ye", +"com.ye", +"edu.ye", +"gov.ye", +"net.ye", +"mil.ye", +"org.ye", +"ac.za", +"agric.za", +"alt.za", +"co.za", +"edu.za", +"gov.za", +"grondar.za", +"law.za", +"mil.za", +"net.za", +"ngo.za", +"nic.za", +"nis.za", +"nom.za", +"org.za", +"school.za", +"tm.za", +"web.za", +"zm", +"ac.zm", +"biz.zm", +"co.zm", +"com.zm", +"edu.zm", +"gov.zm", +"info.zm", +"mil.zm", +"net.zm", +"org.zm", +"sch.zm", +"zw", +"ac.zw", +"co.zw", +"gov.zw", +"mil.zw", +"org.zw", +"aaa", +"aarp", +"abarth", +"abb", +"abbott", +"abbvie", +"abc", +"able", +"abogado", +"abudhabi", +"academy", +"accenture", +"accountant", +"accountants", +"aco", +"actor", +"adac", +"ads", +"adult", +"aeg", +"aetna", +"afl", +"africa", +"agakhan", +"agency", +"aig", +"airbus", +"airforce", +"airtel", +"akdn", +"alfaromeo", +"alibaba", +"alipay", +"allfinanz", +"allstate", +"ally", +"alsace", +"alstom", +"amazon", +"americanexpress", +"americanfamily", +"amex", +"amfam", +"amica", +"amsterdam", +"analytics", +"android", +"anquan", +"anz", +"aol", +"apartments", +"app", +"apple", +"aquarelle", +"arab", +"aramco", +"archi", +"army", +"art", +"arte", +"asda", +"associates", +"athleta", +"attorney", +"auction", +"audi", +"audible", +"audio", +"auspost", +"author", +"auto", +"autos", +"avianca", +"aws", +"axa", +"azure", +"baby", +"baidu", +"banamex", +"bananarepublic", +"band", +"bank", +"bar", +"barcelona", +"barclaycard", +"barclays", +"barefoot", +"bargains", +"baseball", +"basketball", +"bauhaus", +"bayern", +"bbc", +"bbt", +"bbva", +"bcg", +"bcn", +"beats", +"beauty", +"beer", +"bentley", +"berlin", +"best", +"bestbuy", +"bet", +"bharti", +"bible", +"bid", +"bike", +"bing", +"bingo", +"bio", +"black", +"blackfriday", +"blockbuster", +"blog", +"bloomberg", +"blue", +"bms", +"bmw", +"bnpparibas", +"boats", +"boehringer", +"bofa", +"bom", +"bond", +"boo", +"book", +"booking", +"bosch", +"bostik", +"boston", +"bot", +"boutique", +"box", +"bradesco", +"bridgestone", +"broadway", +"broker", +"brother", +"brussels", +"bugatti", +"build", +"builders", +"business", +"buy", +"buzz", +"bzh", +"cab", +"cafe", +"cal", +"call", +"calvinklein", +"cam", +"camera", +"camp", +"cancerresearch", +"canon", +"capetown", +"capital", +"capitalone", +"car", +"caravan", +"cards", +"care", +"career", +"careers", +"cars", +"casa", +"case", +"cash", +"casino", +"catering", +"catholic", +"cba", +"cbn", +"cbre", +"cbs", +"center", +"ceo", +"cern", +"cfa", +"cfd", +"chanel", +"channel", +"charity", +"chase", +"chat", +"cheap", +"chintai", +"christmas", +"chrome", +"church", +"cipriani", +"circle", +"cisco", +"citadel", +"citi", +"citic", +"city", +"cityeats", +"claims", +"cleaning", +"click", +"clinic", +"clinique", +"clothing", +"cloud", +"club", +"clubmed", +"coach", +"codes", +"coffee", +"college", +"cologne", +"comcast", +"commbank", +"community", +"company", +"compare", +"computer", +"comsec", +"condos", +"construction", +"consulting", +"contact", +"contractors", +"cooking", +"cookingchannel", +"cool", +"corsica", +"country", +"coupon", +"coupons", +"courses", +"cpa", +"credit", +"creditcard", +"creditunion", +"cricket", +"crown", +"crs", +"cruise", +"cruises", +"cuisinella", +"cymru", +"cyou", +"dabur", +"dad", +"dance", +"data", +"date", +"dating", +"datsun", +"day", +"dclk", +"dds", +"deal", +"dealer", +"deals", +"degree", +"delivery", +"dell", +"deloitte", +"delta", +"democrat", +"dental", +"dentist", +"desi", +"design", +"dev", +"dhl", +"diamonds", +"diet", +"digital", +"direct", +"directory", +"discount", +"discover", +"dish", +"diy", +"dnp", +"docs", +"doctor", +"dog", +"domains", +"dot", +"download", +"drive", +"dtv", +"dubai", +"dunlop", +"dupont", +"durban", +"dvag", +"dvr", +"earth", +"eat", +"eco", +"edeka", +"education", +"email", +"emerck", +"energy", +"engineer", +"engineering", +"enterprises", +"epson", +"equipment", +"ericsson", +"erni", +"esq", +"estate", +"etisalat", +"eurovision", +"eus", +"events", +"exchange", +"expert", +"exposed", +"express", +"extraspace", +"fage", +"fail", +"fairwinds", +"faith", +"family", +"fan", +"fans", +"farm", +"farmers", +"fashion", +"fast", +"fedex", +"feedback", +"ferrari", +"ferrero", +"fiat", +"fidelity", +"fido", +"film", +"final", +"finance", +"financial", +"fire", +"firestone", +"firmdale", +"fish", +"fishing", +"fit", +"fitness", +"flickr", +"flights", +"flir", +"florist", +"flowers", +"fly", +"foo", +"food", +"foodnetwork", +"football", +"ford", +"forex", +"forsale", +"forum", +"foundation", +"fox", +"free", +"fresenius", +"frl", +"frogans", +"frontdoor", +"frontier", +"ftr", +"fujitsu", +"fun", +"fund", +"furniture", +"futbol", +"fyi", +"gal", +"gallery", +"gallo", +"gallup", +"game", +"games", +"gap", +"garden", +"gay", +"gbiz", +"gdn", +"gea", +"gent", +"genting", +"george", +"ggee", +"gift", +"gifts", +"gives", +"giving", +"glass", +"gle", +"global", +"globo", +"gmail", +"gmbh", +"gmo", +"gmx", +"godaddy", +"gold", +"goldpoint", +"golf", +"goo", +"goodyear", +"goog", +"google", +"gop", +"got", +"grainger", +"graphics", +"gratis", +"green", +"gripe", +"grocery", +"group", +"guardian", +"gucci", +"guge", +"guide", +"guitars", +"guru", +"hair", +"hamburg", +"hangout", +"haus", +"hbo", +"hdfc", +"hdfcbank", +"health", +"healthcare", +"help", +"helsinki", +"here", +"hermes", +"hgtv", +"hiphop", +"hisamitsu", +"hitachi", +"hiv", +"hkt", +"hockey", +"holdings", +"holiday", +"homedepot", +"homegoods", +"homes", +"homesense", +"honda", +"horse", +"hospital", +"host", +"hosting", +"hot", +"hoteles", +"hotels", +"hotmail", +"house", +"how", +"hsbc", +"hughes", +"hyatt", +"hyundai", +"ibm", +"icbc", +"ice", +"icu", +"ieee", +"ifm", +"ikano", +"imamat", +"imdb", +"immo", +"immobilien", +"inc", +"industries", +"infiniti", +"ing", +"ink", +"institute", +"insurance", +"insure", +"international", +"intuit", +"investments", +"ipiranga", +"irish", +"ismaili", +"ist", +"istanbul", +"itau", +"itv", +"jaguar", +"java", +"jcb", +"jeep", +"jetzt", +"jewelry", +"jio", +"jll", +"jmp", +"jnj", +"joburg", +"jot", +"joy", +"jpmorgan", +"jprs", +"juegos", +"juniper", +"kaufen", +"kddi", +"kerryhotels", +"kerrylogistics", +"kerryproperties", +"kfh", +"kia", +"kids", +"kim", +"kinder", +"kindle", +"kitchen", +"kiwi", +"koeln", +"komatsu", +"kosher", +"kpmg", +"kpn", +"krd", +"kred", +"kuokgroup", +"kyoto", +"lacaixa", +"lamborghini", +"lamer", +"lancaster", +"lancia", +"land", +"landrover", +"lanxess", +"lasalle", +"lat", +"latino", +"latrobe", +"law", +"lawyer", +"lds", +"lease", +"leclerc", +"lefrak", +"legal", +"lego", +"lexus", +"lgbt", +"lidl", +"life", +"lifeinsurance", +"lifestyle", +"lighting", +"like", +"lilly", +"limited", +"limo", +"lincoln", +"linde", +"link", +"lipsy", +"live", +"living", +"llc", +"llp", +"loan", +"loans", +"locker", +"locus", +"loft", +"lol", +"london", +"lotte", +"lotto", +"love", +"lpl", +"lplfinancial", +"ltd", +"ltda", +"lundbeck", +"luxe", +"luxury", +"macys", +"madrid", +"maif", +"maison", +"makeup", +"man", +"management", +"mango", +"map", +"market", +"marketing", +"markets", +"marriott", +"marshalls", +"maserati", +"mattel", +"mba", +"mckinsey", +"med", +"media", +"meet", +"melbourne", +"meme", +"memorial", +"men", +"menu", +"merckmsd", +"miami", +"microsoft", +"mini", +"mint", +"mit", +"mitsubishi", +"mlb", +"mls", +"mma", +"mobile", +"moda", +"moe", +"moi", +"mom", +"monash", +"money", +"monster", +"mormon", +"mortgage", +"moscow", +"moto", +"motorcycles", +"mov", +"movie", +"msd", +"mtn", +"mtr", +"music", +"mutual", +"nab", +"nagoya", +"natura", +"navy", +"nba", +"nec", +"netbank", +"netflix", +"network", +"neustar", +"new", +"news", +"next", +"nextdirect", +"nexus", +"nfl", +"ngo", +"nhk", +"nico", +"nike", +"nikon", +"ninja", +"nissan", +"nissay", +"nokia", +"northwesternmutual", +"norton", +"now", +"nowruz", +"nowtv", +"nra", +"nrw", +"ntt", +"nyc", +"obi", +"observer", +"office", +"okinawa", +"olayan", +"olayangroup", +"oldnavy", +"ollo", +"omega", +"one", +"ong", +"onl", +"online", +"ooo", +"open", +"oracle", +"orange", +"organic", +"origins", +"osaka", +"otsuka", +"ott", +"ovh", +"page", +"panasonic", +"paris", +"pars", +"partners", +"parts", +"party", +"passagens", +"pay", +"pccw", +"pet", +"pfizer", +"pharmacy", +"phd", +"philips", +"phone", +"photo", +"photography", +"photos", +"physio", +"pics", +"pictet", +"pictures", +"pid", +"pin", +"ping", +"pink", +"pioneer", +"pizza", +"place", +"play", +"playstation", +"plumbing", +"plus", +"pnc", +"pohl", +"poker", +"politie", +"porn", +"pramerica", +"praxi", +"press", +"prime", +"prod", +"productions", +"prof", +"progressive", +"promo", +"properties", +"property", +"protection", +"pru", +"prudential", +"pub", +"pwc", +"qpon", +"quebec", +"quest", +"racing", +"radio", +"read", +"realestate", +"realtor", +"realty", +"recipes", +"red", +"redstone", +"redumbrella", +"rehab", +"reise", +"reisen", +"reit", +"reliance", +"ren", +"rent", +"rentals", +"repair", +"report", +"republican", +"rest", +"restaurant", +"review", +"reviews", +"rexroth", +"rich", +"richardli", +"ricoh", +"ril", +"rio", +"rip", +"rocher", +"rocks", +"rodeo", +"rogers", +"room", +"rsvp", +"rugby", +"ruhr", +"run", +"rwe", +"ryukyu", +"saarland", +"safe", +"safety", +"sakura", +"sale", +"salon", +"samsclub", +"samsung", +"sandvik", +"sandvikcoromant", +"sanofi", +"sap", +"sarl", +"sas", +"save", +"saxo", +"sbi", +"sbs", +"sca", +"scb", +"schaeffler", +"schmidt", +"scholarships", +"school", +"schule", +"schwarz", +"science", +"scot", +"search", +"seat", +"secure", +"security", +"seek", +"select", +"sener", +"services", +"ses", +"seven", +"sew", +"sex", +"sexy", +"sfr", +"shangrila", +"sharp", +"shaw", +"shell", +"shia", +"shiksha", +"shoes", +"shop", +"shopping", +"shouji", +"show", +"showtime", +"silk", +"sina", +"singles", +"site", +"ski", +"skin", +"sky", +"skype", +"sling", +"smart", +"smile", +"sncf", +"soccer", +"social", +"softbank", +"software", +"sohu", +"solar", +"solutions", +"song", +"sony", +"soy", +"spa", +"space", +"sport", +"spot", +"srl", +"stada", +"staples", +"star", +"statebank", +"statefarm", +"stc", +"stcgroup", +"stockholm", +"storage", +"store", +"stream", +"studio", +"study", +"style", +"sucks", +"supplies", +"supply", +"support", +"surf", +"surgery", +"suzuki", +"swatch", +"swiss", +"sydney", +"systems", +"tab", +"taipei", +"talk", +"taobao", +"target", +"tatamotors", +"tatar", +"tattoo", +"tax", +"taxi", +"tci", +"tdk", +"team", +"tech", +"technology", +"temasek", +"tennis", +"teva", +"thd", +"theater", +"theatre", +"tiaa", +"tickets", +"tienda", +"tiffany", +"tips", +"tires", +"tirol", +"tjmaxx", +"tjx", +"tkmaxx", +"tmall", +"today", +"tokyo", +"tools", +"top", +"toray", +"toshiba", +"total", +"tours", +"town", +"toyota", +"toys", +"trade", +"trading", +"training", +"travel", +"travelchannel", +"travelers", +"travelersinsurance", +"trust", +"trv", +"tube", +"tui", +"tunes", +"tushu", +"tvs", +"ubank", +"ubs", +"unicom", +"university", +"uno", +"uol", +"ups", +"vacations", +"vana", +"vanguard", +"vegas", +"ventures", +"verisign", +"versicherung", +"vet", +"viajes", +"video", +"vig", +"viking", +"villas", +"vin", +"vip", +"virgin", +"visa", +"vision", +"viva", +"vivo", +"vlaanderen", +"vodka", +"volkswagen", +"volvo", +"vote", +"voting", +"voto", +"voyage", +"vuelos", +"wales", +"walmart", +"walter", +"wang", +"wanggou", +"watch", +"watches", +"weather", +"weatherchannel", +"webcam", +"weber", +"website", +"wedding", +"weibo", +"weir", +"whoswho", +"wien", +"wiki", +"williamhill", +"win", +"windows", +"wine", +"winners", +"wme", +"wolterskluwer", +"woodside", +"work", +"works", +"world", +"wow", +"wtc", +"wtf", +"xbox", +"xerox", +"xfinity", +"xihuan", +"xin", +"कॉम", +"セール", +"佛山", +"慈善", +"集团", +"在线", +"点看", +"คอม", +"八卦", +"موقع", +"公益", +"公司", +"香格里拉", +"网站", +"移动", +"我爱你", +"москва", +"католик", +"онлайн", +"сайт", +"联通", +"קום", +"时尚", +"微博", +"淡马锡", +"ファッション", +"орг", +"नेट", +"ストア", +"アマゾン", +"삼성", +"商标", +"商店", +"商城", +"дети", +"ポイント", +"新闻", +"家電", +"كوم", +"中文网", +"中信", +"娱乐", +"谷歌", +"電訊盈科", +"购物", +"クラウド", +"通販", +"网店", +"संगठन", +"餐厅", +"网络", +"ком", +"亚马逊", +"诺基亚", +"食品", +"飞利浦", +"手机", +"ارامكو", +"العليان", +"اتصالات", +"بازار", +"ابوظبي", +"كاثوليك", +"همراه", +"닷컴", +"政府", +"شبكة", +"بيتك", +"عرب", +"机构", +"组织机构", +"健康", +"招聘", +"рус", +"大拿", +"みんな", +"グーグル", +"世界", +"書籍", +"网址", +"닷넷", +"コム", +"天主教", +"游戏", +"vermögensberater", +"vermögensberatung", +"企业", +"信息", +"嘉里大酒店", +"嘉里", +"广东", +"政务", +"xyz", +"yachts", +"yahoo", +"yamaxun", +"yandex", +"yodobashi", +"yoga", +"yokohama", +"you", +"youtube", +"yun", +"zappos", +"zara", +"zero", +"zip", +"zone", +"zuerich", +"cc.ua", +"inf.ua", +"ltd.ua", +"611.to", +"graphox.us", +"*.devcdnaccesso.com", +"adobeaemcloud.com", +"*.dev.adobeaemcloud.com", +"hlx.live", +"adobeaemcloud.net", +"hlx.page", +"hlx3.page", +"beep.pl", +"airkitapps.com", +"airkitapps-au.com", +"airkitapps.eu", +"aivencloud.com", +"barsy.ca", +"*.compute.estate", +"*.alces.network", +"kasserver.com", +"altervista.org", +"alwaysdata.net", +"cloudfront.net", +"*.compute.amazonaws.com", +"*.compute-1.amazonaws.com", +"*.compute.amazonaws.com.cn", +"us-east-1.amazonaws.com", +"cn-north-1.eb.amazonaws.com.cn", +"cn-northwest-1.eb.amazonaws.com.cn", +"elasticbeanstalk.com", +"ap-northeast-1.elasticbeanstalk.com", +"ap-northeast-2.elasticbeanstalk.com", +"ap-northeast-3.elasticbeanstalk.com", +"ap-south-1.elasticbeanstalk.com", +"ap-southeast-1.elasticbeanstalk.com", +"ap-southeast-2.elasticbeanstalk.com", +"ca-central-1.elasticbeanstalk.com", +"eu-central-1.elasticbeanstalk.com", +"eu-west-1.elasticbeanstalk.com", +"eu-west-2.elasticbeanstalk.com", +"eu-west-3.elasticbeanstalk.com", +"sa-east-1.elasticbeanstalk.com", +"us-east-1.elasticbeanstalk.com", +"us-east-2.elasticbeanstalk.com", +"us-gov-west-1.elasticbeanstalk.com", +"us-west-1.elasticbeanstalk.com", +"us-west-2.elasticbeanstalk.com", +"*.elb.amazonaws.com", +"*.elb.amazonaws.com.cn", +"awsglobalaccelerator.com", +"s3.amazonaws.com", +"s3-ap-northeast-1.amazonaws.com", +"s3-ap-northeast-2.amazonaws.com", +"s3-ap-south-1.amazonaws.com", +"s3-ap-southeast-1.amazonaws.com", +"s3-ap-southeast-2.amazonaws.com", +"s3-ca-central-1.amazonaws.com", +"s3-eu-central-1.amazonaws.com", +"s3-eu-west-1.amazonaws.com", +"s3-eu-west-2.amazonaws.com", +"s3-eu-west-3.amazonaws.com", +"s3-external-1.amazonaws.com", +"s3-fips-us-gov-west-1.amazonaws.com", +"s3-sa-east-1.amazonaws.com", +"s3-us-gov-west-1.amazonaws.com", +"s3-us-east-2.amazonaws.com", +"s3-us-west-1.amazonaws.com", +"s3-us-west-2.amazonaws.com", +"s3.ap-northeast-2.amazonaws.com", +"s3.ap-south-1.amazonaws.com", +"s3.cn-north-1.amazonaws.com.cn", +"s3.ca-central-1.amazonaws.com", +"s3.eu-central-1.amazonaws.com", +"s3.eu-west-2.amazonaws.com", +"s3.eu-west-3.amazonaws.com", +"s3.us-east-2.amazonaws.com", +"s3.dualstack.ap-northeast-1.amazonaws.com", +"s3.dualstack.ap-northeast-2.amazonaws.com", +"s3.dualstack.ap-south-1.amazonaws.com", +"s3.dualstack.ap-southeast-1.amazonaws.com", +"s3.dualstack.ap-southeast-2.amazonaws.com", +"s3.dualstack.ca-central-1.amazonaws.com", +"s3.dualstack.eu-central-1.amazonaws.com", +"s3.dualstack.eu-west-1.amazonaws.com", +"s3.dualstack.eu-west-2.amazonaws.com", +"s3.dualstack.eu-west-3.amazonaws.com", +"s3.dualstack.sa-east-1.amazonaws.com", +"s3.dualstack.us-east-1.amazonaws.com", +"s3.dualstack.us-east-2.amazonaws.com", +"s3-website-us-east-1.amazonaws.com", +"s3-website-us-west-1.amazonaws.com", +"s3-website-us-west-2.amazonaws.com", +"s3-website-ap-northeast-1.amazonaws.com", +"s3-website-ap-southeast-1.amazonaws.com", +"s3-website-ap-southeast-2.amazonaws.com", +"s3-website-eu-west-1.amazonaws.com", +"s3-website-sa-east-1.amazonaws.com", +"s3-website.ap-northeast-2.amazonaws.com", +"s3-website.ap-south-1.amazonaws.com", +"s3-website.ca-central-1.amazonaws.com", +"s3-website.eu-central-1.amazonaws.com", +"s3-website.eu-west-2.amazonaws.com", +"s3-website.eu-west-3.amazonaws.com", +"s3-website.us-east-2.amazonaws.com", +"t3l3p0rt.net", +"tele.amune.org", +"apigee.io", +"siiites.com", +"appspacehosted.com", +"appspaceusercontent.com", +"appudo.net", +"on-aptible.com", +"user.aseinet.ne.jp", +"gv.vc", +"d.gv.vc", +"user.party.eus", +"pimienta.org", +"poivron.org", +"potager.org", +"sweetpepper.org", +"myasustor.com", +"cdn.prod.atlassian-dev.net", +"translated.page", +"myfritz.net", +"onavstack.net", +"*.awdev.ca", +"*.advisor.ws", +"ecommerce-shop.pl", +"b-data.io", +"backplaneapp.io", +"balena-devices.com", +"rs.ba", +"*.banzai.cloud", +"app.banzaicloud.io", +"*.backyards.banzaicloud.io", +"base.ec", +"official.ec", +"buyshop.jp", +"fashionstore.jp", +"handcrafted.jp", +"kawaiishop.jp", +"supersale.jp", +"theshop.jp", +"shopselect.net", +"base.shop", +"*.beget.app", +"betainabox.com", +"bnr.la", +"bitbucket.io", +"blackbaudcdn.net", +"of.je", +"bluebite.io", +"boomla.net", +"boutir.com", +"boxfuse.io", +"square7.ch", +"bplaced.com", +"bplaced.de", +"square7.de", +"bplaced.net", +"square7.net", +"shop.brendly.rs", +"browsersafetymark.io", +"uk0.bigv.io", +"dh.bytemark.co.uk", +"vm.bytemark.co.uk", +"cafjs.com", +"mycd.eu", +"drr.ac", +"uwu.ai", +"carrd.co", +"crd.co", +"ju.mp", +"ae.org", +"br.com", +"cn.com", +"com.de", +"com.se", +"de.com", +"eu.com", +"gb.net", +"hu.net", +"jp.net", +"jpn.com", +"mex.com", +"ru.com", +"sa.com", +"se.net", +"uk.com", +"uk.net", +"us.com", +"za.bz", +"za.com", +"ar.com", +"hu.com", +"kr.com", +"no.com", +"qc.com", +"uy.com", +"africa.com", +"gr.com", +"in.net", +"web.in", +"us.org", +"co.com", +"aus.basketball", +"nz.basketball", +"radio.am", +"radio.fm", +"c.la", +"certmgr.org", +"cx.ua", +"discourse.group", +"discourse.team", +"cleverapps.io", +"clerk.app", +"clerkstage.app", +"*.lcl.dev", +"*.lclstage.dev", +"*.stg.dev", +"*.stgstage.dev", +"clickrising.net", +"c66.me", +"cloud66.ws", +"cloud66.zone", +"jdevcloud.com", +"wpdevcloud.com", +"cloudaccess.host", +"freesite.host", +"cloudaccess.net", +"cloudcontrolled.com", +"cloudcontrolapp.com", +"*.cloudera.site", +"pages.dev", +"trycloudflare.com", +"workers.dev", +"wnext.app", +"co.ca", +"*.otap.co", +"co.cz", +"c.cdn77.org", +"cdn77-ssl.net", +"r.cdn77.net", +"rsc.cdn77.org", +"ssl.origin.cdn77-secure.org", +"cloudns.asia", +"cloudns.biz", +"cloudns.club", +"cloudns.cc", +"cloudns.eu", +"cloudns.in", +"cloudns.info", +"cloudns.org", +"cloudns.pro", +"cloudns.pw", +"cloudns.us", +"cnpy.gdn", +"codeberg.page", +"co.nl", +"co.no", +"webhosting.be", +"hosting-cluster.nl", +"ac.ru", +"edu.ru", +"gov.ru", +"int.ru", +"mil.ru", +"test.ru", +"dyn.cosidns.de", +"dynamisches-dns.de", +"dnsupdater.de", +"internet-dns.de", +"l-o-g-i-n.de", +"dynamic-dns.info", +"feste-ip.net", +"knx-server.net", +"static-access.net", +"realm.cz", +"*.cryptonomic.net", +"cupcake.is", +"curv.dev", +"*.customer-oci.com", +"*.oci.customer-oci.com", +"*.ocp.customer-oci.com", +"*.ocs.customer-oci.com", +"cyon.link", +"cyon.site", +"fnwk.site", +"folionetwork.site", +"platform0.app", +"daplie.me", +"localhost.daplie.me", +"dattolocal.com", +"dattorelay.com", +"dattoweb.com", +"mydatto.com", +"dattolocal.net", +"mydatto.net", +"biz.dk", +"co.dk", +"firm.dk", +"reg.dk", +"store.dk", +"dyndns.dappnode.io", +"*.dapps.earth", +"*.bzz.dapps.earth", +"builtwithdark.com", +"demo.datadetect.com", +"instance.datadetect.com", +"edgestack.me", +"ddns5.com", +"debian.net", +"deno.dev", +"deno-staging.dev", +"dedyn.io", +"deta.app", +"deta.dev", +"*.rss.my.id", +"*.diher.solutions", +"discordsays.com", +"discordsez.com", +"jozi.biz", +"dnshome.de", +"online.th", +"shop.th", +"drayddns.com", +"shoparena.pl", +"dreamhosters.com", +"mydrobo.com", +"drud.io", +"drud.us", +"duckdns.org", +"bip.sh", +"bitbridge.net", +"dy.fi", +"tunk.org", +"dyndns-at-home.com", +"dyndns-at-work.com", +"dyndns-blog.com", +"dyndns-free.com", +"dyndns-home.com", +"dyndns-ip.com", +"dyndns-mail.com", +"dyndns-office.com", +"dyndns-pics.com", +"dyndns-remote.com", +"dyndns-server.com", +"dyndns-web.com", +"dyndns-wiki.com", +"dyndns-work.com", +"dyndns.biz", +"dyndns.info", +"dyndns.org", +"dyndns.tv", +"at-band-camp.net", +"ath.cx", +"barrel-of-knowledge.info", +"barrell-of-knowledge.info", +"better-than.tv", +"blogdns.com", +"blogdns.net", +"blogdns.org", +"blogsite.org", +"boldlygoingnowhere.org", +"broke-it.net", +"buyshouses.net", +"cechire.com", +"dnsalias.com", +"dnsalias.net", +"dnsalias.org", +"dnsdojo.com", +"dnsdojo.net", +"dnsdojo.org", +"does-it.net", +"doesntexist.com", +"doesntexist.org", +"dontexist.com", +"dontexist.net", +"dontexist.org", +"doomdns.com", +"doomdns.org", +"dvrdns.org", +"dyn-o-saur.com", +"dynalias.com", +"dynalias.net", +"dynalias.org", +"dynathome.net", +"dyndns.ws", +"endofinternet.net", +"endofinternet.org", +"endoftheinternet.org", +"est-a-la-maison.com", +"est-a-la-masion.com", +"est-le-patron.com", +"est-mon-blogueur.com", +"for-better.biz", +"for-more.biz", +"for-our.info", +"for-some.biz", +"for-the.biz", +"forgot.her.name", +"forgot.his.name", +"from-ak.com", +"from-al.com", +"from-ar.com", +"from-az.net", +"from-ca.com", +"from-co.net", +"from-ct.com", +"from-dc.com", +"from-de.com", +"from-fl.com", +"from-ga.com", +"from-hi.com", +"from-ia.com", +"from-id.com", +"from-il.com", +"from-in.com", +"from-ks.com", +"from-ky.com", +"from-la.net", +"from-ma.com", +"from-md.com", +"from-me.org", +"from-mi.com", +"from-mn.com", +"from-mo.com", +"from-ms.com", +"from-mt.com", +"from-nc.com", +"from-nd.com", +"from-ne.com", +"from-nh.com", +"from-nj.com", +"from-nm.com", +"from-nv.com", +"from-ny.net", +"from-oh.com", +"from-ok.com", +"from-or.com", +"from-pa.com", +"from-pr.com", +"from-ri.com", +"from-sc.com", +"from-sd.com", +"from-tn.com", +"from-tx.com", +"from-ut.com", +"from-va.com", +"from-vt.com", +"from-wa.com", +"from-wi.com", +"from-wv.com", +"from-wy.com", +"ftpaccess.cc", +"fuettertdasnetz.de", +"game-host.org", +"game-server.cc", +"getmyip.com", +"gets-it.net", +"go.dyndns.org", +"gotdns.com", +"gotdns.org", +"groks-the.info", +"groks-this.info", +"ham-radio-op.net", +"here-for-more.info", +"hobby-site.com", +"hobby-site.org", +"home.dyndns.org", +"homedns.org", +"homeftp.net", +"homeftp.org", +"homeip.net", +"homelinux.com", +"homelinux.net", +"homelinux.org", +"homeunix.com", +"homeunix.net", +"homeunix.org", +"iamallama.com", +"in-the-band.net", +"is-a-anarchist.com", +"is-a-blogger.com", +"is-a-bookkeeper.com", +"is-a-bruinsfan.org", +"is-a-bulls-fan.com", +"is-a-candidate.org", +"is-a-caterer.com", +"is-a-celticsfan.org", +"is-a-chef.com", +"is-a-chef.net", +"is-a-chef.org", +"is-a-conservative.com", +"is-a-cpa.com", +"is-a-cubicle-slave.com", +"is-a-democrat.com", +"is-a-designer.com", +"is-a-doctor.com", +"is-a-financialadvisor.com", +"is-a-geek.com", +"is-a-geek.net", +"is-a-geek.org", +"is-a-green.com", +"is-a-guru.com", +"is-a-hard-worker.com", +"is-a-hunter.com", +"is-a-knight.org", +"is-a-landscaper.com", +"is-a-lawyer.com", +"is-a-liberal.com", +"is-a-libertarian.com", +"is-a-linux-user.org", +"is-a-llama.com", +"is-a-musician.com", +"is-a-nascarfan.com", +"is-a-nurse.com", +"is-a-painter.com", +"is-a-patsfan.org", +"is-a-personaltrainer.com", +"is-a-photographer.com", +"is-a-player.com", +"is-a-republican.com", +"is-a-rockstar.com", +"is-a-socialist.com", +"is-a-soxfan.org", +"is-a-student.com", +"is-a-teacher.com", +"is-a-techie.com", +"is-a-therapist.com", +"is-an-accountant.com", +"is-an-actor.com", +"is-an-actress.com", +"is-an-anarchist.com", +"is-an-artist.com", +"is-an-engineer.com", +"is-an-entertainer.com", +"is-by.us", +"is-certified.com", +"is-found.org", +"is-gone.com", +"is-into-anime.com", +"is-into-cars.com", +"is-into-cartoons.com", +"is-into-games.com", +"is-leet.com", +"is-lost.org", +"is-not-certified.com", +"is-saved.org", +"is-slick.com", +"is-uberleet.com", +"is-very-bad.org", +"is-very-evil.org", +"is-very-good.org", +"is-very-nice.org", +"is-very-sweet.org", +"is-with-theband.com", +"isa-geek.com", +"isa-geek.net", +"isa-geek.org", +"isa-hockeynut.com", +"issmarterthanyou.com", +"isteingeek.de", +"istmein.de", +"kicks-ass.net", +"kicks-ass.org", +"knowsitall.info", +"land-4-sale.us", +"lebtimnetz.de", +"leitungsen.de", +"likes-pie.com", +"likescandy.com", +"merseine.nu", +"mine.nu", +"misconfused.org", +"mypets.ws", +"myphotos.cc", +"neat-url.com", +"office-on-the.net", +"on-the-web.tv", +"podzone.net", +"podzone.org", +"readmyblog.org", +"saves-the-whales.com", +"scrapper-site.net", +"scrapping.cc", +"selfip.biz", +"selfip.com", +"selfip.info", +"selfip.net", +"selfip.org", +"sells-for-less.com", +"sells-for-u.com", +"sells-it.net", +"sellsyourhome.org", +"servebbs.com", +"servebbs.net", +"servebbs.org", +"serveftp.net", +"serveftp.org", +"servegame.org", +"shacknet.nu", +"simple-url.com", +"space-to-rent.com", +"stuff-4-sale.org", +"stuff-4-sale.us", +"teaches-yoga.com", +"thruhere.net", +"traeumtgerade.de", +"webhop.biz", +"webhop.info", +"webhop.net", +"webhop.org", +"worse-than.tv", +"writesthisblog.com", +"ddnss.de", +"dyn.ddnss.de", +"dyndns.ddnss.de", +"dyndns1.de", +"dyn-ip24.de", +"home-webserver.de", +"dyn.home-webserver.de", +"myhome-server.de", +"ddnss.org", +"definima.net", +"definima.io", +"ondigitalocean.app", +"*.digitaloceanspaces.com", +"bci.dnstrace.pro", +"ddnsfree.com", +"ddnsgeek.com", +"giize.com", +"gleeze.com", +"kozow.com", +"loseyourip.com", +"ooguy.com", +"theworkpc.com", +"casacam.net", +"dynu.net", +"accesscam.org", +"camdvr.org", +"freeddns.org", +"mywire.org", +"webredirect.org", +"myddns.rocks", +"blogsite.xyz", +"dynv6.net", +"e4.cz", +"eero.online", +"eero-stage.online", +"elementor.cloud", +"elementor.cool", +"en-root.fr", +"mytuleap.com", +"tuleap-partners.com", +"encr.app", +"encoreapi.com", +"onred.one", +"staging.onred.one", +"eu.encoway.cloud", +"eu.org", +"al.eu.org", +"asso.eu.org", +"at.eu.org", +"au.eu.org", +"be.eu.org", +"bg.eu.org", +"ca.eu.org", +"cd.eu.org", +"ch.eu.org", +"cn.eu.org", +"cy.eu.org", +"cz.eu.org", +"de.eu.org", +"dk.eu.org", +"edu.eu.org", +"ee.eu.org", +"es.eu.org", +"fi.eu.org", +"fr.eu.org", +"gr.eu.org", +"hr.eu.org", +"hu.eu.org", +"ie.eu.org", +"il.eu.org", +"in.eu.org", +"int.eu.org", +"is.eu.org", +"it.eu.org", +"jp.eu.org", +"kr.eu.org", +"lt.eu.org", +"lu.eu.org", +"lv.eu.org", +"mc.eu.org", +"me.eu.org", +"mk.eu.org", +"mt.eu.org", +"my.eu.org", +"net.eu.org", +"ng.eu.org", +"nl.eu.org", +"no.eu.org", +"nz.eu.org", +"paris.eu.org", +"pl.eu.org", +"pt.eu.org", +"q-a.eu.org", +"ro.eu.org", +"ru.eu.org", +"se.eu.org", +"si.eu.org", +"sk.eu.org", +"tr.eu.org", +"uk.eu.org", +"us.eu.org", +"eurodir.ru", +"eu-1.evennode.com", +"eu-2.evennode.com", +"eu-3.evennode.com", +"eu-4.evennode.com", +"us-1.evennode.com", +"us-2.evennode.com", +"us-3.evennode.com", +"us-4.evennode.com", +"twmail.cc", +"twmail.net", +"twmail.org", +"mymailer.com.tw", +"url.tw", +"onfabrica.com", +"apps.fbsbx.com", +"ru.net", +"adygeya.ru", +"bashkiria.ru", +"bir.ru", +"cbg.ru", +"com.ru", +"dagestan.ru", +"grozny.ru", +"kalmykia.ru", +"kustanai.ru", +"marine.ru", +"mordovia.ru", +"msk.ru", +"mytis.ru", +"nalchik.ru", +"nov.ru", +"pyatigorsk.ru", +"spb.ru", +"vladikavkaz.ru", +"vladimir.ru", +"abkhazia.su", +"adygeya.su", +"aktyubinsk.su", +"arkhangelsk.su", +"armenia.su", +"ashgabad.su", +"azerbaijan.su", +"balashov.su", +"bashkiria.su", +"bryansk.su", +"bukhara.su", +"chimkent.su", +"dagestan.su", +"east-kazakhstan.su", +"exnet.su", +"georgia.su", +"grozny.su", +"ivanovo.su", +"jambyl.su", +"kalmykia.su", +"kaluga.su", +"karacol.su", +"karaganda.su", +"karelia.su", +"khakassia.su", +"krasnodar.su", +"kurgan.su", +"kustanai.su", +"lenug.su", +"mangyshlak.su", +"mordovia.su", +"msk.su", +"murmansk.su", +"nalchik.su", +"navoi.su", +"north-kazakhstan.su", +"nov.su", +"obninsk.su", +"penza.su", +"pokrovsk.su", +"sochi.su", +"spb.su", +"tashkent.su", +"termez.su", +"togliatti.su", +"troitsk.su", +"tselinograd.su", +"tula.su", +"tuva.su", +"vladikavkaz.su", +"vladimir.su", +"vologda.su", +"channelsdvr.net", +"u.channelsdvr.net", +"edgecompute.app", +"fastly-terrarium.com", +"fastlylb.net", +"map.fastlylb.net", +"freetls.fastly.net", +"map.fastly.net", +"a.prod.fastly.net", +"global.prod.fastly.net", +"a.ssl.fastly.net", +"b.ssl.fastly.net", +"global.ssl.fastly.net", +"fastvps-server.com", +"fastvps.host", +"myfast.host", +"fastvps.site", +"myfast.space", +"fedorainfracloud.org", +"fedorapeople.org", +"cloud.fedoraproject.org", +"app.os.fedoraproject.org", +"app.os.stg.fedoraproject.org", +"conn.uk", +"copro.uk", +"hosp.uk", +"mydobiss.com", +"fh-muenster.io", +"filegear.me", +"filegear-au.me", +"filegear-de.me", +"filegear-gb.me", +"filegear-ie.me", +"filegear-jp.me", +"filegear-sg.me", +"firebaseapp.com", +"fireweb.app", +"flap.id", +"onflashdrive.app", +"fldrv.com", +"fly.dev", +"edgeapp.net", +"shw.io", +"flynnhosting.net", +"forgeblocks.com", +"id.forgerock.io", +"framer.app", +"framercanvas.com", +"*.frusky.de", +"ravpage.co.il", +"0e.vc", +"freebox-os.com", +"freeboxos.com", +"fbx-os.fr", +"fbxos.fr", +"freebox-os.fr", +"freeboxos.fr", +"freedesktop.org", +"freemyip.com", +"wien.funkfeuer.at", +"*.futurecms.at", +"*.ex.futurecms.at", +"*.in.futurecms.at", +"futurehosting.at", +"futuremailing.at", +"*.ex.ortsinfo.at", +"*.kunden.ortsinfo.at", +"*.statics.cloud", +"independent-commission.uk", +"independent-inquest.uk", +"independent-inquiry.uk", +"independent-panel.uk", +"independent-review.uk", +"public-inquiry.uk", +"royal-commission.uk", +"campaign.gov.uk", +"service.gov.uk", +"api.gov.uk", +"gehirn.ne.jp", +"usercontent.jp", +"gentapps.com", +"gentlentapis.com", +"lab.ms", +"cdn-edges.net", +"ghost.io", +"gsj.bz", +"githubusercontent.com", +"githubpreview.dev", +"github.io", +"gitlab.io", +"gitapp.si", +"gitpage.si", +"glitch.me", +"nog.community", +"co.ro", +"shop.ro", +"lolipop.io", +"angry.jp", +"babyblue.jp", +"babymilk.jp", +"backdrop.jp", +"bambina.jp", +"bitter.jp", +"blush.jp", +"boo.jp", +"boy.jp", +"boyfriend.jp", +"but.jp", +"candypop.jp", +"capoo.jp", +"catfood.jp", +"cheap.jp", +"chicappa.jp", +"chillout.jp", +"chips.jp", +"chowder.jp", +"chu.jp", +"ciao.jp", +"cocotte.jp", +"coolblog.jp", +"cranky.jp", +"cutegirl.jp", +"daa.jp", +"deca.jp", +"deci.jp", +"digick.jp", +"egoism.jp", +"fakefur.jp", +"fem.jp", +"flier.jp", +"floppy.jp", +"fool.jp", +"frenchkiss.jp", +"girlfriend.jp", +"girly.jp", +"gloomy.jp", +"gonna.jp", +"greater.jp", +"hacca.jp", +"heavy.jp", +"her.jp", +"hiho.jp", +"hippy.jp", +"holy.jp", +"hungry.jp", +"icurus.jp", +"itigo.jp", +"jellybean.jp", +"kikirara.jp", +"kill.jp", +"kilo.jp", +"kuron.jp", +"littlestar.jp", +"lolipopmc.jp", +"lolitapunk.jp", +"lomo.jp", +"lovepop.jp", +"lovesick.jp", +"main.jp", +"mods.jp", +"mond.jp", +"mongolian.jp", +"moo.jp", +"namaste.jp", +"nikita.jp", +"nobushi.jp", +"noor.jp", +"oops.jp", +"parallel.jp", +"parasite.jp", +"pecori.jp", +"peewee.jp", +"penne.jp", +"pepper.jp", +"perma.jp", +"pigboat.jp", +"pinoko.jp", +"punyu.jp", +"pupu.jp", +"pussycat.jp", +"pya.jp", +"raindrop.jp", +"readymade.jp", +"sadist.jp", +"schoolbus.jp", +"secret.jp", +"staba.jp", +"stripper.jp", +"sub.jp", +"sunnyday.jp", +"thick.jp", +"tonkotsu.jp", +"under.jp", +"upper.jp", +"velvet.jp", +"verse.jp", +"versus.jp", +"vivian.jp", +"watson.jp", +"weblike.jp", +"whitesnow.jp", +"zombie.jp", +"heteml.net", +"cloudapps.digital", +"london.cloudapps.digital", +"pymnt.uk", +"homeoffice.gov.uk", +"ro.im", +"goip.de", +"run.app", +"a.run.app", +"web.app", +"*.0emm.com", +"appspot.com", +"*.r.appspot.com", +"codespot.com", +"googleapis.com", +"googlecode.com", +"pagespeedmobilizer.com", +"publishproxy.com", +"withgoogle.com", +"withyoutube.com", +"*.gateway.dev", +"cloud.goog", +"translate.goog", +"*.usercontent.goog", +"cloudfunctions.net", +"blogspot.ae", +"blogspot.al", +"blogspot.am", +"blogspot.ba", +"blogspot.be", +"blogspot.bg", +"blogspot.bj", +"blogspot.ca", +"blogspot.cf", +"blogspot.ch", +"blogspot.cl", +"blogspot.co.at", +"blogspot.co.id", +"blogspot.co.il", +"blogspot.co.ke", +"blogspot.co.nz", +"blogspot.co.uk", +"blogspot.co.za", +"blogspot.com", +"blogspot.com.ar", +"blogspot.com.au", +"blogspot.com.br", +"blogspot.com.by", +"blogspot.com.co", +"blogspot.com.cy", +"blogspot.com.ee", +"blogspot.com.eg", +"blogspot.com.es", +"blogspot.com.mt", +"blogspot.com.ng", +"blogspot.com.tr", +"blogspot.com.uy", +"blogspot.cv", +"blogspot.cz", +"blogspot.de", +"blogspot.dk", +"blogspot.fi", +"blogspot.fr", +"blogspot.gr", +"blogspot.hk", +"blogspot.hr", +"blogspot.hu", +"blogspot.ie", +"blogspot.in", +"blogspot.is", +"blogspot.it", +"blogspot.jp", +"blogspot.kr", +"blogspot.li", +"blogspot.lt", +"blogspot.lu", +"blogspot.md", +"blogspot.mk", +"blogspot.mr", +"blogspot.mx", +"blogspot.my", +"blogspot.nl", +"blogspot.no", +"blogspot.pe", +"blogspot.pt", +"blogspot.qa", +"blogspot.re", +"blogspot.ro", +"blogspot.rs", +"blogspot.ru", +"blogspot.se", +"blogspot.sg", +"blogspot.si", +"blogspot.sk", +"blogspot.sn", +"blogspot.td", +"blogspot.tw", +"blogspot.ug", +"blogspot.vn", +"goupile.fr", +"gov.nl", +"awsmppl.com", +"günstigbestellen.de", +"günstigliefern.de", +"fin.ci", +"free.hr", +"caa.li", +"ua.rs", +"conf.se", +"hs.zone", +"hs.run", +"hashbang.sh", +"hasura.app", +"hasura-app.io", +"pages.it.hs-heilbronn.de", +"hepforge.org", +"herokuapp.com", +"herokussl.com", +"ravendb.cloud", +"myravendb.com", +"ravendb.community", +"ravendb.me", +"development.run", +"ravendb.run", +"homesklep.pl", +"secaas.hk", +"hoplix.shop", +"orx.biz", +"biz.gl", +"col.ng", +"firm.ng", +"gen.ng", +"ltd.ng", +"ngo.ng", +"edu.scot", +"sch.so", +"hostyhosting.io", +"häkkinen.fi", +"*.moonscale.io", +"moonscale.net", +"iki.fi", +"ibxos.it", +"iliadboxos.it", +"impertrixcdn.com", +"impertrix.com", +"smushcdn.com", +"wphostedmail.com", +"wpmucdn.com", +"tempurl.host", +"wpmudev.host", +"dyn-berlin.de", +"in-berlin.de", +"in-brb.de", +"in-butter.de", +"in-dsl.de", +"in-dsl.net", +"in-dsl.org", +"in-vpn.de", +"in-vpn.net", +"in-vpn.org", +"biz.at", +"info.at", +"info.cx", +"ac.leg.br", +"al.leg.br", +"am.leg.br", +"ap.leg.br", +"ba.leg.br", +"ce.leg.br", +"df.leg.br", +"es.leg.br", +"go.leg.br", +"ma.leg.br", +"mg.leg.br", +"ms.leg.br", +"mt.leg.br", +"pa.leg.br", +"pb.leg.br", +"pe.leg.br", +"pi.leg.br", +"pr.leg.br", +"rj.leg.br", +"rn.leg.br", +"ro.leg.br", +"rr.leg.br", +"rs.leg.br", +"sc.leg.br", +"se.leg.br", +"sp.leg.br", +"to.leg.br", +"pixolino.com", +"na4u.ru", +"iopsys.se", +"ipifony.net", +"iservschule.de", +"mein-iserv.de", +"schulplattform.de", +"schulserver.de", +"test-iserv.de", +"iserv.dev", +"iobb.net", +"mel.cloudlets.com.au", +"cloud.interhostsolutions.be", +"users.scale.virtualcloud.com.br", +"mycloud.by", +"alp1.ae.flow.ch", +"appengine.flow.ch", +"es-1.axarnet.cloud", +"diadem.cloud", +"vip.jelastic.cloud", +"jele.cloud", +"it1.eur.aruba.jenv-aruba.cloud", +"it1.jenv-aruba.cloud", +"keliweb.cloud", +"cs.keliweb.cloud", +"oxa.cloud", +"tn.oxa.cloud", +"uk.oxa.cloud", +"primetel.cloud", +"uk.primetel.cloud", +"ca.reclaim.cloud", +"uk.reclaim.cloud", +"us.reclaim.cloud", +"ch.trendhosting.cloud", +"de.trendhosting.cloud", +"jele.club", +"amscompute.com", +"clicketcloud.com", +"dopaas.com", +"hidora.com", +"paas.hosted-by-previder.com", +"rag-cloud.hosteur.com", +"rag-cloud-ch.hosteur.com", +"jcloud.ik-server.com", +"jcloud-ver-jpc.ik-server.com", +"demo.jelastic.com", +"kilatiron.com", +"paas.massivegrid.com", +"jed.wafaicloud.com", +"lon.wafaicloud.com", +"ryd.wafaicloud.com", +"j.scaleforce.com.cy", +"jelastic.dogado.eu", +"fi.cloudplatform.fi", +"demo.datacenter.fi", +"paas.datacenter.fi", +"jele.host", +"mircloud.host", +"paas.beebyte.io", +"sekd1.beebyteapp.io", +"jele.io", +"cloud-fr1.unispace.io", +"jc.neen.it", +"cloud.jelastic.open.tim.it", +"jcloud.kz", +"upaas.kazteleport.kz", +"cloudjiffy.net", +"fra1-de.cloudjiffy.net", +"west1-us.cloudjiffy.net", +"jls-sto1.elastx.net", +"jls-sto2.elastx.net", +"jls-sto3.elastx.net", +"faststacks.net", +"fr-1.paas.massivegrid.net", +"lon-1.paas.massivegrid.net", +"lon-2.paas.massivegrid.net", +"ny-1.paas.massivegrid.net", +"ny-2.paas.massivegrid.net", +"sg-1.paas.massivegrid.net", +"jelastic.saveincloud.net", +"nordeste-idc.saveincloud.net", +"j.scaleforce.net", +"jelastic.tsukaeru.net", +"sdscloud.pl", +"unicloud.pl", +"mircloud.ru", +"jelastic.regruhosting.ru", +"enscaled.sg", +"jele.site", +"jelastic.team", +"orangecloud.tn", +"j.layershift.co.uk", +"phx.enscaled.us", +"mircloud.us", +"myjino.ru", +"*.hosting.myjino.ru", +"*.landing.myjino.ru", +"*.spectrum.myjino.ru", +"*.vps.myjino.ru", +"jotelulu.cloud", +"*.triton.zone", +"*.cns.joyent.com", +"js.org", +"kaas.gg", +"khplay.nl", +"ktistory.com", +"kapsi.fi", +"keymachine.de", +"kinghost.net", +"uni5.net", +"knightpoint.systems", +"koobin.events", +"oya.to", +"kuleuven.cloud", +"ezproxy.kuleuven.be", +"co.krd", +"edu.krd", +"krellian.net", +"webthings.io", +"git-repos.de", +"lcube-server.de", +"svn-repos.de", +"leadpages.co", +"lpages.co", +"lpusercontent.com", +"lelux.site", +"co.business", +"co.education", +"co.events", +"co.financial", +"co.network", +"co.place", +"co.technology", +"app.lmpm.com", +"linkyard.cloud", +"linkyard-cloud.ch", +"members.linode.com", +"*.nodebalancer.linode.com", +"*.linodeobjects.com", +"ip.linodeusercontent.com", +"we.bs", +"*.user.localcert.dev", +"localzone.xyz", +"loginline.app", +"loginline.dev", +"loginline.io", +"loginline.services", +"loginline.site", +"servers.run", +"lohmus.me", +"krasnik.pl", +"leczna.pl", +"lubartow.pl", +"lublin.pl", +"poniatowa.pl", +"swidnik.pl", +"glug.org.uk", +"lug.org.uk", +"lugs.org.uk", +"barsy.bg", +"barsy.co.uk", +"barsyonline.co.uk", +"barsycenter.com", +"barsyonline.com", +"barsy.club", +"barsy.de", +"barsy.eu", +"barsy.in", +"barsy.info", +"barsy.io", +"barsy.me", +"barsy.menu", +"barsy.mobi", +"barsy.net", +"barsy.online", +"barsy.org", +"barsy.pro", +"barsy.pub", +"barsy.ro", +"barsy.shop", +"barsy.site", +"barsy.support", +"barsy.uk", +"*.magentosite.cloud", +"mayfirst.info", +"mayfirst.org", +"hb.cldmail.ru", +"cn.vu", +"mazeplay.com", +"mcpe.me", +"mcdir.me", +"mcdir.ru", +"mcpre.ru", +"vps.mcdir.ru", +"mediatech.by", +"mediatech.dev", +"hra.health", +"miniserver.com", +"memset.net", +"messerli.app", +"*.cloud.metacentrum.cz", +"custom.metacentrum.cz", +"flt.cloud.muni.cz", +"usr.cloud.muni.cz", +"meteorapp.com", +"eu.meteorapp.com", +"co.pl", +"*.azurecontainer.io", +"azurewebsites.net", +"azure-mobile.net", +"cloudapp.net", +"azurestaticapps.net", +"1.azurestaticapps.net", +"centralus.azurestaticapps.net", +"eastasia.azurestaticapps.net", +"eastus2.azurestaticapps.net", +"westeurope.azurestaticapps.net", +"westus2.azurestaticapps.net", +"csx.cc", +"mintere.site", +"forte.id", +"mozilla-iot.org", +"bmoattachments.org", +"net.ru", +"org.ru", +"pp.ru", +"hostedpi.com", +"customer.mythic-beasts.com", +"caracal.mythic-beasts.com", +"fentiger.mythic-beasts.com", +"lynx.mythic-beasts.com", +"ocelot.mythic-beasts.com", +"oncilla.mythic-beasts.com", +"onza.mythic-beasts.com", +"sphinx.mythic-beasts.com", +"vs.mythic-beasts.com", +"x.mythic-beasts.com", +"yali.mythic-beasts.com", +"cust.retrosnub.co.uk", +"ui.nabu.casa", +"pony.club", +"of.fashion", +"in.london", +"of.london", +"from.marketing", +"with.marketing", +"for.men", +"repair.men", +"and.mom", +"for.mom", +"for.one", +"under.one", +"for.sale", +"that.win", +"from.work", +"to.work", +"cloud.nospamproxy.com", +"netlify.app", +"4u.com", +"ngrok.io", +"nh-serv.co.uk", +"nfshost.com", +"*.developer.app", +"noop.app", +"*.northflank.app", +"*.build.run", +"*.code.run", +"*.database.run", +"*.migration.run", +"noticeable.news", +"dnsking.ch", +"mypi.co", +"n4t.co", +"001www.com", +"ddnslive.com", +"myiphost.com", +"forumz.info", +"16-b.it", +"32-b.it", +"64-b.it", +"soundcast.me", +"tcp4.me", +"dnsup.net", +"hicam.net", +"now-dns.net", +"ownip.net", +"vpndns.net", +"dynserv.org", +"now-dns.org", +"x443.pw", +"now-dns.top", +"ntdll.top", +"freeddns.us", +"crafting.xyz", +"zapto.xyz", +"nsupdate.info", +"nerdpol.ovh", +"blogsyte.com", +"brasilia.me", +"cable-modem.org", +"ciscofreak.com", +"collegefan.org", +"couchpotatofries.org", +"damnserver.com", +"ddns.me", +"ditchyourip.com", +"dnsfor.me", +"dnsiskinky.com", +"dvrcam.info", +"dynns.com", +"eating-organic.net", +"fantasyleague.cc", +"geekgalaxy.com", +"golffan.us", +"health-carereform.com", +"homesecuritymac.com", +"homesecuritypc.com", +"hopto.me", +"ilovecollege.info", +"loginto.me", +"mlbfan.org", +"mmafan.biz", +"myactivedirectory.com", +"mydissent.net", +"myeffect.net", +"mymediapc.net", +"mypsx.net", +"mysecuritycamera.com", +"mysecuritycamera.net", +"mysecuritycamera.org", +"net-freaks.com", +"nflfan.org", +"nhlfan.net", +"no-ip.ca", +"no-ip.co.uk", +"no-ip.net", +"noip.us", +"onthewifi.com", +"pgafan.net", +"point2this.com", +"pointto.us", +"privatizehealthinsurance.net", +"quicksytes.com", +"read-books.org", +"securitytactics.com", +"serveexchange.com", +"servehumour.com", +"servep2p.com", +"servesarcasm.com", +"stufftoread.com", +"ufcfan.org", +"unusualperson.com", +"workisboring.com", +"3utilities.com", +"bounceme.net", +"ddns.net", +"ddnsking.com", +"gotdns.ch", +"hopto.org", +"myftp.biz", +"myftp.org", +"myvnc.com", +"no-ip.biz", +"no-ip.info", +"no-ip.org", +"noip.me", +"redirectme.net", +"servebeer.com", +"serveblog.net", +"servecounterstrike.com", +"serveftp.com", +"servegame.com", +"servehalflife.com", +"servehttp.com", +"serveirc.com", +"serveminecraft.net", +"servemp3.com", +"servepics.com", +"servequake.com", +"sytes.net", +"webhop.me", +"zapto.org", +"stage.nodeart.io", +"pcloud.host", +"nyc.mn", +"static.observableusercontent.com", +"cya.gg", +"omg.lol", +"cloudycluster.net", +"omniwe.site", +"service.one", +"nid.io", +"opensocial.site", +"opencraft.hosting", +"orsites.com", +"operaunite.com", +"tech.orange", +"authgear-staging.com", +"authgearapps.com", +"skygearapp.com", +"outsystemscloud.com", +"*.webpaas.ovh.net", +"*.hosting.ovh.net", +"ownprovider.com", +"own.pm", +"*.owo.codes", +"ox.rs", +"oy.lc", +"pgfog.com", +"pagefrontapp.com", +"pagexl.com", +"*.paywhirl.com", +"bar0.net", +"bar1.net", +"bar2.net", +"rdv.to", +"art.pl", +"gliwice.pl", +"krakow.pl", +"poznan.pl", +"wroc.pl", +"zakopane.pl", +"pantheonsite.io", +"gotpantheon.com", +"mypep.link", +"perspecta.cloud", +"lk3.ru", +"on-web.fr", +"bc.platform.sh", +"ent.platform.sh", +"eu.platform.sh", +"us.platform.sh", +"*.platformsh.site", +"*.tst.site", +"platter-app.com", +"platter-app.dev", +"platterp.us", +"pdns.page", +"plesk.page", +"pleskns.com", +"dyn53.io", +"onporter.run", +"co.bn", +"postman-echo.com", +"pstmn.io", +"mock.pstmn.io", +"httpbin.org", +"prequalifyme.today", +"xen.prgmr.com", +"priv.at", +"prvcy.page", +"*.dweb.link", +"protonet.io", +"chirurgiens-dentistes-en-france.fr", +"byen.site", +"pubtls.org", +"pythonanywhere.com", +"eu.pythonanywhere.com", +"qoto.io", +"qualifioapp.com", +"qbuser.com", +"cloudsite.builders", +"instances.spawn.cc", +"instantcloud.cn", +"ras.ru", +"qa2.com", +"qcx.io", +"*.sys.qcx.io", +"dev-myqnapcloud.com", +"alpha-myqnapcloud.com", +"myqnapcloud.com", +"*.quipelements.com", +"vapor.cloud", +"vaporcloud.io", +"rackmaze.com", +"rackmaze.net", +"g.vbrplsbx.io", +"*.on-k3s.io", +"*.on-rancher.cloud", +"*.on-rio.io", +"readthedocs.io", +"rhcloud.com", +"app.render.com", +"onrender.com", +"repl.co", +"id.repl.co", +"repl.run", +"resindevice.io", +"devices.resinstaging.io", +"hzc.io", +"wellbeingzone.eu", +"wellbeingzone.co.uk", +"adimo.co.uk", +"itcouldbewor.se", +"git-pages.rit.edu", +"rocky.page", +"биз.рус", +"ком.рус", +"крым.рус", +"мир.рус", +"мск.рус", +"орг.рус", +"самара.рус", +"сочи.рус", +"спб.рус", +"я.рус", +"*.builder.code.com", +"*.dev-builder.code.com", +"*.stg-builder.code.com", +"sandcats.io", +"logoip.de", +"logoip.com", +"fr-par-1.baremetal.scw.cloud", +"fr-par-2.baremetal.scw.cloud", +"nl-ams-1.baremetal.scw.cloud", +"fnc.fr-par.scw.cloud", +"functions.fnc.fr-par.scw.cloud", +"k8s.fr-par.scw.cloud", +"nodes.k8s.fr-par.scw.cloud", +"s3.fr-par.scw.cloud", +"s3-website.fr-par.scw.cloud", +"whm.fr-par.scw.cloud", +"priv.instances.scw.cloud", +"pub.instances.scw.cloud", +"k8s.scw.cloud", +"k8s.nl-ams.scw.cloud", +"nodes.k8s.nl-ams.scw.cloud", +"s3.nl-ams.scw.cloud", +"s3-website.nl-ams.scw.cloud", +"whm.nl-ams.scw.cloud", +"k8s.pl-waw.scw.cloud", +"nodes.k8s.pl-waw.scw.cloud", +"s3.pl-waw.scw.cloud", +"s3-website.pl-waw.scw.cloud", +"scalebook.scw.cloud", +"smartlabeling.scw.cloud", +"dedibox.fr", +"schokokeks.net", +"gov.scot", +"service.gov.scot", +"scrysec.com", +"firewall-gateway.com", +"firewall-gateway.de", +"my-gateway.de", +"my-router.de", +"spdns.de", +"spdns.eu", +"firewall-gateway.net", +"my-firewall.org", +"myfirewall.org", +"spdns.org", +"seidat.net", +"sellfy.store", +"senseering.net", +"minisite.ms", +"magnet.page", +"biz.ua", +"co.ua", +"pp.ua", +"shiftcrypto.dev", +"shiftcrypto.io", +"shiftedit.io", +"myshopblocks.com", +"myshopify.com", +"shopitsite.com", +"shopware.store", +"mo-siemens.io", +"1kapp.com", +"appchizi.com", +"applinzi.com", +"sinaapp.com", +"vipsinaapp.com", +"siteleaf.net", +"bounty-full.com", +"alpha.bounty-full.com", +"beta.bounty-full.com", +"small-web.org", +"vp4.me", +"try-snowplow.com", +"srht.site", +"stackhero-network.com", +"musician.io", +"novecore.site", +"static.land", +"dev.static.land", +"sites.static.land", +"storebase.store", +"vps-host.net", +"atl.jelastic.vps-host.net", +"njs.jelastic.vps-host.net", +"ric.jelastic.vps-host.net", +"playstation-cloud.com", +"apps.lair.io", +"*.stolos.io", +"spacekit.io", +"customer.speedpartner.de", +"myspreadshop.at", +"myspreadshop.com.au", +"myspreadshop.be", +"myspreadshop.ca", +"myspreadshop.ch", +"myspreadshop.com", +"myspreadshop.de", +"myspreadshop.dk", +"myspreadshop.es", +"myspreadshop.fi", +"myspreadshop.fr", +"myspreadshop.ie", +"myspreadshop.it", +"myspreadshop.net", +"myspreadshop.nl", +"myspreadshop.no", +"myspreadshop.pl", +"myspreadshop.se", +"myspreadshop.co.uk", +"api.stdlib.com", +"storj.farm", +"utwente.io", +"soc.srcf.net", +"user.srcf.net", +"temp-dns.com", +"supabase.co", +"supabase.in", +"supabase.net", +"su.paba.se", +"*.s5y.io", +"*.sensiosite.cloud", +"syncloud.it", +"dscloud.biz", +"direct.quickconnect.cn", +"dsmynas.com", +"familyds.com", +"diskstation.me", +"dscloud.me", +"i234.me", +"myds.me", +"synology.me", +"dscloud.mobi", +"dsmynas.net", +"familyds.net", +"dsmynas.org", +"familyds.org", +"vpnplus.to", +"direct.quickconnect.to", +"tabitorder.co.il", +"taifun-dns.de", +"beta.tailscale.net", +"ts.net", +"gda.pl", +"gdansk.pl", +"gdynia.pl", +"med.pl", +"sopot.pl", +"site.tb-hosting.com", +"edugit.io", +"s3.teckids.org", +"telebit.app", +"telebit.io", +"*.telebit.xyz", +"gwiddle.co.uk", +"*.firenet.ch", +"*.svc.firenet.ch", +"reservd.com", +"thingdustdata.com", +"cust.dev.thingdust.io", +"cust.disrec.thingdust.io", +"cust.prod.thingdust.io", +"cust.testing.thingdust.io", +"reservd.dev.thingdust.io", +"reservd.disrec.thingdust.io", +"reservd.testing.thingdust.io", +"tickets.io", +"arvo.network", +"azimuth.network", +"tlon.network", +"torproject.net", +"pages.torproject.net", +"bloxcms.com", +"townnews-staging.com", +"tbits.me", +"12hp.at", +"2ix.at", +"4lima.at", +"lima-city.at", +"12hp.ch", +"2ix.ch", +"4lima.ch", +"lima-city.ch", +"trafficplex.cloud", +"de.cool", +"12hp.de", +"2ix.de", +"4lima.de", +"lima-city.de", +"1337.pictures", +"clan.rip", +"lima-city.rocks", +"webspace.rocks", +"lima.zone", +"*.transurl.be", +"*.transurl.eu", +"*.transurl.nl", +"site.transip.me", +"tuxfamily.org", +"dd-dns.de", +"diskstation.eu", +"diskstation.org", +"dray-dns.de", +"draydns.de", +"dyn-vpn.de", +"dynvpn.de", +"mein-vigor.de", +"my-vigor.de", +"my-wan.de", +"syno-ds.de", +"synology-diskstation.de", +"synology-ds.de", +"typedream.app", +"pro.typeform.com", +"uber.space", +"*.uberspace.de", +"hk.com", +"hk.org", +"ltd.hk", +"inc.hk", +"name.pm", +"sch.tf", +"biz.wf", +"sch.wf", +"org.yt", +"virtualuser.de", +"virtual-user.de", +"upli.io", +"urown.cloud", +"dnsupdate.info", +"lib.de.us", +"2038.io", +"vercel.app", +"vercel.dev", +"now.sh", +"router.management", +"v-info.info", +"voorloper.cloud", +"neko.am", +"nyaa.am", +"be.ax", +"cat.ax", +"es.ax", +"eu.ax", +"gg.ax", +"mc.ax", +"us.ax", +"xy.ax", +"nl.ci", +"xx.gl", +"app.gp", +"blog.gt", +"de.gt", +"to.gt", +"be.gy", +"cc.hn", +"blog.kg", +"io.kg", +"jp.kg", +"tv.kg", +"uk.kg", +"us.kg", +"de.ls", +"at.md", +"de.md", +"jp.md", +"to.md", +"indie.porn", +"vxl.sh", +"ch.tc", +"me.tc", +"we.tc", +"nyan.to", +"at.vg", +"blog.vu", +"dev.vu", +"me.vu", +"v.ua", +"*.vultrobjects.com", +"wafflecell.com", +"*.webhare.dev", +"reserve-online.net", +"reserve-online.com", +"bookonline.app", +"hotelwithflight.com", +"wedeploy.io", +"wedeploy.me", +"wedeploy.sh", +"remotewd.com", +"pages.wiardweb.com", +"wmflabs.org", +"toolforge.org", +"wmcloud.org", +"panel.gg", +"daemon.panel.gg", +"messwithdns.com", +"woltlab-demo.com", +"myforum.community", +"community-pro.de", +"diskussionsbereich.de", +"community-pro.net", +"meinforum.net", +"affinitylottery.org.uk", +"raffleentry.org.uk", +"weeklylottery.org.uk", +"wpenginepowered.com", +"js.wpenginepowered.com", +"wixsite.com", +"editorx.io", +"half.host", +"xnbay.com", +"u2.xnbay.com", +"u2-local.xnbay.com", +"cistron.nl", +"demon.nl", +"xs4all.space", +"yandexcloud.net", +"storage.yandexcloud.net", +"website.yandexcloud.net", +"official.academy", +"yolasite.com", +"ybo.faith", +"yombo.me", +"homelink.one", +"ybo.party", +"ybo.review", +"ybo.science", +"ybo.trade", +"ynh.fr", +"nohost.me", +"noho.st", +"za.net", +"za.org", +"bss.design", +"basicserver.io", +"virtualserver.io", +"enterprisecloud.nu" +] \ No newline at end of file diff --git a/node_modules/psl/dist/psl.js b/node_modules/psl/dist/psl.js new file mode 100644 index 0000000..2e967df --- /dev/null +++ b/node_modules/psl/dist/psl.js @@ -0,0 +1,10187 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.psl = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i= punySuffix.length) { + // return memo; + // } + //} + return rule; + }, null); +}; + + +// +// Error codes and messages. +// +exports.errorCodes = { + DOMAIN_TOO_SHORT: 'Domain name too short.', + DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', + LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', + LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', + LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', + LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', + LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' +}; + + +// +// Validate domain name and throw if not valid. +// +// From wikipedia: +// +// Hostnames are composed of series of labels concatenated with dots, as are all +// domain names. Each label must be between 1 and 63 characters long, and the +// entire hostname (including the delimiting dots) has a maximum of 255 chars. +// +// Allowed chars: +// +// * `a-z` +// * `0-9` +// * `-` but not as a starting or ending character +// * `.` as a separator for the textual portions of a domain name +// +// * http://en.wikipedia.org/wiki/Domain_name +// * http://en.wikipedia.org/wiki/Hostname +// +internals.validate = function (input) { + + // Before we can validate we need to take care of IDNs with unicode chars. + var ascii = Punycode.toASCII(input); + + if (ascii.length < 1) { + return 'DOMAIN_TOO_SHORT'; + } + if (ascii.length > 255) { + return 'DOMAIN_TOO_LONG'; + } + + // Check each part's length and allowed chars. + var labels = ascii.split('.'); + var label; + + for (var i = 0; i < labels.length; ++i) { + label = labels[i]; + if (!label.length) { + return 'LABEL_TOO_SHORT'; + } + if (label.length > 63) { + return 'LABEL_TOO_LONG'; + } + if (label.charAt(0) === '-') { + return 'LABEL_STARTS_WITH_DASH'; + } + if (label.charAt(label.length - 1) === '-') { + return 'LABEL_ENDS_WITH_DASH'; + } + if (!/^[a-z0-9\-]+$/.test(label)) { + return 'LABEL_INVALID_CHARS'; + } + } +}; + + +// +// Public API +// + + +// +// Parse domain. +// +exports.parse = function (input) { + + if (typeof input !== 'string') { + throw new TypeError('Domain name must be a string.'); + } + + // Force domain to lowercase. + var domain = input.slice(0).toLowerCase(); + + // Handle FQDN. + // TODO: Simply remove trailing dot? + if (domain.charAt(domain.length - 1) === '.') { + domain = domain.slice(0, domain.length - 1); + } + + // Validate and sanitise input. + var error = internals.validate(domain); + if (error) { + return { + input: input, + error: { + message: exports.errorCodes[error], + code: error + } + }; + } + + var parsed = { + input: input, + tld: null, + sld: null, + domain: null, + subdomain: null, + listed: false + }; + + var domainParts = domain.split('.'); + + // Non-Internet TLD + if (domainParts[domainParts.length - 1] === 'local') { + return parsed; + } + + var handlePunycode = function () { + + if (!/xn--/.test(domain)) { + return parsed; + } + if (parsed.domain) { + parsed.domain = Punycode.toASCII(parsed.domain); + } + if (parsed.subdomain) { + parsed.subdomain = Punycode.toASCII(parsed.subdomain); + } + return parsed; + }; + + var rule = internals.findRule(domain); + + // Unlisted tld. + if (!rule) { + if (domainParts.length < 2) { + return parsed; + } + parsed.tld = domainParts.pop(); + parsed.sld = domainParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + if (domainParts.length) { + parsed.subdomain = domainParts.pop(); + } + return handlePunycode(); + } + + // At this point we know the public suffix is listed. + parsed.listed = true; + + var tldParts = rule.suffix.split('.'); + var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); + + if (rule.exception) { + privateParts.push(tldParts.shift()); + } + + parsed.tld = tldParts.join('.'); + + if (!privateParts.length) { + return handlePunycode(); + } + + if (rule.wildcard) { + tldParts.unshift(privateParts.pop()); + parsed.tld = tldParts.join('.'); + } + + if (!privateParts.length) { + return handlePunycode(); + } + + parsed.sld = privateParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + + if (privateParts.length) { + parsed.subdomain = privateParts.join('.'); + } + + return handlePunycode(); +}; + + +// +// Get domain. +// +exports.get = function (domain) { + + if (!domain) { + return null; + } + return exports.parse(domain).domain || null; +}; + + +// +// Check whether domain belongs to a known public suffix. +// +exports.isValid = function (domain) { + + var parsed = exports.parse(domain); + return Boolean(parsed.domain && parsed.listed); +}; + +},{"./data/rules.json":1,"punycode":3}],3:[function(require,module,exports){ +(function (global){(function (){ +/*! https://mths.be/punycode v1.4.1 by @mathias */ +;(function(root) { + + /** Detect free variables */ + var freeExports = typeof exports == 'object' && exports && + !exports.nodeType && exports; + var freeModule = typeof module == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof global == 'object' && global; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof define == 'function' && + typeof define.amd == 'object' && + define.amd + ) { + define('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + +}(this)); + +}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}]},{},[2])(2) +}); diff --git a/node_modules/psl/dist/psl.min.js b/node_modules/psl/dist/psl.min.js new file mode 100644 index 0000000..cbcd8eb --- /dev/null +++ b/node_modules/psl/dist/psl.min.js @@ -0,0 +1 @@ +!function(a){"object"==typeof exports&&"undefined"!=typeof module?module.exports=a():"function"==typeof define&&define.amd?define([],a):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).psl=a()}(function(){return function e(s,n,t){function m(o,a){if(!n[o]){if(!s[o]){var i="function"==typeof require&&require;if(!a&&i)return i(o,!0);if(u)return u(o,!0);throw(a=new Error("Cannot find module '"+o+"'")).code="MODULE_NOT_FOUND",a}i=n[o]={exports:{}},s[o][0].call(i.exports,function(a){return m(s[o][1][a]||a)},i,i.exports,e,s,n,t)}return n[o].exports}for(var u="function"==typeof require&&require,a=0;a= 0x80 (not a basic code point)","invalid-input":"Invalid input"},l=j-1,y=Math.floor,f=String.fromCharCode;function v(a){throw new RangeError(c[a])}function k(a,o){for(var i=a.length,e=[];i--;)e[i]=o(a[i]);return e}function g(a,o){var i=a.split("@"),e="",i=(1>>10&1023|55296),a=56320|1023&a),o+=f(a)}).join("")}function z(a,o){return a+22+75*(a<26)-((0!=o)<<5)}function x(a,o,i){var e=0;for(a=i?y(a/m):a>>1,a+=y(a/o);l*b>>1y((d-p)/n))&&v("overflow"),p+=m*n,!(m<(m=t<=l?1:l+b<=t?b:t-l));t+=j)n>y(d/(m=j-m))&&v("overflow"),n*=m;l=x(p-s,o=u.length+1,0==s),y(p/o)>d-c&&v("overflow"),c+=y(p/o),p%=o,u.splice(p++,0,c)}return h(u)}function A(a){for(var o,i,e,s,n,t,m,u,r,p,c=[],l=(a=w(a)).length,k=128,g=72,h=o=0;hy((d-o)/(u=i+1))&&v("overflow"),o+=(s-k)*u,k=s,h=0;hd&&v("overflow"),m==k){for(n=o,t=j;!(n<(r=t<=g?1:g+b<=t?b:t-g));t+=j)c.push(f(z(r+(p=n-r)%(r=j-r),0))),n=y(p/r);c.push(f(z(n,0))),g=x(o,u,i==e),o=0,++i}++o,++k}return c.join("")}if(s={version:"1.4.1",ucs2:{decode:w,encode:h},decode:q,encode:A,toASCII:function(a){return g(a,function(a){return r.test(a)?"xn--"+A(a):a})},toUnicode:function(a){return g(a,function(a){return u.test(a)?q(a.slice(4).toLowerCase()):a})}},o&&i)if(_.exports==o)i.exports=s;else for(n in s)s.hasOwnProperty(n)&&(o[n]=s[n]);else a.punycode=s}.call(this)}.call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[2])(2)}); diff --git a/node_modules/psl/index.js b/node_modules/psl/index.js new file mode 100644 index 0000000..da7bc12 --- /dev/null +++ b/node_modules/psl/index.js @@ -0,0 +1,269 @@ +/*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */ +'use strict'; + + +var Punycode = require('punycode'); + + +var internals = {}; + + +// +// Read rules from file. +// +internals.rules = require('./data/rules.json').map(function (rule) { + + return { + rule: rule, + suffix: rule.replace(/^(\*\.|\!)/, ''), + punySuffix: -1, + wildcard: rule.charAt(0) === '*', + exception: rule.charAt(0) === '!' + }; +}); + + +// +// Check is given string ends with `suffix`. +// +internals.endsWith = function (str, suffix) { + + return str.indexOf(suffix, str.length - suffix.length) !== -1; +}; + + +// +// Find rule for a given domain. +// +internals.findRule = function (domain) { + + var punyDomain = Punycode.toASCII(domain); + return internals.rules.reduce(function (memo, rule) { + + if (rule.punySuffix === -1){ + rule.punySuffix = Punycode.toASCII(rule.suffix); + } + if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) { + return memo; + } + // This has been commented out as it never seems to run. This is because + // sub tlds always appear after their parents and we never find a shorter + // match. + //if (memo) { + // var memoSuffix = Punycode.toASCII(memo.suffix); + // if (memoSuffix.length >= punySuffix.length) { + // return memo; + // } + //} + return rule; + }, null); +}; + + +// +// Error codes and messages. +// +exports.errorCodes = { + DOMAIN_TOO_SHORT: 'Domain name too short.', + DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.', + LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.', + LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.', + LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.', + LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.', + LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.' +}; + + +// +// Validate domain name and throw if not valid. +// +// From wikipedia: +// +// Hostnames are composed of series of labels concatenated with dots, as are all +// domain names. Each label must be between 1 and 63 characters long, and the +// entire hostname (including the delimiting dots) has a maximum of 255 chars. +// +// Allowed chars: +// +// * `a-z` +// * `0-9` +// * `-` but not as a starting or ending character +// * `.` as a separator for the textual portions of a domain name +// +// * http://en.wikipedia.org/wiki/Domain_name +// * http://en.wikipedia.org/wiki/Hostname +// +internals.validate = function (input) { + + // Before we can validate we need to take care of IDNs with unicode chars. + var ascii = Punycode.toASCII(input); + + if (ascii.length < 1) { + return 'DOMAIN_TOO_SHORT'; + } + if (ascii.length > 255) { + return 'DOMAIN_TOO_LONG'; + } + + // Check each part's length and allowed chars. + var labels = ascii.split('.'); + var label; + + for (var i = 0; i < labels.length; ++i) { + label = labels[i]; + if (!label.length) { + return 'LABEL_TOO_SHORT'; + } + if (label.length > 63) { + return 'LABEL_TOO_LONG'; + } + if (label.charAt(0) === '-') { + return 'LABEL_STARTS_WITH_DASH'; + } + if (label.charAt(label.length - 1) === '-') { + return 'LABEL_ENDS_WITH_DASH'; + } + if (!/^[a-z0-9\-]+$/.test(label)) { + return 'LABEL_INVALID_CHARS'; + } + } +}; + + +// +// Public API +// + + +// +// Parse domain. +// +exports.parse = function (input) { + + if (typeof input !== 'string') { + throw new TypeError('Domain name must be a string.'); + } + + // Force domain to lowercase. + var domain = input.slice(0).toLowerCase(); + + // Handle FQDN. + // TODO: Simply remove trailing dot? + if (domain.charAt(domain.length - 1) === '.') { + domain = domain.slice(0, domain.length - 1); + } + + // Validate and sanitise input. + var error = internals.validate(domain); + if (error) { + return { + input: input, + error: { + message: exports.errorCodes[error], + code: error + } + }; + } + + var parsed = { + input: input, + tld: null, + sld: null, + domain: null, + subdomain: null, + listed: false + }; + + var domainParts = domain.split('.'); + + // Non-Internet TLD + if (domainParts[domainParts.length - 1] === 'local') { + return parsed; + } + + var handlePunycode = function () { + + if (!/xn--/.test(domain)) { + return parsed; + } + if (parsed.domain) { + parsed.domain = Punycode.toASCII(parsed.domain); + } + if (parsed.subdomain) { + parsed.subdomain = Punycode.toASCII(parsed.subdomain); + } + return parsed; + }; + + var rule = internals.findRule(domain); + + // Unlisted tld. + if (!rule) { + if (domainParts.length < 2) { + return parsed; + } + parsed.tld = domainParts.pop(); + parsed.sld = domainParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + if (domainParts.length) { + parsed.subdomain = domainParts.pop(); + } + return handlePunycode(); + } + + // At this point we know the public suffix is listed. + parsed.listed = true; + + var tldParts = rule.suffix.split('.'); + var privateParts = domainParts.slice(0, domainParts.length - tldParts.length); + + if (rule.exception) { + privateParts.push(tldParts.shift()); + } + + parsed.tld = tldParts.join('.'); + + if (!privateParts.length) { + return handlePunycode(); + } + + if (rule.wildcard) { + tldParts.unshift(privateParts.pop()); + parsed.tld = tldParts.join('.'); + } + + if (!privateParts.length) { + return handlePunycode(); + } + + parsed.sld = privateParts.pop(); + parsed.domain = [parsed.sld, parsed.tld].join('.'); + + if (privateParts.length) { + parsed.subdomain = privateParts.join('.'); + } + + return handlePunycode(); +}; + + +// +// Get domain. +// +exports.get = function (domain) { + + if (!domain) { + return null; + } + return exports.parse(domain).domain || null; +}; + + +// +// Check whether domain belongs to a known public suffix. +// +exports.isValid = function (domain) { + + var parsed = exports.parse(domain); + return Boolean(parsed.domain && parsed.listed); +}; diff --git a/node_modules/psl/package.json b/node_modules/psl/package.json new file mode 100644 index 0000000..baddd50 --- /dev/null +++ b/node_modules/psl/package.json @@ -0,0 +1,43 @@ +{ + "name": "psl", + "version": "1.9.0", + "description": "Domain name parser based on the Public Suffix List", + "repository": { + "type": "git", + "url": "git@github.com:lupomontero/psl.git" + }, + "main": "index.js", + "scripts": { + "lint": "eslint .", + "test": "mocha test/*.spec.js", + "test:browserstack": "node test/browserstack.js", + "watch": "mocha test --watch", + "prebuild": "./scripts/update-rules.js", + "build": "browserify ./index.js --standalone=psl > ./dist/psl.js", + "postbuild": "cat ./dist/psl.js | uglifyjs -c -m > ./dist/psl.min.js", + "commit-and-pr": "commit-and-pr", + "changelog": "git log $(git describe --tags --abbrev=0)..HEAD --oneline --format=\"%h %s (%an <%ae>)\"" + }, + "keywords": [ + "publicsuffix", + "publicsuffixlist" + ], + "author": "Lupo Montero (https://lupomontero.com/)", + "license": "MIT", + "devDependencies": { + "browserify": "^17.0.0", + "browserslist-browserstack": "^3.1.1", + "browserstack-local": "^1.5.1", + "chai": "^4.3.6", + "commit-and-pr": "^1.0.4", + "eslint": "^8.19.0", + "JSONStream": "^1.3.5", + "mocha": "^7.2.0", + "porch": "^2.0.0", + "request": "^2.88.2", + "selenium-webdriver": "^4.3.0", + "serve-handler": "^6.1.3", + "uglify-js": "^3.16.2", + "watchify": "^4.0.0" + } +} diff --git a/node_modules/safer-buffer/LICENSE b/node_modules/safer-buffer/LICENSE new file mode 100644 index 0000000..4fe9e6f --- /dev/null +++ b/node_modules/safer-buffer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Nikita Skovoroda + +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/safer-buffer/Porting-Buffer.md b/node_modules/safer-buffer/Porting-Buffer.md new file mode 100644 index 0000000..68d86ba --- /dev/null +++ b/node_modules/safer-buffer/Porting-Buffer.md @@ -0,0 +1,268 @@ +# Porting to the Buffer.from/Buffer.alloc API + + +## Overview + +- [Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1) (*recommended*) +- [Variant 2: Use a polyfill](#variant-2) +- [Variant 3: manual detection, with safeguards](#variant-3) + +### Finding problematic bits of code using grep + +Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`. + +It will find all the potentially unsafe places in your own code (with some considerably unlikely +exceptions). + +### Finding problematic bits of code using Node.js 8 + +If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code: + +- `--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js. +- `--trace-deprecation` does the same thing, but only for deprecation warnings. +- `--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8. + +You can set these flags using an environment variable: + +```console +$ export NODE_OPTIONS='--trace-warnings --pending-deprecation' +$ cat example.js +'use strict'; +const foo = new Buffer('foo'); +$ node example.js +(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead. + at showFlaggedDeprecation (buffer.js:127:13) + at new Buffer (buffer.js:148:3) + at Object. (/path/to/example.js:2:13) + [... more stack trace lines ...] +``` + +### Finding problematic bits of code using linters + +Eslint rules [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets. + +There is a drawback, though, that it doesn't always +[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is +overriden e.g. with a polyfill, so recommended is a combination of this and some other method +described above. + + +## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x. + +This is the recommended solution nowadays that would imply only minimal overhead. + +The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible. + +What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way: + +- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`. +- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`). +- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`. + +Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than +`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended to avoid accidential unsafe Buffer API usage. + +There is also a [JSCodeshift codemod](https://github.com/joyeecheung/node-dep-codemod#dep005) +for automatically migrating Buffer constructors to `Buffer.alloc()` or `Buffer.from()`. +Note that it currently only works with cases where the arguments are literals or where the +constructor is invoked with two arguments. + +_If you currently support those older Node.js versions and dropping them would be a semver-major change +for you, or if you support older branches of your packages, consider using [Variant 2](#variant-2) +or [Variant 3](#variant-3) on older branches, so people using those older branches will also receive +the fix. That way, you will eradicate potential issues caused by unguarded Buffer API usage and +your users will not observe a runtime deprecation warning when running your code on Node.js 10._ + + +## Variant 2: Use a polyfill + +Utilize [safer-buffer](https://www.npmjs.com/package/safer-buffer) as a polyfill to support older +Node.js versions. + +You would take exacly the same steps as in [Variant 1](#variant-1), but with a polyfill +`const Buffer = require('safer-buffer').Buffer` in all files where you use the new `Buffer` api. + +Make sure that you do not use old `new Buffer` API — in any files where the line above is added, +using old `new Buffer()` API will _throw_. It will be easy to notice that in CI, though. + +Alternatively, you could use [buffer-from](https://www.npmjs.com/package/buffer-from) and/or +[buffer-alloc](https://www.npmjs.com/package/buffer-alloc) [ponyfills](https://ponyfill.com/) — +those are great, the only downsides being 4 deps in the tree and slightly more code changes to +migrate off them (as you would be using e.g. `Buffer.from` under a different name). If you need only +`Buffer.from` polyfilled — `buffer-from` alone which comes with no extra dependencies. + +_Alternatively, you could use [safe-buffer](https://www.npmjs.com/package/safe-buffer) — it also +provides a polyfill, but takes a different approach which has +[it's drawbacks](https://github.com/chalker/safer-buffer#why-not-safe-buffer). It will allow you +to also use the older `new Buffer()` API in your code, though — but that's arguably a benefit, as +it is problematic, can cause issues in your code, and will start emitting runtime deprecation +warnings starting with Node.js 10._ + +Note that in either case, it is important that you also remove all calls to the old Buffer +API manually — just throwing in `safe-buffer` doesn't fix the problem by itself, it just provides +a polyfill for the new API. I have seen people doing that mistake. + +Enabling eslint rule [no-buffer-constructor](https://eslint.org/docs/rules/no-buffer-constructor) +or +[node/no-deprecated-api](https://github.com/mysticatea/eslint-plugin-node/blob/master/docs/rules/no-deprecated-api.md) +is recommended. + +_Don't forget to drop the polyfill usage once you drop support for Node.js < 4.5.0._ + + +## Variant 3 — manual detection, with safeguards + +This is useful if you create Buffer instances in only a few places (e.g. one), or you have your own +wrapper around them. + +### Buffer(0) + +This special case for creating empty buffers can be safely replaced with `Buffer.concat([])`, which +returns the same result all the way down to Node.js 0.8.x. + +### Buffer(notNumber) + +Before: + +```js +var buf = new Buffer(notNumber, encoding); +``` + +After: + +```js +var buf; +if (Buffer.from && Buffer.from !== Uint8Array.from) { + buf = Buffer.from(notNumber, encoding); +} else { + if (typeof notNumber === 'number') + throw new Error('The "size" argument must be of type number.'); + buf = new Buffer(notNumber, encoding); +} +``` + +`encoding` is optional. + +Note that the `typeof notNumber` before `new Buffer` is required (for cases when `notNumber` argument is not +hard-coded) and _is not caused by the deprecation of Buffer constructor_ — it's exactly _why_ the +Buffer constructor is deprecated. Ecosystem packages lacking this type-check caused numereous +security issues — situations when unsanitized user input could end up in the `Buffer(arg)` create +problems ranging from DoS to leaking sensitive information to the attacker from the process memory. + +When `notNumber` argument is hardcoded (e.g. literal `"abc"` or `[0,1,2]`), the `typeof` check can +be omitted. + +Also note that using TypeScript does not fix this problem for you — when libs written in +`TypeScript` are used from JS, or when user input ends up there — it behaves exactly as pure JS, as +all type checks are translation-time only and are not present in the actual JS code which TS +compiles to. + +### Buffer(number) + +For Node.js 0.10.x (and below) support: + +```js +var buf; +if (Buffer.alloc) { + buf = Buffer.alloc(number); +} else { + buf = new Buffer(number); + buf.fill(0); +} +``` + +Otherwise (Node.js ≥ 0.12.x): + +```js +const buf = Buffer.alloc ? Buffer.alloc(number) : new Buffer(number).fill(0); +``` + +## Regarding Buffer.allocUnsafe + +Be extra cautious when using `Buffer.allocUnsafe`: + * Don't use it if you don't have a good reason to + * e.g. you probably won't ever see a performance difference for small buffers, in fact, those + might be even faster with `Buffer.alloc()`, + * if your code is not in the hot code path — you also probably won't notice a difference, + * keep in mind that zero-filling minimizes the potential risks. + * If you use it, make sure that you never return the buffer in a partially-filled state, + * if you are writing to it sequentially — always truncate it to the actuall written length + +Errors in handling buffers allocated with `Buffer.allocUnsafe` could result in various issues, +ranged from undefined behaviour of your code to sensitive data (user input, passwords, certs) +leaking to the remote attacker. + +_Note that the same applies to `new Buffer` usage without zero-filling, depending on the Node.js +version (and lacking type checks also adds DoS to the list of potential problems)._ + + +## FAQ + + +### What is wrong with the `Buffer` constructor? + +The `Buffer` constructor could be used to create a buffer in many different ways: + +- `new Buffer(42)` creates a `Buffer` of 42 bytes. Before Node.js 8, this buffer contained + *arbitrary memory* for performance reasons, which could include anything ranging from + program source code to passwords and encryption keys. +- `new Buffer('abc')` creates a `Buffer` that contains the UTF-8-encoded version of + the string `'abc'`. A second argument could specify another encoding: For example, + `new Buffer(string, 'base64')` could be used to convert a Base64 string into the original + sequence of bytes that it represents. +- There are several other combinations of arguments. + +This meant that, in code like `var buffer = new Buffer(foo);`, *it is not possible to tell +what exactly the contents of the generated buffer are* without knowing the type of `foo`. + +Sometimes, the value of `foo` comes from an external source. For example, this function +could be exposed as a service on a web server, converting a UTF-8 string into its Base64 form: + +``` +function stringToBase64(req, res) { + // The request body should have the format of `{ string: 'foobar' }` + const rawBytes = new Buffer(req.body.string) + const encoded = rawBytes.toString('base64') + res.end({ encoded: encoded }) +} +``` + +Note that this code does *not* validate the type of `req.body.string`: + +- `req.body.string` is expected to be a string. If this is the case, all goes well. +- `req.body.string` is controlled by the client that sends the request. +- If `req.body.string` is the *number* `50`, the `rawBytes` would be 50 bytes: + - Before Node.js 8, the content would be uninitialized + - After Node.js 8, the content would be `50` bytes with the value `0` + +Because of the missing type check, an attacker could intentionally send a number +as part of the request. Using this, they can either: + +- Read uninitialized memory. This **will** leak passwords, encryption keys and other + kinds of sensitive information. (Information leak) +- Force the program to allocate a large amount of memory. For example, when specifying + `500000000` as the input value, each request will allocate 500MB of memory. + This can be used to either exhaust the memory available of a program completely + and make it crash, or slow it down significantly. (Denial of Service) + +Both of these scenarios are considered serious security issues in a real-world +web server context. + +when using `Buffer.from(req.body.string)` instead, passing a number will always +throw an exception instead, giving a controlled behaviour that can always be +handled by the program. + + +### The `Buffer()` constructor has been deprecated for a while. Is this really an issue? + +Surveys of code in the `npm` ecosystem have shown that the `Buffer()` constructor is still +widely used. This includes new code, and overall usage of such code has actually been +*increasing*. diff --git a/node_modules/safer-buffer/Readme.md b/node_modules/safer-buffer/Readme.md new file mode 100644 index 0000000..14b0822 --- /dev/null +++ b/node_modules/safer-buffer/Readme.md @@ -0,0 +1,156 @@ +# safer-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![javascript style guide][standard-image]][standard-url] [![Security Responsible Disclosure][secuirty-image]][secuirty-url] + +[travis-image]: https://travis-ci.org/ChALkeR/safer-buffer.svg?branch=master +[travis-url]: https://travis-ci.org/ChALkeR/safer-buffer +[npm-image]: https://img.shields.io/npm/v/safer-buffer.svg +[npm-url]: https://npmjs.org/package/safer-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com +[secuirty-image]: https://img.shields.io/badge/Security-Responsible%20Disclosure-green.svg +[secuirty-url]: https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md + +Modern Buffer API polyfill without footguns, working on Node.js from 0.8 to current. + +## How to use? + +First, port all `Buffer()` and `new Buffer()` calls to `Buffer.alloc()` and `Buffer.from()` API. + +Then, to achieve compatibility with outdated Node.js versions (`<4.5.0` and 5.x `<5.9.0`), use +`const Buffer = require('safer-buffer').Buffer` in all files where you make calls to the new +Buffer API. _Use `var` instead of `const` if you need that for your Node.js version range support._ + +Also, see the +[porting Buffer](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) guide. + +## Do I need it? + +Hopefully, not — dropping support for outdated Node.js versions should be fine nowdays, and that +is the recommended path forward. You _do_ need to port to the `Buffer.alloc()` and `Buffer.from()` +though. + +See the [porting guide](https://github.com/ChALkeR/safer-buffer/blob/master/Porting-Buffer.md) +for a better description. + +## Why not [safe-buffer](https://npmjs.com/safe-buffer)? + +_In short: while `safe-buffer` serves as a polyfill for the new API, it allows old API usage and +itself contains footguns._ + +`safe-buffer` could be used safely to get the new API while still keeping support for older +Node.js versions (like this module), but while analyzing ecosystem usage of the old Buffer API +I found out that `safe-buffer` is itself causing problems in some cases. + +For example, consider the following snippet: + +```console +$ cat example.unsafe.js +console.log(Buffer(20)) +$ ./node-v6.13.0-linux-x64/bin/node example.unsafe.js + +$ standard example.unsafe.js +standard: Use JavaScript Standard Style (https://standardjs.com) + /home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead. +``` + +This is allocates and writes to console an uninitialized chunk of memory. +[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people +to avoid using unsafe API. + +Let's now throw in `safe-buffer`! + +```console +$ cat example.safe-buffer.js +const Buffer = require('safe-buffer').Buffer +console.log(Buffer(20)) +$ standard example.safe-buffer.js +$ ./node-v6.13.0-linux-x64/bin/node example.safe-buffer.js + +``` + +See the problem? Adding in `safe-buffer` _magically removes the lint warning_, but the behavior +remains identiсal to what we had before, and when launched on Node.js 6.x LTS — this dumps out +chunks of uninitialized memory. +_And this code will still emit runtime warnings on Node.js 10.x and above._ + +That was done by design. I first considered changing `safe-buffer`, prohibiting old API usage or +emitting warnings on it, but that significantly diverges from `safe-buffer` design. After some +discussion, it was decided to move my approach into a separate package, and _this is that separate +package_. + +This footgun is not imaginary — I observed top-downloaded packages doing that kind of thing, +«fixing» the lint warning by blindly including `safe-buffer` without any actual changes. + +Also in some cases, even if the API _was_ migrated to use of safe Buffer API — a random pull request +can bring unsafe Buffer API usage back to the codebase by adding new calls — and that could go +unnoticed even if you have a linter prohibiting that (becase of the reason stated above), and even +pass CI. _I also observed that being done in popular packages._ + +Some examples: + * [webdriverio](https://github.com/webdriverio/webdriverio/commit/05cbd3167c12e4930f09ef7cf93b127ba4effae4#diff-124380949022817b90b622871837d56cR31) + (a module with 548 759 downloads/month), + * [websocket-stream](https://github.com/maxogden/websocket-stream/commit/c9312bd24d08271687d76da0fe3c83493871cf61) + (218 288 d/m, fix in [maxogden/websocket-stream#142](https://github.com/maxogden/websocket-stream/pull/142)), + * [node-serialport](https://github.com/node-serialport/node-serialport/commit/e8d9d2b16c664224920ce1c895199b1ce2def48c) + (113 138 d/m, fix in [node-serialport/node-serialport#1510](https://github.com/node-serialport/node-serialport/pull/1510)), + * [karma](https://github.com/karma-runner/karma/commit/3d94b8cf18c695104ca195334dc75ff054c74eec) + (3 973 193 d/m, fix in [karma-runner/karma#2947](https://github.com/karma-runner/karma/pull/2947)), + * [spdy-transport](https://github.com/spdy-http2/spdy-transport/commit/5375ac33f4a62a4f65bcfc2827447d42a5dbe8b1) + (5 970 727 d/m, fix in [spdy-http2/spdy-transport#53](https://github.com/spdy-http2/spdy-transport/pull/53)). + * And there are a lot more over the ecosystem. + +I filed a PR at +[mysticatea/eslint-plugin-node#110](https://github.com/mysticatea/eslint-plugin-node/pull/110) to +partially fix that (for cases when that lint rule is used), but it is a semver-major change for +linter rules and presets, so it would take significant time for that to reach actual setups. +_It also hasn't been released yet (2018-03-20)._ + +Also, `safer-buffer` discourages the usage of `.allocUnsafe()`, which is often done by a mistake. +It still supports it with an explicit concern barier, by placing it under +`require('safer-buffer/dangereous')`. + +## But isn't throwing bad? + +Not really. It's an error that could be noticed and fixed early, instead of causing havoc later like +unguarded `new Buffer()` calls that end up receiving user input can do. + +This package affects only the files where `var Buffer = require('safer-buffer').Buffer` was done, so +it is really simple to keep track of things and make sure that you don't mix old API usage with that. +Also, CI should hint anything that you might have missed. + +New commits, if tested, won't land new usage of unsafe Buffer API this way. +_Node.js 10.x also deals with that by printing a runtime depecation warning._ + +### Would it affect third-party modules? + +No, unless you explicitly do an awful thing like monkey-patching or overriding the built-in `Buffer`. +Don't do that. + +### But I don't want throwing… + +That is also fine! + +Also, it could be better in some cases when you don't comprehensive enough test coverage. + +In that case — just don't override `Buffer` and use +`var SaferBuffer = require('safer-buffer').Buffer` instead. + +That way, everything using `Buffer` natively would still work, but there would be two drawbacks: + +* `Buffer.from`/`Buffer.alloc` won't be polyfilled — use `SaferBuffer.from` and + `SaferBuffer.alloc` instead. +* You are still open to accidentally using the insecure deprecated API — use a linter to catch that. + +Note that using a linter to catch accidential `Buffer` constructor usage in this case is strongly +recommended. `Buffer` is not overriden in this usecase, so linters won't get confused. + +## «Without footguns»? + +Well, it is still possible to do _some_ things with `Buffer` API, e.g. accessing `.buffer` property +on older versions and duping things from there. You shouldn't do that in your code, probabably. + +The intention is to remove the most significant footguns that affect lots of packages in the +ecosystem, and to do it in the proper way. + +Also, this package doesn't protect against security issues affecting some Node.js versions, so for +usage in your own production code, it is still recommended to update to a Node.js version +[supported by upstream](https://github.com/nodejs/release#release-schedule). diff --git a/node_modules/safer-buffer/dangerous.js b/node_modules/safer-buffer/dangerous.js new file mode 100644 index 0000000..ca41fdc --- /dev/null +++ b/node_modules/safer-buffer/dangerous.js @@ -0,0 +1,58 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer +var safer = require('./safer.js') +var Safer = safer.Buffer + +var dangerous = {} + +var key + +for (key in safer) { + if (!safer.hasOwnProperty(key)) continue + dangerous[key] = safer[key] +} + +var Dangereous = dangerous.Buffer = {} + +// Copy Safer API +for (key in Safer) { + if (!Safer.hasOwnProperty(key)) continue + Dangereous[key] = Safer[key] +} + +// Copy those missing unsafe methods, if they are present +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (Dangereous.hasOwnProperty(key)) continue + Dangereous[key] = Buffer[key] +} + +if (!Dangereous.allocUnsafe) { + Dangereous.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return Buffer(size) + } +} + +if (!Dangereous.allocUnsafeSlow) { + Dangereous.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + return buffer.SlowBuffer(size) + } +} + +module.exports = dangerous diff --git a/node_modules/safer-buffer/package.json b/node_modules/safer-buffer/package.json new file mode 100644 index 0000000..d452b04 --- /dev/null +++ b/node_modules/safer-buffer/package.json @@ -0,0 +1,34 @@ +{ + "name": "safer-buffer", + "version": "2.1.2", + "description": "Modern Buffer API polyfill without footguns", + "main": "safer.js", + "scripts": { + "browserify-test": "browserify --external tape tests.js > browserify-tests.js && tape browserify-tests.js", + "test": "standard && tape tests.js" + }, + "author": { + "name": "Nikita Skovoroda", + "email": "chalkerx@gmail.com", + "url": "https://github.com/ChALkeR" + }, + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/ChALkeR/safer-buffer.git" + }, + "bugs": { + "url": "https://github.com/ChALkeR/safer-buffer/issues" + }, + "devDependencies": { + "standard": "^11.0.1", + "tape": "^4.9.0" + }, + "files": [ + "Porting-Buffer.md", + "Readme.md", + "tests.js", + "dangerous.js", + "safer.js" + ] +} diff --git a/node_modules/safer-buffer/safer.js b/node_modules/safer-buffer/safer.js new file mode 100644 index 0000000..37c7e1a --- /dev/null +++ b/node_modules/safer-buffer/safer.js @@ -0,0 +1,77 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var buffer = require('buffer') +var Buffer = buffer.Buffer + +var safer = {} + +var key + +for (key in buffer) { + if (!buffer.hasOwnProperty(key)) continue + if (key === 'SlowBuffer' || key === 'Buffer') continue + safer[key] = buffer[key] +} + +var Safer = safer.Buffer = {} +for (key in Buffer) { + if (!Buffer.hasOwnProperty(key)) continue + if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue + Safer[key] = Buffer[key] +} + +safer.Buffer.prototype = Buffer.prototype + +if (!Safer.from || Safer.from === Uint8Array.from) { + Safer.from = function (value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value) + } + if (value && typeof value.length === 'undefined') { + throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value) + } + return Buffer(value, encodingOrOffset, length) + } +} + +if (!Safer.alloc) { + Safer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size) + } + if (size < 0 || size >= 2 * (1 << 30)) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } + var buf = Buffer(size) + if (!fill || fill.length === 0) { + buf.fill(0) + } else if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + return buf + } +} + +if (!safer.kStringMaxLength) { + try { + safer.kStringMaxLength = process.binding('buffer').kStringMaxLength + } catch (e) { + // we can't determine kStringMaxLength in environments where process.binding + // is unsupported, so let's not set it + } +} + +if (!safer.constants) { + safer.constants = { + MAX_LENGTH: safer.kMaxLength + } + if (safer.kStringMaxLength) { + safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength + } +} + +module.exports = safer diff --git a/node_modules/safer-buffer/tests.js b/node_modules/safer-buffer/tests.js new file mode 100644 index 0000000..7ed2777 --- /dev/null +++ b/node_modules/safer-buffer/tests.js @@ -0,0 +1,406 @@ +/* eslint-disable node/no-deprecated-api */ + +'use strict' + +var test = require('tape') + +var buffer = require('buffer') + +var index = require('./') +var safer = require('./safer') +var dangerous = require('./dangerous') + +/* Inheritance tests */ + +test('Default is Safer', function (t) { + t.equal(index, safer) + t.notEqual(safer, dangerous) + t.notEqual(index, dangerous) + t.end() +}) + +test('Is not a function', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'object') + }); + [buffer].forEach(function (impl) { + t.equal(typeof impl, 'object') + t.equal(typeof impl.Buffer, 'function') + }) + t.end() +}) + +test('Constructor throws', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer() }) + t.throws(function () { impl.Buffer(0) }) + t.throws(function () { impl.Buffer('a') }) + t.throws(function () { impl.Buffer('a', 'utf-8') }) + t.throws(function () { return new impl.Buffer() }) + t.throws(function () { return new impl.Buffer(0) }) + t.throws(function () { return new impl.Buffer('a') }) + t.throws(function () { return new impl.Buffer('a', 'utf-8') }) + }) + t.end() +}) + +test('Safe methods exist', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.alloc, 'function', 'alloc') + t.equal(typeof impl.Buffer.from, 'function', 'from') + }) + t.end() +}) + +test('Unsafe methods exist only in Dangerous', function (t) { + [index, safer].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'undefined') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined') + }); + [dangerous].forEach(function (impl) { + t.equal(typeof impl.Buffer.allocUnsafe, 'function') + t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function') + }) + t.end() +}) + +test('Generic methods/properties are defined and equal', function (t) { + ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in buffer static methods/properties are inherited', function (t) { + Object.keys(buffer).forEach(function (method) { + if (method === 'SlowBuffer' || method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], buffer[method], method) + t.notEqual(typeof impl[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Built-in Buffer static methods/properties are inherited', function (t) { + Object.keys(buffer.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], buffer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('.prototype property of Buffer is inherited', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype') + t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype') + }) + t.end() +}) + +test('All Safer methods are present in Dangerous', function (t) { + Object.keys(safer).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], safer[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(safer.Buffer).forEach(function (method) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], safer.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +test('Safe methods from Dangerous methods are present in Safer', function (t) { + Object.keys(dangerous).forEach(function (method) { + if (method === 'Buffer') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl[method], dangerous[method], method) + if (method !== 'kStringMaxLength') { + t.notEqual(typeof impl[method], 'undefined', method) + } + }) + }) + Object.keys(dangerous.Buffer).forEach(function (method) { + if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return; + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer[method], dangerous.Buffer[method], method) + t.notEqual(typeof impl.Buffer[method], 'undefined', method) + }) + }) + t.end() +}) + +/* Behaviour tests */ + +test('Methods return Buffers', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(''))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3]))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3])))) + t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([]))) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0))) + t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10))) + }) + t.end() +}) + +test('Constructor is buffer.Buffer', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer) + t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer) + t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer) + t.equal(impl.Buffer.from([]).constructor, buffer.Buffer) + }); + [0, 10, 100].forEach(function (arg) { + t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer) + t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor) + }) + t.end() +}) + +test('Invalid calls throw', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.throws(function () { impl.Buffer.from(0) }) + t.throws(function () { impl.Buffer.from(10) }) + t.throws(function () { impl.Buffer.from(10, 'utf-8') }) + t.throws(function () { impl.Buffer.from('string', 'invalid encoding') }) + t.throws(function () { impl.Buffer.from(-10) }) + t.throws(function () { impl.Buffer.from(1e90) }) + t.throws(function () { impl.Buffer.from(Infinity) }) + t.throws(function () { impl.Buffer.from(-Infinity) }) + t.throws(function () { impl.Buffer.from(NaN) }) + t.throws(function () { impl.Buffer.from(null) }) + t.throws(function () { impl.Buffer.from(undefined) }) + t.throws(function () { impl.Buffer.from() }) + t.throws(function () { impl.Buffer.from({}) }) + t.throws(function () { impl.Buffer.alloc('') }) + t.throws(function () { impl.Buffer.alloc('string') }) + t.throws(function () { impl.Buffer.alloc('string', 'utf-8') }) + t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') }) + t.throws(function () { impl.Buffer.alloc(-10) }) + t.throws(function () { impl.Buffer.alloc(1e90) }) + t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) }) + t.throws(function () { impl.Buffer.alloc(Infinity) }) + t.throws(function () { impl.Buffer.alloc(-Infinity) }) + t.throws(function () { impl.Buffer.alloc(null) }) + t.throws(function () { impl.Buffer.alloc(undefined) }) + t.throws(function () { impl.Buffer.alloc() }) + t.throws(function () { impl.Buffer.alloc([]) }) + t.throws(function () { impl.Buffer.alloc([0, 42, 3]) }) + t.throws(function () { impl.Buffer.alloc({}) }) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.throws(function () { dangerous.Buffer[method]('') }) + t.throws(function () { dangerous.Buffer[method]('string') }) + t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') }) + t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) }) + t.throws(function () { dangerous.Buffer[method](Infinity) }) + if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) { + t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0') + } else { + t.throws(function () { dangerous.Buffer[method](-10) }) + t.throws(function () { dangerous.Buffer[method](-1e90) }) + t.throws(function () { dangerous.Buffer[method](-Infinity) }) + } + t.throws(function () { dangerous.Buffer[method](null) }) + t.throws(function () { dangerous.Buffer[method](undefined) }) + t.throws(function () { dangerous.Buffer[method]() }) + t.throws(function () { dangerous.Buffer[method]([]) }) + t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) }) + t.throws(function () { dangerous.Buffer[method]({}) }) + }) + t.end() +}) + +test('Buffers have appropriate lengths', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.equal(impl.Buffer.alloc(0).length, 0) + t.equal(impl.Buffer.alloc(10).length, 10) + t.equal(impl.Buffer.from('').length, 0) + t.equal(impl.Buffer.from('string').length, 6) + t.equal(impl.Buffer.from('string', 'utf-8').length, 6) + t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11) + t.equal(impl.Buffer.from([0, 42, 3]).length, 3) + t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3) + t.equal(impl.Buffer.from([]).length, 0) + }); + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + t.equal(dangerous.Buffer[method](0).length, 0) + t.equal(dangerous.Buffer[method](10).length, 10) + }) + t.end() +}) + +test('Buffers have appropriate lengths (2)', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true; + [ safer.Buffer.alloc, + dangerous.Buffer.allocUnsafe, + dangerous.Buffer.allocUnsafeSlow + ].forEach(function (method) { + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 1e5) + var buf = method(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + } + }) + t.ok(ok) + t.end() +}) + +test('.alloc(size) is zero-filled and has correct length', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = index.Buffer.alloc(length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) { + ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) { + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var buf = dangerous.Buffer[method](length) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + buf.fill(0, 0, length) + var j + for (j = 0; j < length; j++) { + if (buf[j] !== 0) ok = false + } + buf.fill(1, 0, length) + for (j = 0; j < length; j++) { + if (buf[j] !== 1) ok = false + } + } + t.ok(ok, method) + }) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.end() +}) + +test('.alloc(size, fill) is `fill`-filled', function (t) { + t.equal(index.Buffer.alloc, safer.Buffer.alloc) + t.equal(index.Buffer.alloc, dangerous.Buffer.alloc) + var ok = true + for (var i = 0; i < 1e2; i++) { + var length = Math.round(Math.random() * 2e6) + var fill = Math.round(Math.random() * 255) + var buf = index.Buffer.alloc(length, fill) + if (!buffer.Buffer.isBuffer(buf)) ok = false + if (buf.length !== length) ok = false + for (var j = 0; j < length; j++) { + if (buf[j] !== fill) ok = false + } + } + t.ok(ok) + t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97)) + t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98)) + + var tmp = new buffer.Buffer(2) + tmp.fill('ok') + if (tmp[1] === tmp[0]) { + // Outdated Node.js + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo')) + } else { + t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko')) + } + t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok')) + + t.end() +}) + +test('safer.Buffer.from returns results same as Buffer constructor', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), new buffer.Buffer('')) + t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string')) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8')) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64')) + t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3])) + t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3]))) + t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([])) + }) + t.end() +}) + +test('safer.Buffer.from returns consistent results', function (t) { + [index, safer, dangerous].forEach(function (impl) { + t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0)) + t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string')) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103])) + t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string'))) + t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree')) + t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree')) + }) + t.end() +}) diff --git a/node_modules/simple-git/dist/cjs/index.js b/node_modules/simple-git/dist/cjs/index.js new file mode 100644 index 0000000..8b569aa --- /dev/null +++ b/node_modules/simple-git/dist/cjs/index.js @@ -0,0 +1,4907 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +// src/lib/errors/git-error.ts +var GitError; +var init_git_error = __esm({ + "src/lib/errors/git-error.ts"() { + "use strict"; + GitError = class extends Error { + constructor(task, message) { + super(message); + this.task = task; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + } +}); + +// src/lib/errors/git-response-error.ts +var GitResponseError; +var init_git_response_error = __esm({ + "src/lib/errors/git-response-error.ts"() { + "use strict"; + init_git_error(); + GitResponseError = class extends GitError { + constructor(git, message) { + super(void 0, message || String(git)); + this.git = git; + } + }; + } +}); + +// src/lib/args/pathspec.ts +function pathspec(...paths) { + const key = new String(paths); + cache.set(key, paths); + return key; +} +function isPathSpec(path) { + return path instanceof String && cache.has(path); +} +function toPaths(pathSpec) { + return cache.get(pathSpec) || []; +} +var cache; +var init_pathspec = __esm({ + "src/lib/args/pathspec.ts"() { + "use strict"; + cache = /* @__PURE__ */ new WeakMap(); + } +}); + +// src/lib/errors/git-construct-error.ts +var GitConstructError; +var init_git_construct_error = __esm({ + "src/lib/errors/git-construct-error.ts"() { + "use strict"; + init_git_error(); + GitConstructError = class extends GitError { + constructor(config, message) { + super(void 0, message); + this.config = config; + } + }; + } +}); + +// src/lib/errors/git-plugin-error.ts +var GitPluginError; +var init_git_plugin_error = __esm({ + "src/lib/errors/git-plugin-error.ts"() { + "use strict"; + init_git_error(); + GitPluginError = class extends GitError { + constructor(task, plugin, message) { + super(task, message); + this.task = task; + this.plugin = plugin; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + } +}); + +// src/lib/errors/task-configuration-error.ts +var TaskConfigurationError; +var init_task_configuration_error = __esm({ + "src/lib/errors/task-configuration-error.ts"() { + "use strict"; + init_git_error(); + TaskConfigurationError = class extends GitError { + constructor(message) { + super(void 0, message); + } + }; + } +}); + +// src/lib/utils/util.ts +function asFunction(source) { + return typeof source === "function" ? source : NOOP; +} +function isUserFunction(source) { + return typeof source === "function" && source !== NOOP; +} +function splitOn(input, char) { + const index = input.indexOf(char); + if (index <= 0) { + return [input, ""]; + } + return [input.substr(0, index), input.substr(index + 1)]; +} +function first(input, offset = 0) { + return isArrayLike(input) && input.length > offset ? input[offset] : void 0; +} +function last(input, offset = 0) { + if (isArrayLike(input) && input.length > offset) { + return input[input.length - 1 - offset]; + } +} +function isArrayLike(input) { + return !!(input && typeof input.length === "number"); +} +function toLinesWithContent(input = "", trimmed2 = true, separator = "\n") { + return input.split(separator).reduce((output, line) => { + const lineContent = trimmed2 ? line.trim() : line; + if (lineContent) { + output.push(lineContent); + } + return output; + }, []); +} +function forEachLineWithContent(input, callback) { + return toLinesWithContent(input, true).map((line) => callback(line)); +} +function folderExists(path) { + return (0, import_file_exists.exists)(path, import_file_exists.FOLDER); +} +function append(target, item) { + if (Array.isArray(target)) { + if (!target.includes(item)) { + target.push(item); + } + } else { + target.add(item); + } + return item; +} +function including(target, item) { + if (Array.isArray(target) && !target.includes(item)) { + target.push(item); + } + return target; +} +function remove(target, item) { + if (Array.isArray(target)) { + const index = target.indexOf(item); + if (index >= 0) { + target.splice(index, 1); + } + } else { + target.delete(item); + } + return item; +} +function asArray(source) { + return Array.isArray(source) ? source : [source]; +} +function asStringArray(source) { + return asArray(source).map(String); +} +function asNumber(source, onNaN = 0) { + if (source == null) { + return onNaN; + } + const num = parseInt(source, 10); + return isNaN(num) ? onNaN : num; +} +function prefixedArray(input, prefix) { + const output = []; + for (let i = 0, max = input.length; i < max; i++) { + output.push(prefix, input[i]); + } + return output; +} +function bufferToString(input) { + return (Array.isArray(input) ? Buffer.concat(input) : input).toString("utf-8"); +} +function pick(source, properties) { + return Object.assign( + {}, + ...properties.map((property) => property in source ? { [property]: source[property] } : {}) + ); +} +function delay(duration = 0) { + return new Promise((done) => setTimeout(done, duration)); +} +function orVoid(input) { + if (input === false) { + return void 0; + } + return input; +} +var import_file_exists, NULL, NOOP, objectToString; +var init_util = __esm({ + "src/lib/utils/util.ts"() { + "use strict"; + import_file_exists = require("@kwsites/file-exists"); + NULL = "\0"; + NOOP = () => { + }; + objectToString = Object.prototype.toString.call.bind(Object.prototype.toString); + } +}); + +// src/lib/utils/argument-filters.ts +function filterType(input, filter, def) { + if (filter(input)) { + return input; + } + return arguments.length > 2 ? def : void 0; +} +function filterPrimitives(input, omit) { + const type = isPathSpec(input) ? "string" : typeof input; + return /number|string|boolean/.test(type) && (!omit || !omit.includes(type)); +} +function filterPlainObject(input) { + return !!input && objectToString(input) === "[object Object]"; +} +function filterFunction(input) { + return typeof input === "function"; +} +var filterArray, filterString, filterStringArray, filterStringOrStringArray, filterHasLength; +var init_argument_filters = __esm({ + "src/lib/utils/argument-filters.ts"() { + "use strict"; + init_util(); + init_pathspec(); + filterArray = (input) => { + return Array.isArray(input); + }; + filterString = (input) => { + return typeof input === "string"; + }; + filterStringArray = (input) => { + return Array.isArray(input) && input.every(filterString); + }; + filterStringOrStringArray = (input) => { + return filterString(input) || Array.isArray(input) && input.every(filterString); + }; + filterHasLength = (input) => { + if (input == null || "number|boolean|function".includes(typeof input)) { + return false; + } + return Array.isArray(input) || typeof input === "string" || typeof input.length === "number"; + }; + } +}); + +// src/lib/utils/exit-codes.ts +var ExitCodes; +var init_exit_codes = __esm({ + "src/lib/utils/exit-codes.ts"() { + "use strict"; + ExitCodes = /* @__PURE__ */ ((ExitCodes2) => { + ExitCodes2[ExitCodes2["SUCCESS"] = 0] = "SUCCESS"; + ExitCodes2[ExitCodes2["ERROR"] = 1] = "ERROR"; + ExitCodes2[ExitCodes2["NOT_FOUND"] = -2] = "NOT_FOUND"; + ExitCodes2[ExitCodes2["UNCLEAN"] = 128] = "UNCLEAN"; + return ExitCodes2; + })(ExitCodes || {}); + } +}); + +// src/lib/utils/git-output-streams.ts +var GitOutputStreams; +var init_git_output_streams = __esm({ + "src/lib/utils/git-output-streams.ts"() { + "use strict"; + GitOutputStreams = class { + constructor(stdOut, stdErr) { + this.stdOut = stdOut; + this.stdErr = stdErr; + } + asStrings() { + return new GitOutputStreams(this.stdOut.toString("utf8"), this.stdErr.toString("utf8")); + } + }; + } +}); + +// src/lib/utils/line-parser.ts +var LineParser, RemoteLineParser; +var init_line_parser = __esm({ + "src/lib/utils/line-parser.ts"() { + "use strict"; + LineParser = class { + constructor(regExp, useMatches) { + this.matches = []; + this.parse = (line, target) => { + this.resetMatches(); + if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) { + return false; + } + return this.useMatches(target, this.prepareMatches()) !== false; + }; + this._regExp = Array.isArray(regExp) ? regExp : [regExp]; + if (useMatches) { + this.useMatches = useMatches; + } + } + useMatches(target, match) { + throw new Error(`LineParser:useMatches not implemented`); + } + resetMatches() { + this.matches.length = 0; + } + prepareMatches() { + return this.matches; + } + addMatch(reg, index, line) { + const matched = line && reg.exec(line); + if (matched) { + this.pushMatch(index, matched); + } + return !!matched; + } + pushMatch(_index, matched) { + this.matches.push(...matched.slice(1)); + } + }; + RemoteLineParser = class extends LineParser { + addMatch(reg, index, line) { + return /^remote:\s/.test(String(line)) && super.addMatch(reg, index, line); + } + pushMatch(index, matched) { + if (index > 0 || matched.length > 1) { + super.pushMatch(index, matched); + } + } + }; + } +}); + +// src/lib/utils/simple-git-options.ts +function createInstanceConfig(...options) { + const baseDir = process.cwd(); + const config = Object.assign( + __spreadValues({ baseDir }, defaultOptions), + ...options.filter((o) => typeof o === "object" && o) + ); + config.baseDir = config.baseDir || baseDir; + config.trimmed = config.trimmed === true; + return config; +} +var defaultOptions; +var init_simple_git_options = __esm({ + "src/lib/utils/simple-git-options.ts"() { + "use strict"; + defaultOptions = { + binary: "git", + maxConcurrentProcesses: 5, + config: [], + trimmed: false + }; + } +}); + +// src/lib/utils/task-options.ts +function appendTaskOptions(options, commands = []) { + if (!filterPlainObject(options)) { + return commands; + } + return Object.keys(options).reduce((commands2, key) => { + const value = options[key]; + if (isPathSpec(value)) { + commands2.push(value); + } else if (filterPrimitives(value, ["boolean"])) { + commands2.push(key + "=" + value); + } else { + commands2.push(key); + } + return commands2; + }, commands); +} +function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) { + const command = []; + for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) { + if ("string|number".includes(typeof args[i])) { + command.push(String(args[i])); + } + } + appendTaskOptions(trailingOptionsArgument(args), command); + if (!objectOnly) { + command.push(...trailingArrayArgument(args)); + } + return command; +} +function trailingArrayArgument(args) { + const hasTrailingCallback = typeof last(args) === "function"; + return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []); +} +function trailingOptionsArgument(args) { + const hasTrailingCallback = filterFunction(last(args)); + return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject); +} +function trailingFunctionArgument(args, includeNoop = true) { + const callback = asFunction(last(args)); + return includeNoop || isUserFunction(callback) ? callback : void 0; +} +var init_task_options = __esm({ + "src/lib/utils/task-options.ts"() { + "use strict"; + init_argument_filters(); + init_util(); + init_pathspec(); + } +}); + +// src/lib/utils/task-parser.ts +function callTaskParser(parser3, streams) { + return parser3(streams.stdOut, streams.stdErr); +} +function parseStringResponse(result, parsers12, texts, trim = true) { + asArray(texts).forEach((text) => { + for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) { + const line = (offset = 0) => { + if (i + offset >= max) { + return; + } + return lines[i + offset]; + }; + parsers12.some(({ parse }) => parse(line, result)); + } + }); + return result; +} +var init_task_parser = __esm({ + "src/lib/utils/task-parser.ts"() { + "use strict"; + init_util(); + } +}); + +// src/lib/utils/index.ts +var utils_exports = {}; +__export(utils_exports, { + ExitCodes: () => ExitCodes, + GitOutputStreams: () => GitOutputStreams, + LineParser: () => LineParser, + NOOP: () => NOOP, + NULL: () => NULL, + RemoteLineParser: () => RemoteLineParser, + append: () => append, + appendTaskOptions: () => appendTaskOptions, + asArray: () => asArray, + asFunction: () => asFunction, + asNumber: () => asNumber, + asStringArray: () => asStringArray, + bufferToString: () => bufferToString, + callTaskParser: () => callTaskParser, + createInstanceConfig: () => createInstanceConfig, + delay: () => delay, + filterArray: () => filterArray, + filterFunction: () => filterFunction, + filterHasLength: () => filterHasLength, + filterPlainObject: () => filterPlainObject, + filterPrimitives: () => filterPrimitives, + filterString: () => filterString, + filterStringArray: () => filterStringArray, + filterStringOrStringArray: () => filterStringOrStringArray, + filterType: () => filterType, + first: () => first, + folderExists: () => folderExists, + forEachLineWithContent: () => forEachLineWithContent, + getTrailingOptions: () => getTrailingOptions, + including: () => including, + isUserFunction: () => isUserFunction, + last: () => last, + objectToString: () => objectToString, + orVoid: () => orVoid, + parseStringResponse: () => parseStringResponse, + pick: () => pick, + prefixedArray: () => prefixedArray, + remove: () => remove, + splitOn: () => splitOn, + toLinesWithContent: () => toLinesWithContent, + trailingFunctionArgument: () => trailingFunctionArgument, + trailingOptionsArgument: () => trailingOptionsArgument +}); +var init_utils = __esm({ + "src/lib/utils/index.ts"() { + "use strict"; + init_argument_filters(); + init_exit_codes(); + init_git_output_streams(); + init_line_parser(); + init_simple_git_options(); + init_task_options(); + init_task_parser(); + init_util(); + } +}); + +// src/lib/tasks/check-is-repo.ts +var check_is_repo_exports = {}; +__export(check_is_repo_exports, { + CheckRepoActions: () => CheckRepoActions, + checkIsBareRepoTask: () => checkIsBareRepoTask, + checkIsRepoRootTask: () => checkIsRepoRootTask, + checkIsRepoTask: () => checkIsRepoTask +}); +function checkIsRepoTask(action) { + switch (action) { + case "bare" /* BARE */: + return checkIsBareRepoTask(); + case "root" /* IS_REPO_ROOT */: + return checkIsRepoRootTask(); + } + const commands = ["rev-parse", "--is-inside-work-tree"]; + return { + commands, + format: "utf-8", + onError, + parser + }; +} +function checkIsRepoRootTask() { + const commands = ["rev-parse", "--git-dir"]; + return { + commands, + format: "utf-8", + onError, + parser(path) { + return /^\.(git)?$/.test(path.trim()); + } + }; +} +function checkIsBareRepoTask() { + const commands = ["rev-parse", "--is-bare-repository"]; + return { + commands, + format: "utf-8", + onError, + parser + }; +} +function isNotRepoMessage(error) { + return /(Not a git repository|Kein Git-Repository)/i.test(String(error)); +} +var CheckRepoActions, onError, parser; +var init_check_is_repo = __esm({ + "src/lib/tasks/check-is-repo.ts"() { + "use strict"; + init_utils(); + CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => { + CheckRepoActions2["BARE"] = "bare"; + CheckRepoActions2["IN_TREE"] = "tree"; + CheckRepoActions2["IS_REPO_ROOT"] = "root"; + return CheckRepoActions2; + })(CheckRepoActions || {}); + onError = ({ exitCode }, error, done, fail) => { + if (exitCode === 128 /* UNCLEAN */ && isNotRepoMessage(error)) { + return done(Buffer.from("false")); + } + fail(error); + }; + parser = (text) => { + return text.trim() === "true"; + }; + } +}); + +// src/lib/responses/CleanSummary.ts +function cleanSummaryParser(dryRun, text) { + const summary = new CleanResponse(dryRun); + const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp; + toLinesWithContent(text).forEach((line) => { + const removed = line.replace(regexp, ""); + summary.paths.push(removed); + (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed); + }); + return summary; +} +var CleanResponse, removalRegexp, dryRunRemovalRegexp, isFolderRegexp; +var init_CleanSummary = __esm({ + "src/lib/responses/CleanSummary.ts"() { + "use strict"; + init_utils(); + CleanResponse = class { + constructor(dryRun) { + this.dryRun = dryRun; + this.paths = []; + this.files = []; + this.folders = []; + } + }; + removalRegexp = /^[a-z]+\s*/i; + dryRunRemovalRegexp = /^[a-z]+\s+[a-z]+\s*/i; + isFolderRegexp = /\/$/; + } +}); + +// src/lib/tasks/task.ts +var task_exports = {}; +__export(task_exports, { + EMPTY_COMMANDS: () => EMPTY_COMMANDS, + adhocExecTask: () => adhocExecTask, + configurationErrorTask: () => configurationErrorTask, + isBufferTask: () => isBufferTask, + isEmptyTask: () => isEmptyTask, + straightThroughBufferTask: () => straightThroughBufferTask, + straightThroughStringTask: () => straightThroughStringTask +}); +function adhocExecTask(parser3) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser: parser3 + }; +} +function configurationErrorTask(error) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser() { + throw typeof error === "string" ? new TaskConfigurationError(error) : error; + } + }; +} +function straightThroughStringTask(commands, trimmed2 = false) { + return { + commands, + format: "utf-8", + parser(text) { + return trimmed2 ? String(text).trim() : text; + } + }; +} +function straightThroughBufferTask(commands) { + return { + commands, + format: "buffer", + parser(buffer) { + return buffer; + } + }; +} +function isBufferTask(task) { + return task.format === "buffer"; +} +function isEmptyTask(task) { + return task.format === "empty" || !task.commands.length; +} +var EMPTY_COMMANDS; +var init_task = __esm({ + "src/lib/tasks/task.ts"() { + "use strict"; + init_task_configuration_error(); + EMPTY_COMMANDS = []; + } +}); + +// src/lib/tasks/clean.ts +var clean_exports = {}; +__export(clean_exports, { + CONFIG_ERROR_INTERACTIVE_MODE: () => CONFIG_ERROR_INTERACTIVE_MODE, + CONFIG_ERROR_MODE_REQUIRED: () => CONFIG_ERROR_MODE_REQUIRED, + CONFIG_ERROR_UNKNOWN_OPTION: () => CONFIG_ERROR_UNKNOWN_OPTION, + CleanOptions: () => CleanOptions, + cleanTask: () => cleanTask, + cleanWithOptionsTask: () => cleanWithOptionsTask, + isCleanOptionsArray: () => isCleanOptionsArray +}); +function cleanWithOptionsTask(mode, customArgs) { + const { cleanMode, options, valid } = getCleanOptions(mode); + if (!cleanMode) { + return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED); + } + if (!valid.options) { + return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode)); + } + options.push(...customArgs); + if (options.some(isInteractiveMode)) { + return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE); + } + return cleanTask(cleanMode, options); +} +function cleanTask(mode, customArgs) { + const commands = ["clean", `-${mode}`, ...customArgs]; + return { + commands, + format: "utf-8", + parser(text) { + return cleanSummaryParser(mode === "n" /* DRY_RUN */, text); + } + }; +} +function isCleanOptionsArray(input) { + return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test)); +} +function getCleanOptions(input) { + let cleanMode; + let options = []; + let valid = { cleanMode: false, options: true }; + input.replace(/[^a-z]i/g, "").split("").forEach((char) => { + if (isCleanMode(char)) { + cleanMode = char; + valid.cleanMode = true; + } else { + valid.options = valid.options && isKnownOption(options[options.length] = `-${char}`); + } + }); + return { + cleanMode, + options, + valid + }; +} +function isCleanMode(cleanMode) { + return cleanMode === "f" /* FORCE */ || cleanMode === "n" /* DRY_RUN */; +} +function isKnownOption(option) { + return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1)); +} +function isInteractiveMode(option) { + if (/^-[^\-]/.test(option)) { + return option.indexOf("i") > 0; + } + return option === "--interactive"; +} +var CONFIG_ERROR_INTERACTIVE_MODE, CONFIG_ERROR_MODE_REQUIRED, CONFIG_ERROR_UNKNOWN_OPTION, CleanOptions, CleanOptionValues; +var init_clean = __esm({ + "src/lib/tasks/clean.ts"() { + "use strict"; + init_CleanSummary(); + init_utils(); + init_task(); + CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported"; + CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required'; + CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: "; + CleanOptions = /* @__PURE__ */ ((CleanOptions2) => { + CleanOptions2["DRY_RUN"] = "n"; + CleanOptions2["FORCE"] = "f"; + CleanOptions2["IGNORED_INCLUDED"] = "x"; + CleanOptions2["IGNORED_ONLY"] = "X"; + CleanOptions2["EXCLUDING"] = "e"; + CleanOptions2["QUIET"] = "q"; + CleanOptions2["RECURSIVE"] = "d"; + return CleanOptions2; + })(CleanOptions || {}); + CleanOptionValues = /* @__PURE__ */ new Set([ + "i", + ...asStringArray(Object.values(CleanOptions)) + ]); + } +}); + +// src/lib/responses/ConfigList.ts +function configListParser(text) { + const config = new ConfigList(); + for (const item of configParser(text)) { + config.addValue(item.file, String(item.key), item.value); + } + return config; +} +function configGetParser(text, key) { + let value = null; + const values = []; + const scopes = /* @__PURE__ */ new Map(); + for (const item of configParser(text, key)) { + if (item.key !== key) { + continue; + } + values.push(value = item.value); + if (!scopes.has(item.file)) { + scopes.set(item.file, []); + } + scopes.get(item.file).push(value); + } + return { + key, + paths: Array.from(scopes.keys()), + scopes, + value, + values + }; +} +function configFilePath(filePath) { + return filePath.replace(/^(file):/, ""); +} +function* configParser(text, requestedKey = null) { + const lines = text.split("\0"); + for (let i = 0, max = lines.length - 1; i < max; ) { + const file = configFilePath(lines[i++]); + let value = lines[i++]; + let key = requestedKey; + if (value.includes("\n")) { + const line = splitOn(value, "\n"); + key = line[0]; + value = line[1]; + } + yield { file, key, value }; + } +} +var ConfigList; +var init_ConfigList = __esm({ + "src/lib/responses/ConfigList.ts"() { + "use strict"; + init_utils(); + ConfigList = class { + constructor() { + this.files = []; + this.values = /* @__PURE__ */ Object.create(null); + } + get all() { + if (!this._all) { + this._all = this.files.reduce((all, file) => { + return Object.assign(all, this.values[file]); + }, {}); + } + return this._all; + } + addFile(file) { + if (!(file in this.values)) { + const latest = last(this.files); + this.values[file] = latest ? Object.create(this.values[latest]) : {}; + this.files.push(file); + } + return this.values[file]; + } + addValue(file, key, value) { + const values = this.addFile(file); + if (!values.hasOwnProperty(key)) { + values[key] = value; + } else if (Array.isArray(values[key])) { + values[key].push(value); + } else { + values[key] = [values[key], value]; + } + this._all = void 0; + } + }; + } +}); + +// src/lib/tasks/config.ts +function asConfigScope(scope, fallback) { + if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) { + return scope; + } + return fallback; +} +function addConfigTask(key, value, append2, scope) { + const commands = ["config", `--${scope}`]; + if (append2) { + commands.push("--add"); + } + commands.push(key, value); + return { + commands, + format: "utf-8", + parser(text) { + return text; + } + }; +} +function getConfigTask(key, scope) { + const commands = ["config", "--null", "--show-origin", "--get-all", key]; + if (scope) { + commands.splice(1, 0, `--${scope}`); + } + return { + commands, + format: "utf-8", + parser(text) { + return configGetParser(text, key); + } + }; +} +function listConfigTask(scope) { + const commands = ["config", "--list", "--show-origin", "--null"]; + if (scope) { + commands.push(`--${scope}`); + } + return { + commands, + format: "utf-8", + parser(text) { + return configListParser(text); + } + }; +} +function config_default() { + return { + addConfig(key, value, ...rest) { + return this._runTask( + addConfigTask( + key, + value, + rest[0] === true, + asConfigScope(rest[1], "local" /* local */) + ), + trailingFunctionArgument(arguments) + ); + }, + getConfig(key, scope) { + return this._runTask( + getConfigTask(key, asConfigScope(scope, void 0)), + trailingFunctionArgument(arguments) + ); + }, + listConfig(...rest) { + return this._runTask( + listConfigTask(asConfigScope(rest[0], void 0)), + trailingFunctionArgument(arguments) + ); + } + }; +} +var GitConfigScope; +var init_config = __esm({ + "src/lib/tasks/config.ts"() { + "use strict"; + init_ConfigList(); + init_utils(); + GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => { + GitConfigScope2["system"] = "system"; + GitConfigScope2["global"] = "global"; + GitConfigScope2["local"] = "local"; + GitConfigScope2["worktree"] = "worktree"; + return GitConfigScope2; + })(GitConfigScope || {}); + } +}); + +// src/lib/tasks/diff-name-status.ts +function isDiffNameStatus(input) { + return diffNameStatus.has(input); +} +var DiffNameStatus, diffNameStatus; +var init_diff_name_status = __esm({ + "src/lib/tasks/diff-name-status.ts"() { + "use strict"; + DiffNameStatus = /* @__PURE__ */ ((DiffNameStatus2) => { + DiffNameStatus2["ADDED"] = "A"; + DiffNameStatus2["COPIED"] = "C"; + DiffNameStatus2["DELETED"] = "D"; + DiffNameStatus2["MODIFIED"] = "M"; + DiffNameStatus2["RENAMED"] = "R"; + DiffNameStatus2["CHANGED"] = "T"; + DiffNameStatus2["UNMERGED"] = "U"; + DiffNameStatus2["UNKNOWN"] = "X"; + DiffNameStatus2["BROKEN"] = "B"; + return DiffNameStatus2; + })(DiffNameStatus || {}); + diffNameStatus = new Set(Object.values(DiffNameStatus)); + } +}); + +// src/lib/tasks/grep.ts +function grepQueryBuilder(...params) { + return new GrepQuery().param(...params); +} +function parseGrep(grep) { + const paths = /* @__PURE__ */ new Set(); + const results = {}; + forEachLineWithContent(grep, (input) => { + const [path, line, preview] = input.split(NULL); + paths.add(path); + (results[path] = results[path] || []).push({ + line: asNumber(line), + path, + preview + }); + }); + return { + paths, + results + }; +} +function grep_default() { + return { + grep(searchTerm) { + const then = trailingFunctionArgument(arguments); + const options = getTrailingOptions(arguments); + for (const option of disallowedOptions) { + if (options.includes(option)) { + return this._runTask( + configurationErrorTask(`git.grep: use of "${option}" is not supported.`), + then + ); + } + } + if (typeof searchTerm === "string") { + searchTerm = grepQueryBuilder().param(searchTerm); + } + const commands = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm]; + return this._runTask( + { + commands, + format: "utf-8", + parser(stdOut) { + return parseGrep(stdOut); + } + }, + then + ); + } + }; +} +var disallowedOptions, Query, _a, GrepQuery; +var init_grep = __esm({ + "src/lib/tasks/grep.ts"() { + "use strict"; + init_utils(); + init_task(); + disallowedOptions = ["-h"]; + Query = Symbol("grepQuery"); + GrepQuery = class { + constructor() { + this[_a] = []; + } + *[(_a = Query, Symbol.iterator)]() { + for (const query of this[Query]) { + yield query; + } + } + and(...and) { + and.length && this[Query].push("--and", "(", ...prefixedArray(and, "-e"), ")"); + return this; + } + param(...param) { + this[Query].push(...prefixedArray(param, "-e")); + return this; + } + }; + } +}); + +// src/lib/tasks/reset.ts +var reset_exports = {}; +__export(reset_exports, { + ResetMode: () => ResetMode, + getResetMode: () => getResetMode, + resetTask: () => resetTask +}); +function resetTask(mode, customArgs) { + const commands = ["reset"]; + if (isValidResetMode(mode)) { + commands.push(`--${mode}`); + } + commands.push(...customArgs); + return straightThroughStringTask(commands); +} +function getResetMode(mode) { + if (isValidResetMode(mode)) { + return mode; + } + switch (typeof mode) { + case "string": + case "undefined": + return "soft" /* SOFT */; + } + return; +} +function isValidResetMode(mode) { + return ResetModes.includes(mode); +} +var ResetMode, ResetModes; +var init_reset = __esm({ + "src/lib/tasks/reset.ts"() { + "use strict"; + init_task(); + ResetMode = /* @__PURE__ */ ((ResetMode2) => { + ResetMode2["MIXED"] = "mixed"; + ResetMode2["SOFT"] = "soft"; + ResetMode2["HARD"] = "hard"; + ResetMode2["MERGE"] = "merge"; + ResetMode2["KEEP"] = "keep"; + return ResetMode2; + })(ResetMode || {}); + ResetModes = Array.from(Object.values(ResetMode)); + } +}); + +// src/lib/api.ts +var api_exports = {}; +__export(api_exports, { + CheckRepoActions: () => CheckRepoActions, + CleanOptions: () => CleanOptions, + DiffNameStatus: () => DiffNameStatus, + GitConfigScope: () => GitConfigScope, + GitConstructError: () => GitConstructError, + GitError: () => GitError, + GitPluginError: () => GitPluginError, + GitResponseError: () => GitResponseError, + ResetMode: () => ResetMode, + TaskConfigurationError: () => TaskConfigurationError, + grepQueryBuilder: () => grepQueryBuilder, + pathspec: () => pathspec +}); +var init_api = __esm({ + "src/lib/api.ts"() { + "use strict"; + init_pathspec(); + init_git_construct_error(); + init_git_error(); + init_git_plugin_error(); + init_git_response_error(); + init_task_configuration_error(); + init_check_is_repo(); + init_clean(); + init_config(); + init_diff_name_status(); + init_grep(); + init_reset(); + } +}); + +// src/lib/plugins/abort-plugin.ts +function abortPlugin(signal) { + if (!signal) { + return; + } + const onSpawnAfter = { + type: "spawn.after", + action(_data, context) { + function kill() { + context.kill(new GitPluginError(void 0, "abort", "Abort signal received")); + } + signal.addEventListener("abort", kill); + context.spawned.on("close", () => signal.removeEventListener("abort", kill)); + } + }; + const onSpawnBefore = { + type: "spawn.before", + action(_data, context) { + if (signal.aborted) { + context.kill(new GitPluginError(void 0, "abort", "Abort already signaled")); + } + } + }; + return [onSpawnBefore, onSpawnAfter]; +} +var init_abort_plugin = __esm({ + "src/lib/plugins/abort-plugin.ts"() { + "use strict"; + init_git_plugin_error(); + } +}); + +// src/lib/plugins/block-unsafe-operations-plugin.ts +function isConfigSwitch(arg) { + return typeof arg === "string" && arg.trim().toLowerCase() === "-c"; +} +function preventProtocolOverride(arg, next) { + if (!isConfigSwitch(arg)) { + return; + } + if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) { + return; + } + throw new GitPluginError( + void 0, + "unsafe", + "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol" + ); +} +function preventUploadPack(arg, method) { + if (/^\s*--(upload|receive)-pack/.test(arg)) { + throw new GitPluginError( + void 0, + "unsafe", + `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack` + ); + } + if (method === "clone" && /^\s*-u\b/.test(arg)) { + throw new GitPluginError( + void 0, + "unsafe", + `Use of clone with option -u is not permitted without enabling allowUnsafePack` + ); + } + if (method === "push" && /^\s*--exec\b/.test(arg)) { + throw new GitPluginError( + void 0, + "unsafe", + `Use of push with option --exec is not permitted without enabling allowUnsafePack` + ); + } +} +function blockUnsafeOperationsPlugin({ + allowUnsafeProtocolOverride = false, + allowUnsafePack = false +} = {}) { + return { + type: "spawn.args", + action(args, context) { + args.forEach((current, index) => { + const next = index < args.length ? args[index + 1] : ""; + allowUnsafeProtocolOverride || preventProtocolOverride(current, next); + allowUnsafePack || preventUploadPack(current, context.method); + }); + return args; + } + }; +} +var init_block_unsafe_operations_plugin = __esm({ + "src/lib/plugins/block-unsafe-operations-plugin.ts"() { + "use strict"; + init_git_plugin_error(); + } +}); + +// src/lib/plugins/command-config-prefixing-plugin.ts +function commandConfigPrefixingPlugin(configuration) { + const prefix = prefixedArray(configuration, "-c"); + return { + type: "spawn.args", + action(data) { + return [...prefix, ...data]; + } + }; +} +var init_command_config_prefixing_plugin = __esm({ + "src/lib/plugins/command-config-prefixing-plugin.ts"() { + "use strict"; + init_utils(); + } +}); + +// src/lib/plugins/completion-detection.plugin.ts +function completionDetectionPlugin({ + onClose = true, + onExit = 50 +} = {}) { + function createEvents() { + let exitCode = -1; + const events = { + close: (0, import_promise_deferred.deferred)(), + closeTimeout: (0, import_promise_deferred.deferred)(), + exit: (0, import_promise_deferred.deferred)(), + exitTimeout: (0, import_promise_deferred.deferred)() + }; + const result = Promise.race([ + onClose === false ? never : events.closeTimeout.promise, + onExit === false ? never : events.exitTimeout.promise + ]); + configureTimeout(onClose, events.close, events.closeTimeout); + configureTimeout(onExit, events.exit, events.exitTimeout); + return { + close(code) { + exitCode = code; + events.close.done(); + }, + exit(code) { + exitCode = code; + events.exit.done(); + }, + get exitCode() { + return exitCode; + }, + result + }; + } + function configureTimeout(flag, event, timeout) { + if (flag === false) { + return; + } + (flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done); + } + return { + type: "spawn.after", + action(_0, _1) { + return __async(this, arguments, function* (_data, { spawned, close }) { + var _a3, _b; + const events = createEvents(); + let deferClose = true; + let quickClose = () => void (deferClose = false); + (_a3 = spawned.stdout) == null ? void 0 : _a3.on("data", quickClose); + (_b = spawned.stderr) == null ? void 0 : _b.on("data", quickClose); + spawned.on("error", quickClose); + spawned.on("close", (code) => events.close(code)); + spawned.on("exit", (code) => events.exit(code)); + try { + yield events.result; + if (deferClose) { + yield delay(50); + } + close(events.exitCode); + } catch (err) { + close(events.exitCode, err); + } + }); + } + }; +} +var import_promise_deferred, never; +var init_completion_detection_plugin = __esm({ + "src/lib/plugins/completion-detection.plugin.ts"() { + "use strict"; + import_promise_deferred = require("@kwsites/promise-deferred"); + init_utils(); + never = (0, import_promise_deferred.deferred)().promise; + } +}); + +// src/lib/plugins/custom-binary.plugin.ts +function isBadArgument(arg) { + return !arg || !/^([a-z]:)?([a-z0-9/.\\_-]+)$/i.test(arg); +} +function toBinaryConfig(input, allowUnsafe) { + if (input.length < 1 || input.length > 2) { + throw new GitPluginError(void 0, "binary", WRONG_NUMBER_ERR); + } + const isBad = input.some(isBadArgument); + if (isBad) { + if (allowUnsafe) { + console.warn(WRONG_CHARS_ERR); + } else { + throw new GitPluginError(void 0, "binary", WRONG_CHARS_ERR); + } + } + const [binary, prefix] = input; + return { + binary, + prefix + }; +} +function customBinaryPlugin(plugins, input = ["git"], allowUnsafe = false) { + let config = toBinaryConfig(asArray(input), allowUnsafe); + plugins.on("binary", (input2) => { + config = toBinaryConfig(asArray(input2), allowUnsafe); + }); + plugins.append("spawn.binary", () => { + return config.binary; + }); + plugins.append("spawn.args", (data) => { + return config.prefix ? [config.prefix, ...data] : data; + }); +} +var WRONG_NUMBER_ERR, WRONG_CHARS_ERR; +var init_custom_binary_plugin = __esm({ + "src/lib/plugins/custom-binary.plugin.ts"() { + "use strict"; + init_git_plugin_error(); + init_utils(); + WRONG_NUMBER_ERR = `Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`; + WRONG_CHARS_ERR = `Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`; + } +}); + +// src/lib/plugins/error-detection.plugin.ts +function isTaskError(result) { + return !!(result.exitCode && result.stdErr.length); +} +function getErrorMessage(result) { + return Buffer.concat([...result.stdOut, ...result.stdErr]); +} +function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage) { + return (error, result) => { + if (!overwrite && error || !isError(result)) { + return error; + } + return errorMessage(result); + }; +} +function errorDetectionPlugin(config) { + return { + type: "task.error", + action(data, context) { + const error = config(data.error, { + stdErr: context.stdErr, + stdOut: context.stdOut, + exitCode: context.exitCode + }); + if (Buffer.isBuffer(error)) { + return { error: new GitError(void 0, error.toString("utf-8")) }; + } + return { + error + }; + } + }; +} +var init_error_detection_plugin = __esm({ + "src/lib/plugins/error-detection.plugin.ts"() { + "use strict"; + init_git_error(); + } +}); + +// src/lib/plugins/plugin-store.ts +var import_node_events, PluginStore; +var init_plugin_store = __esm({ + "src/lib/plugins/plugin-store.ts"() { + "use strict"; + import_node_events = require("node:events"); + init_utils(); + PluginStore = class { + constructor() { + this.plugins = /* @__PURE__ */ new Set(); + this.events = new import_node_events.EventEmitter(); + } + on(type, listener) { + this.events.on(type, listener); + } + reconfigure(type, data) { + this.events.emit(type, data); + } + append(type, action) { + const plugin = append(this.plugins, { type, action }); + return () => this.plugins.delete(plugin); + } + add(plugin) { + const plugins = []; + asArray(plugin).forEach((plugin2) => plugin2 && this.plugins.add(append(plugins, plugin2))); + return () => { + plugins.forEach((plugin2) => this.plugins.delete(plugin2)); + }; + } + exec(type, data, context) { + let output = data; + const contextual = Object.freeze(Object.create(context)); + for (const plugin of this.plugins) { + if (plugin.type === type) { + output = plugin.action(output, contextual); + } + } + return output; + } + }; + } +}); + +// src/lib/plugins/progress-monitor-plugin.ts +function progressMonitorPlugin(progress) { + const progressCommand = "--progress"; + const progressMethods = ["checkout", "clone", "fetch", "pull", "push"]; + const onProgress = { + type: "spawn.after", + action(_data, context) { + var _a2; + if (!context.commands.includes(progressCommand)) { + return; + } + (_a2 = context.spawned.stderr) == null ? void 0 : _a2.on("data", (chunk) => { + const message = /^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(chunk.toString("utf8")); + if (!message) { + return; + } + progress({ + method: context.method, + stage: progressEventStage(message[1]), + progress: asNumber(message[2]), + processed: asNumber(message[3]), + total: asNumber(message[4]) + }); + }); + } + }; + const onArgs = { + type: "spawn.args", + action(args, context) { + if (!progressMethods.includes(context.method)) { + return args; + } + return including(args, progressCommand); + } + }; + return [onArgs, onProgress]; +} +function progressEventStage(input) { + return String(input.toLowerCase().split(" ", 1)) || "unknown"; +} +var init_progress_monitor_plugin = __esm({ + "src/lib/plugins/progress-monitor-plugin.ts"() { + "use strict"; + init_utils(); + } +}); + +// src/lib/plugins/simple-git-plugin.ts +var init_simple_git_plugin = __esm({ + "src/lib/plugins/simple-git-plugin.ts"() { + "use strict"; + } +}); + +// src/lib/plugins/spawn-options-plugin.ts +function spawnOptionsPlugin(spawnOptions) { + const options = pick(spawnOptions, ["uid", "gid"]); + return { + type: "spawn.options", + action(data) { + return __spreadValues(__spreadValues({}, options), data); + } + }; +} +var init_spawn_options_plugin = __esm({ + "src/lib/plugins/spawn-options-plugin.ts"() { + "use strict"; + init_utils(); + } +}); + +// src/lib/plugins/timout-plugin.ts +function timeoutPlugin({ + block, + stdErr = true, + stdOut = true +}) { + if (block > 0) { + return { + type: "spawn.after", + action(_data, context) { + var _a2, _b; + let timeout; + function wait() { + timeout && clearTimeout(timeout); + timeout = setTimeout(kill, block); + } + function stop() { + var _a3, _b2; + (_a3 = context.spawned.stdout) == null ? void 0 : _a3.off("data", wait); + (_b2 = context.spawned.stderr) == null ? void 0 : _b2.off("data", wait); + context.spawned.off("exit", stop); + context.spawned.off("close", stop); + timeout && clearTimeout(timeout); + } + function kill() { + stop(); + context.kill(new GitPluginError(void 0, "timeout", `block timeout reached`)); + } + stdOut && ((_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait)); + stdErr && ((_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait)); + context.spawned.on("exit", stop); + context.spawned.on("close", stop); + wait(); + } + }; + } +} +var init_timout_plugin = __esm({ + "src/lib/plugins/timout-plugin.ts"() { + "use strict"; + init_git_plugin_error(); + } +}); + +// src/lib/plugins/index.ts +var init_plugins = __esm({ + "src/lib/plugins/index.ts"() { + "use strict"; + init_abort_plugin(); + init_block_unsafe_operations_plugin(); + init_command_config_prefixing_plugin(); + init_completion_detection_plugin(); + init_custom_binary_plugin(); + init_error_detection_plugin(); + init_plugin_store(); + init_progress_monitor_plugin(); + init_simple_git_plugin(); + init_spawn_options_plugin(); + init_timout_plugin(); + } +}); + +// src/lib/plugins/suffix-paths.plugin.ts +function suffixPathsPlugin() { + return { + type: "spawn.args", + action(data) { + const prefix = []; + let suffix; + function append2(args) { + (suffix = suffix || []).push(...args); + } + for (let i = 0; i < data.length; i++) { + const param = data[i]; + if (isPathSpec(param)) { + append2(toPaths(param)); + continue; + } + if (param === "--") { + append2( + data.slice(i + 1).flatMap((item) => isPathSpec(item) && toPaths(item) || item) + ); + break; + } + prefix.push(param); + } + return !suffix ? prefix : [...prefix, "--", ...suffix.map(String)]; + } + }; +} +var init_suffix_paths_plugin = __esm({ + "src/lib/plugins/suffix-paths.plugin.ts"() { + "use strict"; + init_pathspec(); + } +}); + +// src/lib/git-logger.ts +function createLog() { + return (0, import_debug.default)("simple-git"); +} +function prefixedLogger(to, prefix, forward) { + if (!prefix || !String(prefix).replace(/\s*/, "")) { + return !forward ? to : (message, ...args) => { + to(message, ...args); + forward(message, ...args); + }; + } + return (message, ...args) => { + to(`%s ${message}`, prefix, ...args); + if (forward) { + forward(message, ...args); + } + }; +} +function childLoggerName(name, childDebugger, { namespace: parentNamespace }) { + if (typeof name === "string") { + return name; + } + const childNamespace = childDebugger && childDebugger.namespace || ""; + if (childNamespace.startsWith(parentNamespace)) { + return childNamespace.substr(parentNamespace.length + 1); + } + return childNamespace || parentNamespace; +} +function createLogger(label, verbose, initialStep, infoDebugger = createLog()) { + const labelPrefix = label && `[${label}]` || ""; + const spawned = []; + const debugDebugger = typeof verbose === "string" ? infoDebugger.extend(verbose) : verbose; + const key = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger); + return step(initialStep); + function sibling(name, initial) { + return append( + spawned, + createLogger(label, key.replace(/^[^:]+/, name), initial, infoDebugger) + ); + } + function step(phase) { + const stepPrefix = phase && `[${phase}]` || ""; + const debug2 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP; + const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug2); + return Object.assign(debugDebugger ? debug2 : info, { + label, + sibling, + info, + step + }); + } +} +var import_debug; +var init_git_logger = __esm({ + "src/lib/git-logger.ts"() { + "use strict"; + import_debug = __toESM(require("debug")); + init_utils(); + import_debug.default.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-"); + import_debug.default.formatters.B = (value) => { + if (Buffer.isBuffer(value)) { + return value.toString("utf8"); + } + return objectToString(value); + }; + } +}); + +// src/lib/runners/tasks-pending-queue.ts +var _TasksPendingQueue, TasksPendingQueue; +var init_tasks_pending_queue = __esm({ + "src/lib/runners/tasks-pending-queue.ts"() { + "use strict"; + init_git_error(); + init_git_logger(); + _TasksPendingQueue = class { + constructor(logLabel = "GitExecutor") { + this.logLabel = logLabel; + this._queue = /* @__PURE__ */ new Map(); + } + withProgress(task) { + return this._queue.get(task); + } + createProgress(task) { + const name = _TasksPendingQueue.getName(task.commands[0]); + const logger = createLogger(this.logLabel, name); + return { + task, + logger, + name + }; + } + push(task) { + const progress = this.createProgress(task); + progress.logger("Adding task to the queue, commands = %o", task.commands); + this._queue.set(task, progress); + return progress; + } + fatal(err) { + for (const [task, { logger }] of Array.from(this._queue.entries())) { + if (task === err.task) { + logger.info(`Failed %o`, err); + logger( + `Fatal exception, any as-yet un-started tasks run through this executor will not be attempted` + ); + } else { + logger.info( + `A fatal exception occurred in a previous task, the queue has been purged: %o`, + err.message + ); + } + this.complete(task); + } + if (this._queue.size !== 0) { + throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`); + } + } + complete(task) { + const progress = this.withProgress(task); + if (progress) { + this._queue.delete(task); + } + } + attempt(task) { + const progress = this.withProgress(task); + if (!progress) { + throw new GitError(void 0, "TasksPendingQueue: attempt called for an unknown task"); + } + progress.logger("Starting task"); + return progress; + } + static getName(name = "empty") { + return `task:${name}:${++_TasksPendingQueue.counter}`; + } + }; + TasksPendingQueue = _TasksPendingQueue; + TasksPendingQueue.counter = 0; + } +}); + +// src/lib/runners/git-executor-chain.ts +function pluginContext(task, commands) { + return { + method: first(task.commands) || "", + commands + }; +} +function onErrorReceived(target, logger) { + return (err) => { + logger(`[ERROR] child process exception %o`, err); + target.push(Buffer.from(String(err.stack), "ascii")); + }; +} +function onDataReceived(target, name, logger, output) { + return (buffer) => { + logger(`%s received %L bytes`, name, buffer); + output(`%B`, buffer); + target.push(buffer); + }; +} +var import_child_process, GitExecutorChain; +var init_git_executor_chain = __esm({ + "src/lib/runners/git-executor-chain.ts"() { + "use strict"; + import_child_process = require("child_process"); + init_git_error(); + init_task(); + init_utils(); + init_tasks_pending_queue(); + GitExecutorChain = class { + constructor(_executor, _scheduler, _plugins) { + this._executor = _executor; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = Promise.resolve(); + this._queue = new TasksPendingQueue(); + } + get cwd() { + return this._cwd || this._executor.cwd; + } + set cwd(cwd) { + this._cwd = cwd; + } + get env() { + return this._executor.env; + } + get outputHandler() { + return this._executor.outputHandler; + } + chain() { + return this; + } + push(task) { + this._queue.push(task); + return this._chain = this._chain.then(() => this.attemptTask(task)); + } + attemptTask(task) { + return __async(this, null, function* () { + const onScheduleComplete = yield this._scheduler.next(); + const onQueueComplete = () => this._queue.complete(task); + try { + const { logger } = this._queue.attempt(task); + return yield isEmptyTask(task) ? this.attemptEmptyTask(task, logger) : this.attemptRemoteTask(task, logger); + } catch (e) { + throw this.onFatalException(task, e); + } finally { + onQueueComplete(); + onScheduleComplete(); + } + }); + } + onFatalException(task, e) { + const gitError = e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e)); + this._chain = Promise.resolve(); + this._queue.fatal(gitError); + return gitError; + } + attemptRemoteTask(task, logger) { + return __async(this, null, function* () { + const binary = this._plugins.exec("spawn.binary", "", pluginContext(task, task.commands)); + const args = this._plugins.exec( + "spawn.args", + [...task.commands], + pluginContext(task, task.commands) + ); + const raw = yield this.gitResponse( + task, + binary, + args, + this.outputHandler, + logger.step("SPAWN") + ); + const outputStreams = yield this.handleTaskData(task, args, raw, logger.step("HANDLE")); + logger(`passing response to task's parser as a %s`, task.format); + if (isBufferTask(task)) { + return callTaskParser(task.parser, outputStreams); + } + return callTaskParser(task.parser, outputStreams.asStrings()); + }); + } + attemptEmptyTask(task, logger) { + return __async(this, null, function* () { + logger(`empty task bypassing child process to call to task's parser`); + return task.parser(this); + }); + } + handleTaskData(task, args, result, logger) { + const { exitCode, rejection, stdOut, stdErr } = result; + return new Promise((done, fail) => { + logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode); + const { error } = this._plugins.exec( + "task.error", + { error: rejection }, + __spreadValues(__spreadValues({}, pluginContext(task, args)), result) + ); + if (error && task.onError) { + logger.info(`exitCode=%s handling with custom error handler`); + return task.onError( + result, + error, + (newStdOut) => { + logger.info(`custom error handler treated as success`); + logger(`custom error returned a %s`, objectToString(newStdOut)); + done( + new GitOutputStreams( + Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut, + Buffer.concat(stdErr) + ) + ); + }, + fail + ); + } + if (error) { + logger.info( + `handling as error: exitCode=%s stdErr=%s rejection=%o`, + exitCode, + stdErr.length, + rejection + ); + return fail(error); + } + logger.info(`retrieving task output complete`); + done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr))); + }); + } + gitResponse(task, command, args, outputHandler, logger) { + return __async(this, null, function* () { + const outputLogger = logger.sibling("output"); + const spawnOptions = this._plugins.exec( + "spawn.options", + { + cwd: this.cwd, + env: this.env, + windowsHide: true + }, + pluginContext(task, task.commands) + ); + return new Promise((done) => { + const stdOut = []; + const stdErr = []; + logger.info(`%s %o`, command, args); + logger("%O", spawnOptions); + let rejection = this._beforeSpawn(task, args); + if (rejection) { + return done({ + stdOut, + stdErr, + exitCode: 9901, + rejection + }); + } + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + const spawned = (0, import_child_process.spawn)(command, args, spawnOptions); + spawned.stdout.on( + "data", + onDataReceived(stdOut, "stdOut", logger, outputLogger.step("stdOut")) + ); + spawned.stderr.on( + "data", + onDataReceived(stdErr, "stdErr", logger, outputLogger.step("stdErr")) + ); + spawned.on("error", onErrorReceived(stdErr, logger)); + if (outputHandler) { + logger(`Passing child process stdOut/stdErr to custom outputHandler`); + outputHandler(command, spawned.stdout, spawned.stderr, [...args]); + } + this._plugins.exec("spawn.after", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + spawned, + close(exitCode, reason) { + done({ + stdOut, + stdErr, + exitCode, + rejection: rejection || reason + }); + }, + kill(reason) { + if (spawned.killed) { + return; + } + rejection = reason; + spawned.kill("SIGINT"); + } + })); + }); + }); + } + _beforeSpawn(task, args) { + let rejection; + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + return rejection; + } + }; + } +}); + +// src/lib/runners/git-executor.ts +var git_executor_exports = {}; +__export(git_executor_exports, { + GitExecutor: () => GitExecutor +}); +var GitExecutor; +var init_git_executor = __esm({ + "src/lib/runners/git-executor.ts"() { + "use strict"; + init_git_executor_chain(); + GitExecutor = class { + constructor(cwd, _scheduler, _plugins) { + this.cwd = cwd; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = new GitExecutorChain(this, this._scheduler, this._plugins); + } + chain() { + return new GitExecutorChain(this, this._scheduler, this._plugins); + } + push(task) { + return this._chain.push(task); + } + }; + } +}); + +// src/lib/task-callback.ts +function taskCallback(task, response, callback = NOOP) { + const onSuccess = (data) => { + callback(null, data); + }; + const onError2 = (err) => { + if ((err == null ? void 0 : err.task) === task) { + callback( + err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err, + void 0 + ); + } + }; + response.then(onSuccess, onError2); +} +function addDeprecationNoticeToError(err) { + let log = (name) => { + console.warn( + `simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3` + ); + log = NOOP; + }; + return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {})); + function descriptorReducer(all, name) { + if (name in err) { + return all; + } + all[name] = { + enumerable: false, + configurable: false, + get() { + log(name); + return err.git[name]; + } + }; + return all; + } +} +var init_task_callback = __esm({ + "src/lib/task-callback.ts"() { + "use strict"; + init_git_response_error(); + init_utils(); + } +}); + +// src/lib/tasks/change-working-directory.ts +function changeWorkingDirectoryTask(directory, root) { + return adhocExecTask((instance) => { + if (!folderExists(directory)) { + throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`); + } + return (root || instance).cwd = directory; + }); +} +var init_change_working_directory = __esm({ + "src/lib/tasks/change-working-directory.ts"() { + "use strict"; + init_utils(); + init_task(); + } +}); + +// src/lib/tasks/checkout.ts +function checkoutTask(args) { + const commands = ["checkout", ...args]; + if (commands[1] === "-b" && commands.includes("-B")) { + commands[1] = remove(commands, "-B"); + } + return straightThroughStringTask(commands); +} +function checkout_default() { + return { + checkout() { + return this._runTask( + checkoutTask(getTrailingOptions(arguments, 1)), + trailingFunctionArgument(arguments) + ); + }, + checkoutBranch(branchName, startPoint) { + return this._runTask( + checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]), + trailingFunctionArgument(arguments) + ); + }, + checkoutLocalBranch(branchName) { + return this._runTask( + checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]), + trailingFunctionArgument(arguments) + ); + } + }; +} +var init_checkout = __esm({ + "src/lib/tasks/checkout.ts"() { + "use strict"; + init_utils(); + init_task(); + } +}); + +// src/lib/parsers/parse-commit.ts +function parseCommitResult(stdOut) { + const result = { + author: null, + branch: "", + commit: "", + root: false, + summary: { + changes: 0, + insertions: 0, + deletions: 0 + } + }; + return parseStringResponse(result, parsers, stdOut); +} +var parsers; +var init_parse_commit = __esm({ + "src/lib/parsers/parse-commit.ts"() { + "use strict"; + init_utils(); + parsers = [ + new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch, root, commit]) => { + result.branch = branch; + result.commit = commit; + result.root = !!root; + }), + new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => { + const parts = author.split("<"); + const email = parts.pop(); + if (!email || !email.includes("@")) { + return; + } + result.author = { + email: email.substr(0, email.length - 1), + name: parts.join("<").trim() + }; + }), + new LineParser( + /(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g, + (result, [changes, insertions, deletions]) => { + result.summary.changes = parseInt(changes, 10) || 0; + result.summary.insertions = parseInt(insertions, 10) || 0; + result.summary.deletions = parseInt(deletions, 10) || 0; + } + ), + new LineParser( + /^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/, + (result, [changes, lines, direction]) => { + result.summary.changes = parseInt(changes, 10) || 0; + const count = parseInt(lines, 10) || 0; + if (direction === "-") { + result.summary.deletions = count; + } else if (direction === "+") { + result.summary.insertions = count; + } + } + ) + ]; + } +}); + +// src/lib/tasks/commit.ts +function commitTask(message, files, customArgs) { + const commands = [ + "-c", + "core.abbrev=40", + "commit", + ...prefixedArray(message, "-m"), + ...files, + ...customArgs + ]; + return { + commands, + format: "utf-8", + parser: parseCommitResult + }; +} +function commit_default() { + return { + commit(message, ...rest) { + const next = trailingFunctionArgument(arguments); + const task = rejectDeprecatedSignatures(message) || commitTask( + asArray(message), + asArray(filterType(rest[0], filterStringOrStringArray, [])), + [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)] + ); + return this._runTask(task, next); + } + }; + function rejectDeprecatedSignatures(message) { + return !filterStringOrStringArray(message) && configurationErrorTask( + `git.commit: requires the commit message to be supplied as a string/string[]` + ); + } +} +var init_commit = __esm({ + "src/lib/tasks/commit.ts"() { + "use strict"; + init_parse_commit(); + init_utils(); + init_task(); + } +}); + +// src/lib/tasks/first-commit.ts +function first_commit_default() { + return { + firstCommit() { + return this._runTask( + straightThroughStringTask(["rev-list", "--max-parents=0", "HEAD"], true), + trailingFunctionArgument(arguments) + ); + } + }; +} +var init_first_commit = __esm({ + "src/lib/tasks/first-commit.ts"() { + "use strict"; + init_utils(); + init_task(); + } +}); + +// src/lib/tasks/hash-object.ts +function hashObjectTask(filePath, write) { + const commands = ["hash-object", filePath]; + if (write) { + commands.push("-w"); + } + return straightThroughStringTask(commands, true); +} +var init_hash_object = __esm({ + "src/lib/tasks/hash-object.ts"() { + "use strict"; + init_task(); + } +}); + +// src/lib/responses/InitSummary.ts +function parseInit(bare, path, text) { + const response = String(text).trim(); + let result; + if (result = initResponseRegex.exec(response)) { + return new InitSummary(bare, path, false, result[1]); + } + if (result = reInitResponseRegex.exec(response)) { + return new InitSummary(bare, path, true, result[1]); + } + let gitDir = ""; + const tokens = response.split(" "); + while (tokens.length) { + const token = tokens.shift(); + if (token === "in") { + gitDir = tokens.join(" "); + break; + } + } + return new InitSummary(bare, path, /^re/i.test(response), gitDir); +} +var InitSummary, initResponseRegex, reInitResponseRegex; +var init_InitSummary = __esm({ + "src/lib/responses/InitSummary.ts"() { + "use strict"; + InitSummary = class { + constructor(bare, path, existing, gitDir) { + this.bare = bare; + this.path = path; + this.existing = existing; + this.gitDir = gitDir; + } + }; + initResponseRegex = /^Init.+ repository in (.+)$/; + reInitResponseRegex = /^Rein.+ in (.+)$/; + } +}); + +// src/lib/tasks/init.ts +function hasBareCommand(command) { + return command.includes(bareCommand); +} +function initTask(bare = false, path, customArgs) { + const commands = ["init", ...customArgs]; + if (bare && !hasBareCommand(commands)) { + commands.splice(1, 0, bareCommand); + } + return { + commands, + format: "utf-8", + parser(text) { + return parseInit(commands.includes("--bare"), path, text); + } + }; +} +var bareCommand; +var init_init = __esm({ + "src/lib/tasks/init.ts"() { + "use strict"; + init_InitSummary(); + bareCommand = "--bare"; + } +}); + +// src/lib/args/log-format.ts +function logFormatFromCommand(customArgs) { + for (let i = 0; i < customArgs.length; i++) { + const format = logFormatRegex.exec(customArgs[i]); + if (format) { + return `--${format[1]}`; + } + } + return "" /* NONE */; +} +function isLogFormat(customArg) { + return logFormatRegex.test(customArg); +} +var logFormatRegex; +var init_log_format = __esm({ + "src/lib/args/log-format.ts"() { + "use strict"; + logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/; + } +}); + +// src/lib/responses/DiffSummary.ts +var DiffSummary; +var init_DiffSummary = __esm({ + "src/lib/responses/DiffSummary.ts"() { + "use strict"; + DiffSummary = class { + constructor() { + this.changed = 0; + this.deletions = 0; + this.insertions = 0; + this.files = []; + } + }; + } +}); + +// src/lib/parsers/parse-diff-summary.ts +function getDiffParser(format = "" /* NONE */) { + const parser3 = diffSummaryParsers[format]; + return (stdOut) => parseStringResponse(new DiffSummary(), parser3, stdOut, false); +} +var statParser, numStatParser, nameOnlyParser, nameStatusParser, diffSummaryParsers; +var init_parse_diff_summary = __esm({ + "src/lib/parsers/parse-diff-summary.ts"() { + "use strict"; + init_log_format(); + init_DiffSummary(); + init_diff_name_status(); + init_utils(); + statParser = [ + new LineParser( + /^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/, + (result, [file, changes, alterations = ""]) => { + result.files.push({ + file: file.trim(), + changes: asNumber(changes), + insertions: alterations.replace(/[^+]/g, "").length, + deletions: alterations.replace(/[^-]/g, "").length, + binary: false + }); + } + ), + new LineParser( + /^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/, + (result, [file, before, after]) => { + result.files.push({ + file: file.trim(), + before: asNumber(before), + after: asNumber(after), + binary: true + }); + } + ), + new LineParser( + /(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/, + (result, [changed, summary]) => { + const inserted = /(\d+) i/.exec(summary); + const deleted = /(\d+) d/.exec(summary); + result.changed = asNumber(changed); + result.insertions = asNumber(inserted == null ? void 0 : inserted[1]); + result.deletions = asNumber(deleted == null ? void 0 : deleted[1]); + } + ) + ]; + numStatParser = [ + new LineParser( + /(\d+)\t(\d+)\t(.+)$/, + (result, [changesInsert, changesDelete, file]) => { + const insertions = asNumber(changesInsert); + const deletions = asNumber(changesDelete); + result.changed++; + result.insertions += insertions; + result.deletions += deletions; + result.files.push({ + file, + changes: insertions + deletions, + insertions, + deletions, + binary: false + }); + } + ), + new LineParser(/-\t-\t(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + after: 0, + before: 0, + binary: true + }); + }) + ]; + nameOnlyParser = [ + new LineParser(/(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + changes: 0, + insertions: 0, + deletions: 0, + binary: false + }); + }) + ]; + nameStatusParser = [ + new LineParser( + /([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/, + (result, [status, _similarity, from, _to, to]) => { + result.changed++; + result.files.push({ + file: to != null ? to : from, + changes: 0, + status: orVoid(isDiffNameStatus(status) && status), + insertions: 0, + deletions: 0, + binary: false + }); + } + ) + ]; + diffSummaryParsers = { + ["" /* NONE */]: statParser, + ["--stat" /* STAT */]: statParser, + ["--numstat" /* NUM_STAT */]: numStatParser, + ["--name-status" /* NAME_STATUS */]: nameStatusParser, + ["--name-only" /* NAME_ONLY */]: nameOnlyParser + }; + } +}); + +// src/lib/parsers/parse-list-log-summary.ts +function lineBuilder(tokens, fields) { + return fields.reduce( + (line, field, index) => { + line[field] = tokens[index] || ""; + return line; + }, + /* @__PURE__ */ Object.create({ diff: null }) + ); +} +function createListLogSummaryParser(splitter = SPLITTER, fields = defaultFieldNames, logFormat = "" /* NONE */) { + const parseDiffResult = getDiffParser(logFormat); + return function(stdOut) { + const all = toLinesWithContent( + stdOut, + true, + START_BOUNDARY + ).map(function(item) { + const lineDetail = item.trim().split(COMMIT_BOUNDARY); + const listLogLine = lineBuilder( + lineDetail[0].trim().split(splitter), + fields + ); + if (lineDetail.length > 1 && !!lineDetail[1].trim()) { + listLogLine.diff = parseDiffResult(lineDetail[1]); + } + return listLogLine; + }); + return { + all, + latest: all.length && all[0] || null, + total: all.length + }; + }; +} +var START_BOUNDARY, COMMIT_BOUNDARY, SPLITTER, defaultFieldNames; +var init_parse_list_log_summary = __esm({ + "src/lib/parsers/parse-list-log-summary.ts"() { + "use strict"; + init_utils(); + init_parse_diff_summary(); + init_log_format(); + START_BOUNDARY = "\xF2\xF2\xF2\xF2\xF2\xF2 "; + COMMIT_BOUNDARY = " \xF2\xF2"; + SPLITTER = " \xF2 "; + defaultFieldNames = ["hash", "date", "message", "refs", "author_name", "author_email"]; + } +}); + +// src/lib/tasks/diff.ts +var diff_exports = {}; +__export(diff_exports, { + diffSummaryTask: () => diffSummaryTask, + validateLogFormatConfig: () => validateLogFormatConfig +}); +function diffSummaryTask(customArgs) { + let logFormat = logFormatFromCommand(customArgs); + const commands = ["diff"]; + if (logFormat === "" /* NONE */) { + logFormat = "--stat" /* STAT */; + commands.push("--stat=4096"); + } + commands.push(...customArgs); + return validateLogFormatConfig(commands) || { + commands, + format: "utf-8", + parser: getDiffParser(logFormat) + }; +} +function validateLogFormatConfig(customArgs) { + const flags = customArgs.filter(isLogFormat); + if (flags.length > 1) { + return configurationErrorTask( + `Summary flags are mutually exclusive - pick one of ${flags.join(",")}` + ); + } + if (flags.length && customArgs.includes("-z")) { + return configurationErrorTask( + `Summary flag ${flags} parsing is not compatible with null termination option '-z'` + ); + } +} +var init_diff = __esm({ + "src/lib/tasks/diff.ts"() { + "use strict"; + init_log_format(); + init_parse_diff_summary(); + init_task(); + } +}); + +// src/lib/tasks/log.ts +function prettyFormat(format, splitter) { + const fields = []; + const formatStr = []; + Object.keys(format).forEach((field) => { + fields.push(field); + formatStr.push(String(format[field])); + }); + return [fields, formatStr.join(splitter)]; +} +function userOptions(input) { + return Object.keys(input).reduce((out, key) => { + if (!(key in excludeOptions)) { + out[key] = input[key]; + } + return out; + }, {}); +} +function parseLogOptions(opt = {}, customArgs = []) { + const splitter = filterType(opt.splitter, filterString, SPLITTER); + const format = !filterPrimitives(opt.format) && opt.format ? opt.format : { + hash: "%H", + date: opt.strictDate === false ? "%ai" : "%aI", + message: "%s", + refs: "%D", + body: opt.multiLine ? "%B" : "%b", + author_name: opt.mailMap !== false ? "%aN" : "%an", + author_email: opt.mailMap !== false ? "%aE" : "%ae" + }; + const [fields, formatStr] = prettyFormat(format, splitter); + const suffix = []; + const command = [ + `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`, + ...customArgs + ]; + const maxCount = opt.n || opt["max-count"] || opt.maxCount; + if (maxCount) { + command.push(`--max-count=${maxCount}`); + } + if (opt.from || opt.to) { + const rangeOperator = opt.symmetric !== false ? "..." : ".."; + suffix.push(`${opt.from || ""}${rangeOperator}${opt.to || ""}`); + } + if (filterString(opt.file)) { + command.push("--follow", pathspec(opt.file)); + } + appendTaskOptions(userOptions(opt), command); + return { + fields, + splitter, + commands: [...command, ...suffix] + }; +} +function logTask(splitter, fields, customArgs) { + const parser3 = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs)); + return { + commands: ["log", ...customArgs], + format: "utf-8", + parser: parser3 + }; +} +function log_default() { + return { + log(...rest) { + const next = trailingFunctionArgument(arguments); + const options = parseLogOptions( + trailingOptionsArgument(arguments), + filterType(arguments[0], filterArray) + ); + const task = rejectDeprecatedSignatures(...rest) || validateLogFormatConfig(options.commands) || createLogTask(options); + return this._runTask(task, next); + } + }; + function createLogTask(options) { + return logTask(options.splitter, options.fields, options.commands); + } + function rejectDeprecatedSignatures(from, to) { + return filterString(from) && filterString(to) && configurationErrorTask( + `git.log(string, string) should be replaced with git.log({ from: string, to: string })` + ); + } +} +var excludeOptions; +var init_log = __esm({ + "src/lib/tasks/log.ts"() { + "use strict"; + init_log_format(); + init_pathspec(); + init_parse_list_log_summary(); + init_utils(); + init_task(); + init_diff(); + excludeOptions = /* @__PURE__ */ ((excludeOptions2) => { + excludeOptions2[excludeOptions2["--pretty"] = 0] = "--pretty"; + excludeOptions2[excludeOptions2["max-count"] = 1] = "max-count"; + excludeOptions2[excludeOptions2["maxCount"] = 2] = "maxCount"; + excludeOptions2[excludeOptions2["n"] = 3] = "n"; + excludeOptions2[excludeOptions2["file"] = 4] = "file"; + excludeOptions2[excludeOptions2["format"] = 5] = "format"; + excludeOptions2[excludeOptions2["from"] = 6] = "from"; + excludeOptions2[excludeOptions2["to"] = 7] = "to"; + excludeOptions2[excludeOptions2["splitter"] = 8] = "splitter"; + excludeOptions2[excludeOptions2["symmetric"] = 9] = "symmetric"; + excludeOptions2[excludeOptions2["mailMap"] = 10] = "mailMap"; + excludeOptions2[excludeOptions2["multiLine"] = 11] = "multiLine"; + excludeOptions2[excludeOptions2["strictDate"] = 12] = "strictDate"; + return excludeOptions2; + })(excludeOptions || {}); + } +}); + +// src/lib/responses/MergeSummary.ts +var MergeSummaryConflict, MergeSummaryDetail; +var init_MergeSummary = __esm({ + "src/lib/responses/MergeSummary.ts"() { + "use strict"; + MergeSummaryConflict = class { + constructor(reason, file = null, meta) { + this.reason = reason; + this.file = file; + this.meta = meta; + } + toString() { + return `${this.file}:${this.reason}`; + } + }; + MergeSummaryDetail = class { + constructor() { + this.conflicts = []; + this.merges = []; + this.result = "success"; + } + get failed() { + return this.conflicts.length > 0; + } + get reason() { + return this.result; + } + toString() { + if (this.conflicts.length) { + return `CONFLICTS: ${this.conflicts.join(", ")}`; + } + return "OK"; + } + }; + } +}); + +// src/lib/responses/PullSummary.ts +var PullSummary, PullFailedSummary; +var init_PullSummary = __esm({ + "src/lib/responses/PullSummary.ts"() { + "use strict"; + PullSummary = class { + constructor() { + this.remoteMessages = { + all: [] + }; + this.created = []; + this.deleted = []; + this.files = []; + this.deletions = {}; + this.insertions = {}; + this.summary = { + changes: 0, + deletions: 0, + insertions: 0 + }; + } + }; + PullFailedSummary = class { + constructor() { + this.remote = ""; + this.hash = { + local: "", + remote: "" + }; + this.branch = { + local: "", + remote: "" + }; + this.message = ""; + } + toString() { + return this.message; + } + }; + } +}); + +// src/lib/parsers/parse-remote-objects.ts +function objectEnumerationResult(remoteMessages) { + return remoteMessages.objects = remoteMessages.objects || { + compressing: 0, + counting: 0, + enumerating: 0, + packReused: 0, + reused: { count: 0, delta: 0 }, + total: { count: 0, delta: 0 } + }; +} +function asObjectCount(source) { + const count = /^\s*(\d+)/.exec(source); + const delta = /delta (\d+)/i.exec(source); + return { + count: asNumber(count && count[1] || "0"), + delta: asNumber(delta && delta[1] || "0") + }; +} +var remoteMessagesObjectParsers; +var init_parse_remote_objects = __esm({ + "src/lib/parsers/parse-remote-objects.ts"() { + "use strict"; + init_utils(); + remoteMessagesObjectParsers = [ + new RemoteLineParser( + /^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i, + (result, [action, count]) => { + const key = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key]: asNumber(count) }); + } + ), + new RemoteLineParser( + /^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i, + (result, [action, count]) => { + const key = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key]: asNumber(count) }); + } + ), + new RemoteLineParser( + /total ([^,]+), reused ([^,]+), pack-reused (\d+)/i, + (result, [total, reused, packReused]) => { + const objects = objectEnumerationResult(result.remoteMessages); + objects.total = asObjectCount(total); + objects.reused = asObjectCount(reused); + objects.packReused = asNumber(packReused); + } + ) + ]; + } +}); + +// src/lib/parsers/parse-remote-messages.ts +function parseRemoteMessages(_stdOut, stdErr) { + return parseStringResponse({ remoteMessages: new RemoteMessageSummary() }, parsers2, stdErr); +} +var parsers2, RemoteMessageSummary; +var init_parse_remote_messages = __esm({ + "src/lib/parsers/parse-remote-messages.ts"() { + "use strict"; + init_utils(); + init_parse_remote_objects(); + parsers2 = [ + new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text]) => { + result.remoteMessages.all.push(text.trim()); + return false; + }), + ...remoteMessagesObjectParsers, + new RemoteLineParser( + [/create a (?:pull|merge) request/i, /\s(https?:\/\/\S+)$/], + (result, [pullRequestUrl]) => { + result.remoteMessages.pullRequestUrl = pullRequestUrl; + } + ), + new RemoteLineParser( + [/found (\d+) vulnerabilities.+\(([^)]+)\)/i, /\s(https?:\/\/\S+)$/], + (result, [count, summary, url]) => { + result.remoteMessages.vulnerabilities = { + count: asNumber(count), + summary, + url + }; + } + ) + ]; + RemoteMessageSummary = class { + constructor() { + this.all = []; + } + }; + } +}); + +// src/lib/parsers/parse-pull.ts +function parsePullErrorResult(stdOut, stdErr) { + const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]); + return pullError.message && pullError; +} +var FILE_UPDATE_REGEX, SUMMARY_REGEX, ACTION_REGEX, parsers3, errorParsers, parsePullDetail, parsePullResult; +var init_parse_pull = __esm({ + "src/lib/parsers/parse-pull.ts"() { + "use strict"; + init_PullSummary(); + init_utils(); + init_parse_remote_messages(); + FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/; + SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/; + ACTION_REGEX = /^(create|delete) mode \d+ (.+)/; + parsers3 = [ + new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => { + result.files.push(file); + if (insertions) { + result.insertions[file] = insertions.length; + } + if (deletions) { + result.deletions[file] = deletions.length; + } + }), + new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => { + if (insertions !== void 0 || deletions !== void 0) { + result.summary.changes = +changes || 0; + result.summary.insertions = +insertions || 0; + result.summary.deletions = +deletions || 0; + return true; + } + return false; + }), + new LineParser(ACTION_REGEX, (result, [action, file]) => { + append(result.files, file); + append(action === "create" ? result.created : result.deleted, file); + }) + ]; + errorParsers = [ + new LineParser(/^from\s(.+)$/i, (result, [remote]) => void (result.remote = remote)), + new LineParser(/^fatal:\s(.+)$/, (result, [message]) => void (result.message = message)), + new LineParser( + /([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/, + (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => { + result.branch.local = branchLocal; + result.hash.local = hashLocal; + result.branch.remote = branchRemote; + result.hash.remote = hashRemote; + } + ) + ]; + parsePullDetail = (stdOut, stdErr) => { + return parseStringResponse(new PullSummary(), parsers3, [stdOut, stdErr]); + }; + parsePullResult = (stdOut, stdErr) => { + return Object.assign( + new PullSummary(), + parsePullDetail(stdOut, stdErr), + parseRemoteMessages(stdOut, stdErr) + ); + }; + } +}); + +// src/lib/parsers/parse-merge.ts +var parsers4, parseMergeResult, parseMergeDetail; +var init_parse_merge = __esm({ + "src/lib/parsers/parse-merge.ts"() { + "use strict"; + init_MergeSummary(); + init_utils(); + init_parse_pull(); + parsers4 = [ + new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => { + summary.merges.push(autoMerge); + }), + new LineParser(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/, (summary, [reason, file]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file)); + }), + new LineParser( + /^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/, + (summary, [reason, file, deleteRef]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef })); + } + ), + new LineParser(/^CONFLICT\s+\((.+)\):/, (summary, [reason]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, null)); + }), + new LineParser(/^Automatic merge failed;\s+(.+)$/, (summary, [result]) => { + summary.result = result; + }) + ]; + parseMergeResult = (stdOut, stdErr) => { + return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr)); + }; + parseMergeDetail = (stdOut) => { + return parseStringResponse(new MergeSummaryDetail(), parsers4, stdOut); + }; + } +}); + +// src/lib/tasks/merge.ts +function mergeTask(customArgs) { + if (!customArgs.length) { + return configurationErrorTask("Git.merge requires at least one option"); + } + return { + commands: ["merge", ...customArgs], + format: "utf-8", + parser(stdOut, stdErr) { + const merge = parseMergeResult(stdOut, stdErr); + if (merge.failed) { + throw new GitResponseError(merge); + } + return merge; + } + }; +} +var init_merge = __esm({ + "src/lib/tasks/merge.ts"() { + "use strict"; + init_git_response_error(); + init_parse_merge(); + init_task(); + } +}); + +// src/lib/parsers/parse-push.ts +function pushResultPushedItem(local, remote, status) { + const deleted = status.includes("deleted"); + const tag = status.includes("tag") || /^refs\/tags/.test(local); + const alreadyUpdated = !status.includes("new"); + return { + deleted, + tag, + branch: !tag, + new: !alreadyUpdated, + alreadyUpdated, + local, + remote + }; +} +var parsers5, parsePushResult, parsePushDetail; +var init_parse_push = __esm({ + "src/lib/parsers/parse-push.ts"() { + "use strict"; + init_utils(); + init_parse_remote_messages(); + parsers5 = [ + new LineParser(/^Pushing to (.+)$/, (result, [repo]) => { + result.repo = repo; + }), + new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => { + result.ref = __spreadProps(__spreadValues({}, result.ref || {}), { + local + }); + }), + new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => { + result.pushed.push(pushResultPushedItem(local, remote, type)); + }), + new LineParser( + /^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/, + (result, [local, remote, remoteName]) => { + result.branch = __spreadProps(__spreadValues({}, result.branch || {}), { + local, + remote, + remoteName + }); + } + ), + new LineParser( + /^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/, + (result, [local, remote, from, to]) => { + result.update = { + head: { + local, + remote + }, + hash: { + from, + to + } + }; + } + ) + ]; + parsePushResult = (stdOut, stdErr) => { + const pushDetail = parsePushDetail(stdOut, stdErr); + const responseDetail = parseRemoteMessages(stdOut, stdErr); + return __spreadValues(__spreadValues({}, pushDetail), responseDetail); + }; + parsePushDetail = (stdOut, stdErr) => { + return parseStringResponse({ pushed: [] }, parsers5, [stdOut, stdErr]); + }; + } +}); + +// src/lib/tasks/push.ts +var push_exports = {}; +__export(push_exports, { + pushTagsTask: () => pushTagsTask, + pushTask: () => pushTask +}); +function pushTagsTask(ref = {}, customArgs) { + append(customArgs, "--tags"); + return pushTask(ref, customArgs); +} +function pushTask(ref = {}, customArgs) { + const commands = ["push", ...customArgs]; + if (ref.branch) { + commands.splice(1, 0, ref.branch); + } + if (ref.remote) { + commands.splice(1, 0, ref.remote); + } + remove(commands, "-v"); + append(commands, "--verbose"); + append(commands, "--porcelain"); + return { + commands, + format: "utf-8", + parser: parsePushResult + }; +} +var init_push = __esm({ + "src/lib/tasks/push.ts"() { + "use strict"; + init_parse_push(); + init_utils(); + } +}); + +// src/lib/tasks/show.ts +function show_default() { + return { + showBuffer() { + const commands = ["show", ...getTrailingOptions(arguments, 1)]; + if (!commands.includes("--binary")) { + commands.splice(1, 0, "--binary"); + } + return this._runTask( + straightThroughBufferTask(commands), + trailingFunctionArgument(arguments) + ); + }, + show() { + const commands = ["show", ...getTrailingOptions(arguments, 1)]; + return this._runTask( + straightThroughStringTask(commands), + trailingFunctionArgument(arguments) + ); + } + }; +} +var init_show = __esm({ + "src/lib/tasks/show.ts"() { + "use strict"; + init_utils(); + init_task(); + } +}); + +// src/lib/responses/FileStatusSummary.ts +var fromPathRegex, FileStatusSummary; +var init_FileStatusSummary = __esm({ + "src/lib/responses/FileStatusSummary.ts"() { + "use strict"; + fromPathRegex = /^(.+) -> (.+)$/; + FileStatusSummary = class { + constructor(path, index, working_dir) { + this.path = path; + this.index = index; + this.working_dir = working_dir; + if ("R" === index + working_dir) { + const detail = fromPathRegex.exec(path) || [null, path, path]; + this.from = detail[1] || ""; + this.path = detail[2] || ""; + } + } + }; + } +}); + +// src/lib/responses/StatusSummary.ts +function renamedFile(line) { + const [to, from] = line.split(NULL); + return { + from: from || to, + to + }; +} +function parser2(indexX, indexY, handler) { + return [`${indexX}${indexY}`, handler]; +} +function conflicts(indexX, ...indexY) { + return indexY.map((y) => parser2(indexX, y, (result, file) => append(result.conflicted, file))); +} +function splitLine(result, lineStr) { + const trimmed2 = lineStr.trim(); + switch (" ") { + case trimmed2.charAt(2): + return data(trimmed2.charAt(0), trimmed2.charAt(1), trimmed2.substr(3)); + case trimmed2.charAt(1): + return data(" " /* NONE */, trimmed2.charAt(0), trimmed2.substr(2)); + default: + return; + } + function data(index, workingDir, path) { + const raw = `${index}${workingDir}`; + const handler = parsers6.get(raw); + if (handler) { + handler(result, path); + } + if (raw !== "##" && raw !== "!!") { + result.files.push(new FileStatusSummary(path.replace(/\0.+$/, ""), index, workingDir)); + } + } +} +var StatusSummary, parsers6, parseStatusSummary; +var init_StatusSummary = __esm({ + "src/lib/responses/StatusSummary.ts"() { + "use strict"; + init_utils(); + init_FileStatusSummary(); + StatusSummary = class { + constructor() { + this.not_added = []; + this.conflicted = []; + this.created = []; + this.deleted = []; + this.ignored = void 0; + this.modified = []; + this.renamed = []; + this.files = []; + this.staged = []; + this.ahead = 0; + this.behind = 0; + this.current = null; + this.tracking = null; + this.detached = false; + this.isClean = () => { + return !this.files.length; + }; + } + }; + parsers6 = new Map([ + parser2( + " " /* NONE */, + "A" /* ADDED */, + (result, file) => append(result.created, file) + ), + parser2( + " " /* NONE */, + "D" /* DELETED */, + (result, file) => append(result.deleted, file) + ), + parser2( + " " /* NONE */, + "M" /* MODIFIED */, + (result, file) => append(result.modified, file) + ), + parser2( + "A" /* ADDED */, + " " /* NONE */, + (result, file) => append(result.created, file) && append(result.staged, file) + ), + parser2( + "A" /* ADDED */, + "M" /* MODIFIED */, + (result, file) => append(result.created, file) && append(result.staged, file) && append(result.modified, file) + ), + parser2( + "D" /* DELETED */, + " " /* NONE */, + (result, file) => append(result.deleted, file) && append(result.staged, file) + ), + parser2( + "M" /* MODIFIED */, + " " /* NONE */, + (result, file) => append(result.modified, file) && append(result.staged, file) + ), + parser2( + "M" /* MODIFIED */, + "M" /* MODIFIED */, + (result, file) => append(result.modified, file) && append(result.staged, file) + ), + parser2("R" /* RENAMED */, " " /* NONE */, (result, file) => { + append(result.renamed, renamedFile(file)); + }), + parser2("R" /* RENAMED */, "M" /* MODIFIED */, (result, file) => { + const renamed = renamedFile(file); + append(result.renamed, renamed); + append(result.modified, renamed.to); + }), + parser2("!" /* IGNORED */, "!" /* IGNORED */, (_result, _file) => { + append(_result.ignored = _result.ignored || [], _file); + }), + parser2( + "?" /* UNTRACKED */, + "?" /* UNTRACKED */, + (result, file) => append(result.not_added, file) + ), + ...conflicts("A" /* ADDED */, "A" /* ADDED */, "U" /* UNMERGED */), + ...conflicts( + "D" /* DELETED */, + "D" /* DELETED */, + "U" /* UNMERGED */ + ), + ...conflicts( + "U" /* UNMERGED */, + "A" /* ADDED */, + "D" /* DELETED */, + "U" /* UNMERGED */ + ), + [ + "##", + (result, line) => { + const aheadReg = /ahead (\d+)/; + const behindReg = /behind (\d+)/; + const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/; + const trackingReg = /\.{3}(\S*)/; + const onEmptyBranchReg = /\son\s([\S]+)$/; + let regexResult; + regexResult = aheadReg.exec(line); + result.ahead = regexResult && +regexResult[1] || 0; + regexResult = behindReg.exec(line); + result.behind = regexResult && +regexResult[1] || 0; + regexResult = currentReg.exec(line); + result.current = regexResult && regexResult[1]; + regexResult = trackingReg.exec(line); + result.tracking = regexResult && regexResult[1]; + regexResult = onEmptyBranchReg.exec(line); + result.current = regexResult && regexResult[1] || result.current; + result.detached = /\(no branch\)/.test(line); + } + ] + ]); + parseStatusSummary = function(text) { + const lines = text.split(NULL); + const status = new StatusSummary(); + for (let i = 0, l = lines.length; i < l; ) { + let line = lines[i++].trim(); + if (!line) { + continue; + } + if (line.charAt(0) === "R" /* RENAMED */) { + line += NULL + (lines[i++] || ""); + } + splitLine(status, line); + } + return status; + }; + } +}); + +// src/lib/tasks/status.ts +function statusTask(customArgs) { + const commands = [ + "status", + "--porcelain", + "-b", + "-u", + "--null", + ...customArgs.filter((arg) => !ignoredOptions.includes(arg)) + ]; + return { + format: "utf-8", + commands, + parser(text) { + return parseStatusSummary(text); + } + }; +} +var ignoredOptions; +var init_status = __esm({ + "src/lib/tasks/status.ts"() { + "use strict"; + init_StatusSummary(); + ignoredOptions = ["--null", "-z"]; + } +}); + +// src/lib/tasks/version.ts +function versionResponse(major = 0, minor = 0, patch = 0, agent = "", installed = true) { + return Object.defineProperty( + { + major, + minor, + patch, + agent, + installed + }, + "toString", + { + value() { + return `${this.major}.${this.minor}.${this.patch}`; + }, + configurable: false, + enumerable: false + } + ); +} +function notInstalledResponse() { + return versionResponse(0, 0, 0, "", false); +} +function version_default() { + return { + version() { + return this._runTask({ + commands: ["--version"], + format: "utf-8", + parser: versionParser, + onError(result, error, done, fail) { + if (result.exitCode === -2 /* NOT_FOUND */) { + return done(Buffer.from(NOT_INSTALLED)); + } + fail(error); + } + }); + } + }; +} +function versionParser(stdOut) { + if (stdOut === NOT_INSTALLED) { + return notInstalledResponse(); + } + return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers7, stdOut); +} +var NOT_INSTALLED, parsers7; +var init_version = __esm({ + "src/lib/tasks/version.ts"() { + "use strict"; + init_utils(); + NOT_INSTALLED = "installed=false"; + parsers7 = [ + new LineParser( + /version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/, + (result, [major, minor, patch, agent = ""]) => { + Object.assign( + result, + versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent) + ); + } + ), + new LineParser( + /version (\d+)\.(\d+)\.(\D+)(.+)?$/, + (result, [major, minor, patch, agent = ""]) => { + Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent)); + } + ) + ]; + } +}); + +// src/lib/simple-git-api.ts +var simple_git_api_exports = {}; +__export(simple_git_api_exports, { + SimpleGitApi: () => SimpleGitApi +}); +var SimpleGitApi; +var init_simple_git_api = __esm({ + "src/lib/simple-git-api.ts"() { + "use strict"; + init_task_callback(); + init_change_working_directory(); + init_checkout(); + init_commit(); + init_config(); + init_first_commit(); + init_grep(); + init_hash_object(); + init_init(); + init_log(); + init_merge(); + init_push(); + init_show(); + init_status(); + init_task(); + init_version(); + init_utils(); + SimpleGitApi = class { + constructor(_executor) { + this._executor = _executor; + } + _runTask(task, then) { + const chain = this._executor.chain(); + const promise = chain.push(task); + if (then) { + taskCallback(task, promise, then); + } + return Object.create(this, { + then: { value: promise.then.bind(promise) }, + catch: { value: promise.catch.bind(promise) }, + _executor: { value: chain } + }); + } + add(files) { + return this._runTask( + straightThroughStringTask(["add", ...asArray(files)]), + trailingFunctionArgument(arguments) + ); + } + cwd(directory) { + const next = trailingFunctionArgument(arguments); + if (typeof directory === "string") { + return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next); + } + if (typeof (directory == null ? void 0 : directory.path) === "string") { + return this._runTask( + changeWorkingDirectoryTask( + directory.path, + directory.root && this._executor || void 0 + ), + next + ); + } + return this._runTask( + configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"), + next + ); + } + hashObject(path, write) { + return this._runTask( + hashObjectTask(path, write === true), + trailingFunctionArgument(arguments) + ); + } + init(bare) { + return this._runTask( + initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)), + trailingFunctionArgument(arguments) + ); + } + merge() { + return this._runTask( + mergeTask(getTrailingOptions(arguments)), + trailingFunctionArgument(arguments) + ); + } + mergeFromTo(remote, branch) { + if (!(filterString(remote) && filterString(branch))) { + return this._runTask( + configurationErrorTask( + `Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings` + ) + ); + } + return this._runTask( + mergeTask([remote, branch, ...getTrailingOptions(arguments)]), + trailingFunctionArgument(arguments, false) + ); + } + outputHandler(handler) { + this._executor.outputHandler = handler; + return this; + } + push() { + const task = pushTask( + { + remote: filterType(arguments[0], filterString), + branch: filterType(arguments[1], filterString) + }, + getTrailingOptions(arguments) + ); + return this._runTask(task, trailingFunctionArgument(arguments)); + } + stash() { + return this._runTask( + straightThroughStringTask(["stash", ...getTrailingOptions(arguments)]), + trailingFunctionArgument(arguments) + ); + } + status() { + return this._runTask( + statusTask(getTrailingOptions(arguments)), + trailingFunctionArgument(arguments) + ); + } + }; + Object.assign( + SimpleGitApi.prototype, + checkout_default(), + commit_default(), + config_default(), + first_commit_default(), + grep_default(), + log_default(), + show_default(), + version_default() + ); + } +}); + +// src/lib/runners/scheduler.ts +var scheduler_exports = {}; +__export(scheduler_exports, { + Scheduler: () => Scheduler +}); +var import_promise_deferred2, createScheduledTask, Scheduler; +var init_scheduler = __esm({ + "src/lib/runners/scheduler.ts"() { + "use strict"; + init_utils(); + import_promise_deferred2 = require("@kwsites/promise-deferred"); + init_git_logger(); + createScheduledTask = (() => { + let id = 0; + return () => { + id++; + const { promise, done } = (0, import_promise_deferred2.createDeferred)(); + return { + promise, + done, + id + }; + }; + })(); + Scheduler = class { + constructor(concurrency = 2) { + this.concurrency = concurrency; + this.logger = createLogger("", "scheduler"); + this.pending = []; + this.running = []; + this.logger(`Constructed, concurrency=%s`, concurrency); + } + schedule() { + if (!this.pending.length || this.running.length >= this.concurrency) { + this.logger( + `Schedule attempt ignored, pending=%s running=%s concurrency=%s`, + this.pending.length, + this.running.length, + this.concurrency + ); + return; + } + const task = append(this.running, this.pending.shift()); + this.logger(`Attempting id=%s`, task.id); + task.done(() => { + this.logger(`Completing id=`, task.id); + remove(this.running, task); + this.schedule(); + }); + } + next() { + const { promise, id } = append(this.pending, createScheduledTask()); + this.logger(`Scheduling id=%s`, id); + this.schedule(); + return promise; + } + }; + } +}); + +// src/lib/tasks/apply-patch.ts +var apply_patch_exports = {}; +__export(apply_patch_exports, { + applyPatchTask: () => applyPatchTask +}); +function applyPatchTask(patches, customArgs) { + return straightThroughStringTask(["apply", ...customArgs, ...patches]); +} +var init_apply_patch = __esm({ + "src/lib/tasks/apply-patch.ts"() { + "use strict"; + init_task(); + } +}); + +// src/lib/responses/BranchDeleteSummary.ts +function branchDeletionSuccess(branch, hash) { + return { + branch, + hash, + success: true + }; +} +function branchDeletionFailure(branch) { + return { + branch, + hash: null, + success: false + }; +} +var BranchDeletionBatch; +var init_BranchDeleteSummary = __esm({ + "src/lib/responses/BranchDeleteSummary.ts"() { + "use strict"; + BranchDeletionBatch = class { + constructor() { + this.all = []; + this.branches = {}; + this.errors = []; + } + get success() { + return !this.errors.length; + } + }; + } +}); + +// src/lib/parsers/parse-branch-delete.ts +function hasBranchDeletionError(data, processExitCode) { + return processExitCode === 1 /* ERROR */ && deleteErrorRegex.test(data); +} +var deleteSuccessRegex, deleteErrorRegex, parsers8, parseBranchDeletions; +var init_parse_branch_delete = __esm({ + "src/lib/parsers/parse-branch-delete.ts"() { + "use strict"; + init_BranchDeleteSummary(); + init_utils(); + deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/; + deleteErrorRegex = /^error[^']+'([^']+)'/m; + parsers8 = [ + new LineParser(deleteSuccessRegex, (result, [branch, hash]) => { + const deletion = branchDeletionSuccess(branch, hash); + result.all.push(deletion); + result.branches[branch] = deletion; + }), + new LineParser(deleteErrorRegex, (result, [branch]) => { + const deletion = branchDeletionFailure(branch); + result.errors.push(deletion); + result.all.push(deletion); + result.branches[branch] = deletion; + }) + ]; + parseBranchDeletions = (stdOut, stdErr) => { + return parseStringResponse(new BranchDeletionBatch(), parsers8, [stdOut, stdErr]); + }; + } +}); + +// src/lib/responses/BranchSummary.ts +var BranchSummaryResult; +var init_BranchSummary = __esm({ + "src/lib/responses/BranchSummary.ts"() { + "use strict"; + BranchSummaryResult = class { + constructor() { + this.all = []; + this.branches = {}; + this.current = ""; + this.detached = false; + } + push(status, detached, name, commit, label) { + if (status === "*" /* CURRENT */) { + this.detached = detached; + this.current = name; + } + this.all.push(name); + this.branches[name] = { + current: status === "*" /* CURRENT */, + linkedWorkTree: status === "+" /* LINKED */, + name, + commit, + label + }; + } + }; + } +}); + +// src/lib/parsers/parse-branch.ts +function branchStatus(input) { + return input ? input.charAt(0) : ""; +} +function parseBranchSummary(stdOut) { + return parseStringResponse(new BranchSummaryResult(), parsers9, stdOut); +} +var parsers9; +var init_parse_branch = __esm({ + "src/lib/parsers/parse-branch.ts"() { + "use strict"; + init_BranchSummary(); + init_utils(); + parsers9 = [ + new LineParser( + /^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/, + (result, [current, name, commit, label]) => { + result.push(branchStatus(current), true, name, commit, label); + } + ), + new LineParser( + new RegExp("^([*+]\\s)?(\\S+)\\s+([a-z0-9]+)\\s?(.*)$", "s"), + (result, [current, name, commit, label]) => { + result.push(branchStatus(current), false, name, commit, label); + } + ) + ]; + } +}); + +// src/lib/tasks/branch.ts +var branch_exports = {}; +__export(branch_exports, { + branchLocalTask: () => branchLocalTask, + branchTask: () => branchTask, + containsDeleteBranchCommand: () => containsDeleteBranchCommand, + deleteBranchTask: () => deleteBranchTask, + deleteBranchesTask: () => deleteBranchesTask +}); +function containsDeleteBranchCommand(commands) { + const deleteCommands = ["-d", "-D", "--delete"]; + return commands.some((command) => deleteCommands.includes(command)); +} +function branchTask(customArgs) { + const isDelete = containsDeleteBranchCommand(customArgs); + const commands = ["branch", ...customArgs]; + if (commands.length === 1) { + commands.push("-a"); + } + if (!commands.includes("-v")) { + commands.splice(1, 0, "-v"); + } + return { + format: "utf-8", + commands, + parser(stdOut, stdErr) { + if (isDelete) { + return parseBranchDeletions(stdOut, stdErr).all[0]; + } + return parseBranchSummary(stdOut); + } + }; +} +function branchLocalTask() { + const parser3 = parseBranchSummary; + return { + format: "utf-8", + commands: ["branch", "-v"], + parser: parser3 + }; +} +function deleteBranchesTask(branches, forceDelete = false) { + return { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", ...branches], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr); + }, + onError({ exitCode, stdOut }, error, done, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + done(stdOut); + } + }; +} +function deleteBranchTask(branch, forceDelete = false) { + const task = { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", branch], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr).branches[branch]; + }, + onError({ exitCode, stdErr, stdOut }, error, _, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + throw new GitResponseError( + task.parser(bufferToString(stdOut), bufferToString(stdErr)), + String(error) + ); + } + }; + return task; +} +var init_branch = __esm({ + "src/lib/tasks/branch.ts"() { + "use strict"; + init_git_response_error(); + init_parse_branch_delete(); + init_parse_branch(); + init_utils(); + } +}); + +// src/lib/responses/CheckIgnore.ts +var parseCheckIgnore; +var init_CheckIgnore = __esm({ + "src/lib/responses/CheckIgnore.ts"() { + "use strict"; + parseCheckIgnore = (text) => { + return text.split(/\n/g).map((line) => line.trim()).filter((file) => !!file); + }; + } +}); + +// src/lib/tasks/check-ignore.ts +var check_ignore_exports = {}; +__export(check_ignore_exports, { + checkIgnoreTask: () => checkIgnoreTask +}); +function checkIgnoreTask(paths) { + return { + commands: ["check-ignore", ...paths], + format: "utf-8", + parser: parseCheckIgnore + }; +} +var init_check_ignore = __esm({ + "src/lib/tasks/check-ignore.ts"() { + "use strict"; + init_CheckIgnore(); + } +}); + +// src/lib/tasks/clone.ts +var clone_exports = {}; +__export(clone_exports, { + cloneMirrorTask: () => cloneMirrorTask, + cloneTask: () => cloneTask +}); +function disallowedCommand(command) { + return /^--upload-pack(=|$)/.test(command); +} +function cloneTask(repo, directory, customArgs) { + const commands = ["clone", ...customArgs]; + filterString(repo) && commands.push(repo); + filterString(directory) && commands.push(directory); + const banned = commands.find(disallowedCommand); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return straightThroughStringTask(commands); +} +function cloneMirrorTask(repo, directory, customArgs) { + append(customArgs, "--mirror"); + return cloneTask(repo, directory, customArgs); +} +var init_clone = __esm({ + "src/lib/tasks/clone.ts"() { + "use strict"; + init_task(); + init_utils(); + } +}); + +// src/lib/parsers/parse-fetch.ts +function parseFetchResult(stdOut, stdErr) { + const result = { + raw: stdOut, + remote: null, + branches: [], + tags: [], + updated: [], + deleted: [] + }; + return parseStringResponse(result, parsers10, [stdOut, stdErr]); +} +var parsers10; +var init_parse_fetch = __esm({ + "src/lib/parsers/parse-fetch.ts"() { + "use strict"; + init_utils(); + parsers10 = [ + new LineParser(/From (.+)$/, (result, [remote]) => { + result.remote = remote; + }), + new LineParser(/\* \[new branch]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.branches.push({ + name, + tracking + }); + }), + new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.tags.push({ + name, + tracking + }); + }), + new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => { + result.deleted.push({ + tracking + }); + }), + new LineParser( + /\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/, + (result, [from, to, name, tracking]) => { + result.updated.push({ + name, + tracking, + to, + from + }); + } + ) + ]; + } +}); + +// src/lib/tasks/fetch.ts +var fetch_exports = {}; +__export(fetch_exports, { + fetchTask: () => fetchTask +}); +function disallowedCommand2(command) { + return /^--upload-pack(=|$)/.test(command); +} +function fetchTask(remote, branch, customArgs) { + const commands = ["fetch", ...customArgs]; + if (remote && branch) { + commands.push(remote, branch); + } + const banned = commands.find(disallowedCommand2); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return { + commands, + format: "utf-8", + parser: parseFetchResult + }; +} +var init_fetch = __esm({ + "src/lib/tasks/fetch.ts"() { + "use strict"; + init_parse_fetch(); + init_task(); + } +}); + +// src/lib/parsers/parse-move.ts +function parseMoveResult(stdOut) { + return parseStringResponse({ moves: [] }, parsers11, stdOut); +} +var parsers11; +var init_parse_move = __esm({ + "src/lib/parsers/parse-move.ts"() { + "use strict"; + init_utils(); + parsers11 = [ + new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => { + result.moves.push({ from, to }); + }) + ]; + } +}); + +// src/lib/tasks/move.ts +var move_exports = {}; +__export(move_exports, { + moveTask: () => moveTask +}); +function moveTask(from, to) { + return { + commands: ["mv", "-v", ...asArray(from), to], + format: "utf-8", + parser: parseMoveResult + }; +} +var init_move = __esm({ + "src/lib/tasks/move.ts"() { + "use strict"; + init_parse_move(); + init_utils(); + } +}); + +// src/lib/tasks/pull.ts +var pull_exports = {}; +__export(pull_exports, { + pullTask: () => pullTask +}); +function pullTask(remote, branch, customArgs) { + const commands = ["pull", ...customArgs]; + if (remote && branch) { + commands.splice(1, 0, remote, branch); + } + return { + commands, + format: "utf-8", + parser(stdOut, stdErr) { + return parsePullResult(stdOut, stdErr); + }, + onError(result, _error, _done, fail) { + const pullError = parsePullErrorResult( + bufferToString(result.stdOut), + bufferToString(result.stdErr) + ); + if (pullError) { + return fail(new GitResponseError(pullError)); + } + fail(_error); + } + }; +} +var init_pull = __esm({ + "src/lib/tasks/pull.ts"() { + "use strict"; + init_git_response_error(); + init_parse_pull(); + init_utils(); + } +}); + +// src/lib/responses/GetRemoteSummary.ts +function parseGetRemotes(text) { + const remotes = {}; + forEach(text, ([name]) => remotes[name] = { name }); + return Object.values(remotes); +} +function parseGetRemotesVerbose(text) { + const remotes = {}; + forEach(text, ([name, url, purpose]) => { + if (!remotes.hasOwnProperty(name)) { + remotes[name] = { + name, + refs: { fetch: "", push: "" } + }; + } + if (purpose && url) { + remotes[name].refs[purpose.replace(/[^a-z]/g, "")] = url; + } + }); + return Object.values(remotes); +} +function forEach(text, handler) { + forEachLineWithContent(text, (line) => handler(line.split(/\s+/))); +} +var init_GetRemoteSummary = __esm({ + "src/lib/responses/GetRemoteSummary.ts"() { + "use strict"; + init_utils(); + } +}); + +// src/lib/tasks/remote.ts +var remote_exports = {}; +__export(remote_exports, { + addRemoteTask: () => addRemoteTask, + getRemotesTask: () => getRemotesTask, + listRemotesTask: () => listRemotesTask, + remoteTask: () => remoteTask, + removeRemoteTask: () => removeRemoteTask +}); +function addRemoteTask(remoteName, remoteRepo, customArgs) { + return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]); +} +function getRemotesTask(verbose) { + const commands = ["remote"]; + if (verbose) { + commands.push("-v"); + } + return { + commands, + format: "utf-8", + parser: verbose ? parseGetRemotesVerbose : parseGetRemotes + }; +} +function listRemotesTask(customArgs) { + const commands = [...customArgs]; + if (commands[0] !== "ls-remote") { + commands.unshift("ls-remote"); + } + return straightThroughStringTask(commands); +} +function remoteTask(customArgs) { + const commands = [...customArgs]; + if (commands[0] !== "remote") { + commands.unshift("remote"); + } + return straightThroughStringTask(commands); +} +function removeRemoteTask(remoteName) { + return straightThroughStringTask(["remote", "remove", remoteName]); +} +var init_remote = __esm({ + "src/lib/tasks/remote.ts"() { + "use strict"; + init_GetRemoteSummary(); + init_task(); + } +}); + +// src/lib/tasks/stash-list.ts +var stash_list_exports = {}; +__export(stash_list_exports, { + stashListTask: () => stashListTask +}); +function stashListTask(opt = {}, customArgs) { + const options = parseLogOptions(opt); + const commands = ["stash", "list", ...options.commands, ...customArgs]; + const parser3 = createListLogSummaryParser( + options.splitter, + options.fields, + logFormatFromCommand(commands) + ); + return validateLogFormatConfig(commands) || { + commands, + format: "utf-8", + parser: parser3 + }; +} +var init_stash_list = __esm({ + "src/lib/tasks/stash-list.ts"() { + "use strict"; + init_log_format(); + init_parse_list_log_summary(); + init_diff(); + init_log(); + } +}); + +// src/lib/tasks/sub-module.ts +var sub_module_exports = {}; +__export(sub_module_exports, { + addSubModuleTask: () => addSubModuleTask, + initSubModuleTask: () => initSubModuleTask, + subModuleTask: () => subModuleTask, + updateSubModuleTask: () => updateSubModuleTask +}); +function addSubModuleTask(repo, path) { + return subModuleTask(["add", repo, path]); +} +function initSubModuleTask(customArgs) { + return subModuleTask(["init", ...customArgs]); +} +function subModuleTask(customArgs) { + const commands = [...customArgs]; + if (commands[0] !== "submodule") { + commands.unshift("submodule"); + } + return straightThroughStringTask(commands); +} +function updateSubModuleTask(customArgs) { + return subModuleTask(["update", ...customArgs]); +} +var init_sub_module = __esm({ + "src/lib/tasks/sub-module.ts"() { + "use strict"; + init_task(); + } +}); + +// src/lib/responses/TagList.ts +function singleSorted(a, b) { + const aIsNum = isNaN(a); + const bIsNum = isNaN(b); + if (aIsNum !== bIsNum) { + return aIsNum ? 1 : -1; + } + return aIsNum ? sorted(a, b) : 0; +} +function sorted(a, b) { + return a === b ? 0 : a > b ? 1 : -1; +} +function trimmed(input) { + return input.trim(); +} +function toNumber(input) { + if (typeof input === "string") { + return parseInt(input.replace(/^\D+/g, ""), 10) || 0; + } + return 0; +} +var TagList, parseTagList; +var init_TagList = __esm({ + "src/lib/responses/TagList.ts"() { + "use strict"; + TagList = class { + constructor(all, latest) { + this.all = all; + this.latest = latest; + } + }; + parseTagList = function(data, customSort = false) { + const tags = data.split("\n").map(trimmed).filter(Boolean); + if (!customSort) { + tags.sort(function(tagA, tagB) { + const partsA = tagA.split("."); + const partsB = tagB.split("."); + if (partsA.length === 1 || partsB.length === 1) { + return singleSorted(toNumber(partsA[0]), toNumber(partsB[0])); + } + for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) { + const diff = sorted(toNumber(partsA[i]), toNumber(partsB[i])); + if (diff) { + return diff; + } + } + return 0; + }); + } + const latest = customSort ? tags[0] : [...tags].reverse().find((tag) => tag.indexOf(".") >= 0); + return new TagList(tags, latest); + }; + } +}); + +// src/lib/tasks/tag.ts +var tag_exports = {}; +__export(tag_exports, { + addAnnotatedTagTask: () => addAnnotatedTagTask, + addTagTask: () => addTagTask, + tagListTask: () => tagListTask +}); +function tagListTask(customArgs = []) { + const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option)); + return { + format: "utf-8", + commands: ["tag", "-l", ...customArgs], + parser(text) { + return parseTagList(text, hasCustomSort); + } + }; +} +function addTagTask(name) { + return { + format: "utf-8", + commands: ["tag", name], + parser() { + return { name }; + } + }; +} +function addAnnotatedTagTask(name, tagMessage) { + return { + format: "utf-8", + commands: ["tag", "-a", "-m", tagMessage, name], + parser() { + return { name }; + } + }; +} +var init_tag = __esm({ + "src/lib/tasks/tag.ts"() { + "use strict"; + init_TagList(); + } +}); + +// src/git.js +var require_git = __commonJS({ + "src/git.js"(exports2, module2) { + "use strict"; + var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS(git_executor_exports)); + var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS(simple_git_api_exports)); + var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS(scheduler_exports)); + var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS(task_exports)); + var { + asArray: asArray2, + filterArray: filterArray2, + filterPrimitives: filterPrimitives2, + filterString: filterString2, + filterStringOrStringArray: filterStringOrStringArray2, + filterType: filterType2, + getTrailingOptions: getTrailingOptions2, + trailingFunctionArgument: trailingFunctionArgument2, + trailingOptionsArgument: trailingOptionsArgument2 + } = (init_utils(), __toCommonJS(utils_exports)); + var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS(apply_patch_exports)); + var { + branchTask: branchTask2, + branchLocalTask: branchLocalTask2, + deleteBranchesTask: deleteBranchesTask2, + deleteBranchTask: deleteBranchTask2 + } = (init_branch(), __toCommonJS(branch_exports)); + var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS(check_ignore_exports)); + var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS(check_is_repo_exports)); + var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS(clone_exports)); + var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS(clean_exports)); + var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS(diff_exports)); + var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS(fetch_exports)); + var { moveTask: moveTask2 } = (init_move(), __toCommonJS(move_exports)); + var { pullTask: pullTask2 } = (init_pull(), __toCommonJS(pull_exports)); + var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS(push_exports)); + var { + addRemoteTask: addRemoteTask2, + getRemotesTask: getRemotesTask2, + listRemotesTask: listRemotesTask2, + remoteTask: remoteTask2, + removeRemoteTask: removeRemoteTask2 + } = (init_remote(), __toCommonJS(remote_exports)); + var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS(reset_exports)); + var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS(stash_list_exports)); + var { + addSubModuleTask: addSubModuleTask2, + initSubModuleTask: initSubModuleTask2, + subModuleTask: subModuleTask2, + updateSubModuleTask: updateSubModuleTask2 + } = (init_sub_module(), __toCommonJS(sub_module_exports)); + var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS(tag_exports)); + var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS(task_exports)); + function Git2(options, plugins) { + this._plugins = plugins; + this._executor = new GitExecutor2( + options.baseDir, + new Scheduler2(options.maxConcurrentProcesses), + plugins + ); + this._trimmed = options.trimmed; + } + (Git2.prototype = Object.create(SimpleGitApi2.prototype)).constructor = Git2; + Git2.prototype.customBinary = function(command) { + this._plugins.reconfigure("binary", command); + return this; + }; + Git2.prototype.env = function(name, value) { + if (arguments.length === 1 && typeof name === "object") { + this._executor.env = name; + } else { + (this._executor.env = this._executor.env || {})[name] = value; + } + return this; + }; + Git2.prototype.stashList = function(options) { + return this._runTask( + stashListTask2( + trailingOptionsArgument2(arguments) || {}, + filterArray2(options) && options || [] + ), + trailingFunctionArgument2(arguments) + ); + }; + function createCloneTask(api, task, repoPath, localPath) { + if (typeof repoPath !== "string") { + return configurationErrorTask2(`git.${api}() requires a string 'repoPath'`); + } + return task(repoPath, filterType2(localPath, filterString2), getTrailingOptions2(arguments)); + } + Git2.prototype.clone = function() { + return this._runTask( + createCloneTask("clone", cloneTask2, ...arguments), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.mirror = function() { + return this._runTask( + createCloneTask("mirror", cloneMirrorTask2, ...arguments), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.mv = function(from, to) { + return this._runTask(moveTask2(from, to), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.checkoutLatestTag = function(then) { + var git = this; + return this.pull(function() { + git.tags(function(err, tags) { + git.checkout(tags.latest, then); + }); + }); + }; + Git2.prototype.pull = function(remote, branch, options, then) { + return this._runTask( + pullTask2( + filterType2(remote, filterString2), + filterType2(branch, filterString2), + getTrailingOptions2(arguments) + ), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.fetch = function(remote, branch) { + return this._runTask( + fetchTask2( + filterType2(remote, filterString2), + filterType2(branch, filterString2), + getTrailingOptions2(arguments) + ), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.silent = function(silence) { + console.warn( + "simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3" + ); + return this; + }; + Git2.prototype.tags = function(options, then) { + return this._runTask( + tagListTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.rebase = function() { + return this._runTask( + straightThroughStringTask2(["rebase", ...getTrailingOptions2(arguments)]), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.reset = function(mode) { + return this._runTask( + resetTask2(getResetMode2(mode), getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.revert = function(commit) { + const next = trailingFunctionArgument2(arguments); + if (typeof commit !== "string") { + return this._runTask(configurationErrorTask2("Commit must be a string"), next); + } + return this._runTask( + straightThroughStringTask2(["revert", ...getTrailingOptions2(arguments, 0, true), commit]), + next + ); + }; + Git2.prototype.addTag = function(name) { + const task = typeof name === "string" ? addTagTask2(name) : configurationErrorTask2("Git.addTag requires a tag name"); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) { + return this._runTask( + addAnnotatedTagTask2(tagName, tagMessage), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) { + return this._runTask( + deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.deleteLocalBranches = function(branchNames, forceDelete, then) { + return this._runTask( + deleteBranchesTask2(branchNames, typeof forceDelete === "boolean" ? forceDelete : false), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.branch = function(options, then) { + return this._runTask( + branchTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.branchLocal = function(then) { + return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.raw = function(commands) { + const createRestCommands = !Array.isArray(commands); + const command = [].slice.call(createRestCommands ? arguments : commands, 0); + for (let i = 0; i < command.length && createRestCommands; i++) { + if (!filterPrimitives2(command[i])) { + command.splice(i, command.length - i); + break; + } + } + command.push(...getTrailingOptions2(arguments, 0, true)); + var next = trailingFunctionArgument2(arguments); + if (!command.length) { + return this._runTask( + configurationErrorTask2("Raw: must supply one or more command to execute"), + next + ); + } + return this._runTask(straightThroughStringTask2(command, this._trimmed), next); + }; + Git2.prototype.submoduleAdd = function(repo, path, then) { + return this._runTask(addSubModuleTask2(repo, path), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.submoduleUpdate = function(args, then) { + return this._runTask( + updateSubModuleTask2(getTrailingOptions2(arguments, true)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.submoduleInit = function(args, then) { + return this._runTask( + initSubModuleTask2(getTrailingOptions2(arguments, true)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.subModule = function(options, then) { + return this._runTask( + subModuleTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.listRemote = function() { + return this._runTask( + listRemotesTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.addRemote = function(remoteName, remoteRepo, then) { + return this._runTask( + addRemoteTask2(remoteName, remoteRepo, getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.removeRemote = function(remoteName, then) { + return this._runTask(removeRemoteTask2(remoteName), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.getRemotes = function(verbose, then) { + return this._runTask(getRemotesTask2(verbose === true), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.remote = function(options, then) { + return this._runTask( + remoteTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.tag = function(options, then) { + const command = getTrailingOptions2(arguments); + if (command[0] !== "tag") { + command.unshift("tag"); + } + return this._runTask(straightThroughStringTask2(command), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.updateServerInfo = function(then) { + return this._runTask( + straightThroughStringTask2(["update-server-info"]), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.pushTags = function(remote, then) { + const task = pushTagsTask2( + { remote: filterType2(remote, filterString2) }, + getTrailingOptions2(arguments) + ); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rm = function(files) { + return this._runTask( + straightThroughStringTask2(["rm", "-f", ...asArray2(files)]), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.rmKeepLocal = function(files) { + return this._runTask( + straightThroughStringTask2(["rm", "--cached", ...asArray2(files)]), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.catFile = function(options, then) { + return this._catFile("utf-8", arguments); + }; + Git2.prototype.binaryCatFile = function() { + return this._catFile("buffer", arguments); + }; + Git2.prototype._catFile = function(format, args) { + var handler = trailingFunctionArgument2(args); + var command = ["cat-file"]; + var options = args[0]; + if (typeof options === "string") { + return this._runTask( + configurationErrorTask2("Git.catFile: options must be supplied as an array of strings"), + handler + ); + } + if (Array.isArray(options)) { + command.push.apply(command, options); + } + const task = format === "buffer" ? straightThroughBufferTask2(command) : straightThroughStringTask2(command); + return this._runTask(task, handler); + }; + Git2.prototype.diff = function(options, then) { + const task = filterString2(options) ? configurationErrorTask2( + "git.diff: supplying options as a single string is no longer supported, switch to an array of strings" + ) : straightThroughStringTask2(["diff", ...getTrailingOptions2(arguments)]); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.diffSummary = function() { + return this._runTask( + diffSummaryTask2(getTrailingOptions2(arguments, 1)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.applyPatch = function(patches) { + const task = !filterStringOrStringArray2(patches) ? configurationErrorTask2( + `git.applyPatch requires one or more string patches as the first argument` + ) : applyPatchTask2(asArray2(patches), getTrailingOptions2([].slice.call(arguments, 1))); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.revparse = function() { + const commands = ["rev-parse", ...getTrailingOptions2(arguments, true)]; + return this._runTask( + straightThroughStringTask2(commands, true), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.clean = function(mode, options, then) { + const usingCleanOptionsArray = isCleanOptionsArray2(mode); + const cleanMode = usingCleanOptionsArray && mode.join("") || filterType2(mode, filterString2) || ""; + const customArgs = getTrailingOptions2([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0)); + return this._runTask( + cleanWithOptionsTask2(cleanMode, customArgs), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.exec = function(then) { + const task = { + commands: [], + format: "utf-8", + parser() { + if (typeof then === "function") { + then(); + } + } + }; + return this._runTask(task); + }; + Git2.prototype.clearQueue = function() { + return this; + }; + Git2.prototype.checkIgnore = function(pathnames, then) { + return this._runTask( + checkIgnoreTask2(asArray2(filterType2(pathnames, filterStringOrStringArray2, []))), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.checkIsRepo = function(checkType, then) { + return this._runTask( + checkIsRepoTask2(filterType2(checkType, filterString2)), + trailingFunctionArgument2(arguments) + ); + }; + module2.exports = Git2; + } +}); + +// src/lib/git-factory.ts +var git_factory_exports = {}; +__export(git_factory_exports, { + esModuleFactory: () => esModuleFactory, + gitExportFactory: () => gitExportFactory, + gitInstanceFactory: () => gitInstanceFactory +}); +function esModuleFactory(defaultExport) { + return Object.defineProperties(defaultExport, { + __esModule: { value: true }, + default: { value: defaultExport } + }); +} +function gitExportFactory(factory) { + return Object.assign(factory.bind(null), api_exports); +} +function gitInstanceFactory(baseDir, options) { + var _a2; + const plugins = new PluginStore(); + const config = createInstanceConfig( + baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {}, + options + ); + if (!folderExists(config.baseDir)) { + throw new GitConstructError( + config, + `Cannot use simple-git on a directory that does not exist` + ); + } + if (Array.isArray(config.config)) { + plugins.add(commandConfigPrefixingPlugin(config.config)); + } + plugins.add(blockUnsafeOperationsPlugin(config.unsafe)); + plugins.add(suffixPathsPlugin()); + plugins.add(completionDetectionPlugin(config.completion)); + config.abort && plugins.add(abortPlugin(config.abort)); + config.progress && plugins.add(progressMonitorPlugin(config.progress)); + config.timeout && plugins.add(timeoutPlugin(config.timeout)); + config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions)); + plugins.add(errorDetectionPlugin(errorDetectionHandler(true))); + config.errors && plugins.add(errorDetectionPlugin(config.errors)); + customBinaryPlugin(plugins, config.binary, (_a2 = config.unsafe) == null ? void 0 : _a2.allowUnsafeCustomBinary); + return new Git(config, plugins); +} +var Git; +var init_git_factory = __esm({ + "src/lib/git-factory.ts"() { + "use strict"; + init_api(); + init_plugins(); + init_suffix_paths_plugin(); + init_utils(); + Git = require_git(); + } +}); + +// src/lib/runners/promise-wrapped.ts +var promise_wrapped_exports = {}; +__export(promise_wrapped_exports, { + gitP: () => gitP +}); +function gitP(...args) { + let git; + let chain = Promise.resolve(); + try { + git = gitInstanceFactory(...args); + } catch (e) { + chain = Promise.reject(e); + } + function builderReturn() { + return promiseApi; + } + function chainReturn() { + return chain; + } + const promiseApi = [...functionNamesBuilderApi, ...functionNamesPromiseApi].reduce( + (api, name) => { + const isAsync = functionNamesPromiseApi.includes(name); + const valid = isAsync ? asyncWrapper(name, git) : syncWrapper(name, git, api); + const alternative = isAsync ? chainReturn : builderReturn; + Object.defineProperty(api, name, { + enumerable: false, + configurable: false, + value: git ? valid : alternative + }); + return api; + }, + {} + ); + return promiseApi; + function asyncWrapper(fn, git2) { + return function(...args2) { + if (typeof args2[args2.length] === "function") { + throw new TypeError( + "Promise interface requires that handlers are not supplied inline, trailing function not allowed in call to " + fn + ); + } + return chain.then(function() { + return new Promise(function(resolve, reject) { + const callback = (err, result) => { + if (err) { + return reject(toError(err)); + } + resolve(result); + }; + args2.push(callback); + git2[fn].apply(git2, args2); + }); + }); + }; + } + function syncWrapper(fn, git2, api) { + return (...args2) => { + git2[fn](...args2); + return api; + }; + } +} +function toError(error) { + if (error instanceof Error) { + return error; + } + if (typeof error === "string") { + return new Error(error); + } + return new GitResponseError(error); +} +var functionNamesBuilderApi, functionNamesPromiseApi; +var init_promise_wrapped = __esm({ + "src/lib/runners/promise-wrapped.ts"() { + "use strict"; + init_git_response_error(); + init_git_factory(); + functionNamesBuilderApi = ["customBinary", "env", "outputHandler", "silent"]; + functionNamesPromiseApi = [ + "add", + "addAnnotatedTag", + "addConfig", + "addRemote", + "addTag", + "applyPatch", + "binaryCatFile", + "branch", + "branchLocal", + "catFile", + "checkIgnore", + "checkIsRepo", + "checkout", + "checkoutBranch", + "checkoutLatestTag", + "checkoutLocalBranch", + "clean", + "clone", + "commit", + "cwd", + "deleteLocalBranch", + "deleteLocalBranches", + "diff", + "diffSummary", + "exec", + "fetch", + "getRemotes", + "init", + "listConfig", + "listRemote", + "log", + "merge", + "mergeFromTo", + "mirror", + "mv", + "pull", + "push", + "pushTags", + "raw", + "rebase", + "remote", + "removeRemote", + "reset", + "revert", + "revparse", + "rm", + "rmKeepLocal", + "show", + "stash", + "stashList", + "status", + "subModule", + "submoduleAdd", + "submoduleInit", + "submoduleUpdate", + "tag", + "tags", + "updateServerInfo" + ]; + } +}); + +// src/index.js +var { gitP: gitP2 } = (init_promise_wrapped(), __toCommonJS(promise_wrapped_exports)); +var { esModuleFactory: esModuleFactory2, gitInstanceFactory: gitInstanceFactory2, gitExportFactory: gitExportFactory2 } = (init_git_factory(), __toCommonJS(git_factory_exports)); +var simpleGit = esModuleFactory2(gitExportFactory2(gitInstanceFactory2)); +module.exports = Object.assign(simpleGit, { gitP: gitP2, simpleGit }); +//# sourceMappingURL=index.js.map diff --git a/node_modules/simple-git/dist/cjs/index.js.map b/node_modules/simple-git/dist/cjs/index.js.map new file mode 100644 index 0000000..8336bc0 --- /dev/null +++ b/node_modules/simple-git/dist/cjs/index.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../src/lib/errors/git-error.ts", "../../src/lib/errors/git-response-error.ts", "../../src/lib/args/pathspec.ts", "../../src/lib/errors/git-construct-error.ts", "../../src/lib/errors/git-plugin-error.ts", "../../src/lib/errors/task-configuration-error.ts", "../../src/lib/utils/util.ts", "../../src/lib/utils/argument-filters.ts", "../../src/lib/utils/exit-codes.ts", "../../src/lib/utils/git-output-streams.ts", "../../src/lib/utils/line-parser.ts", "../../src/lib/utils/simple-git-options.ts", "../../src/lib/utils/task-options.ts", "../../src/lib/utils/task-parser.ts", "../../src/lib/utils/index.ts", "../../src/lib/tasks/check-is-repo.ts", "../../src/lib/responses/CleanSummary.ts", "../../src/lib/tasks/task.ts", "../../src/lib/tasks/clean.ts", "../../src/lib/responses/ConfigList.ts", "../../src/lib/tasks/config.ts", "../../src/lib/tasks/diff-name-status.ts", "../../src/lib/tasks/grep.ts", "../../src/lib/tasks/reset.ts", "../../src/lib/api.ts", "../../src/lib/plugins/abort-plugin.ts", "../../src/lib/plugins/block-unsafe-operations-plugin.ts", "../../src/lib/plugins/command-config-prefixing-plugin.ts", "../../src/lib/plugins/completion-detection.plugin.ts", "../../src/lib/plugins/custom-binary.plugin.ts", "../../src/lib/plugins/error-detection.plugin.ts", "../../src/lib/plugins/plugin-store.ts", "../../src/lib/plugins/progress-monitor-plugin.ts", "../../src/lib/plugins/simple-git-plugin.ts", "../../src/lib/plugins/spawn-options-plugin.ts", "../../src/lib/plugins/timout-plugin.ts", "../../src/lib/plugins/index.ts", "../../src/lib/plugins/suffix-paths.plugin.ts", "../../src/lib/git-logger.ts", "../../src/lib/runners/tasks-pending-queue.ts", "../../src/lib/runners/git-executor-chain.ts", "../../src/lib/runners/git-executor.ts", "../../src/lib/task-callback.ts", "../../src/lib/tasks/change-working-directory.ts", "../../src/lib/tasks/checkout.ts", "../../src/lib/parsers/parse-commit.ts", "../../src/lib/tasks/commit.ts", "../../src/lib/tasks/first-commit.ts", "../../src/lib/tasks/hash-object.ts", "../../src/lib/responses/InitSummary.ts", "../../src/lib/tasks/init.ts", "../../src/lib/args/log-format.ts", "../../src/lib/responses/DiffSummary.ts", "../../src/lib/parsers/parse-diff-summary.ts", "../../src/lib/parsers/parse-list-log-summary.ts", "../../src/lib/tasks/diff.ts", "../../src/lib/tasks/log.ts", "../../src/lib/responses/MergeSummary.ts", "../../src/lib/responses/PullSummary.ts", "../../src/lib/parsers/parse-remote-objects.ts", "../../src/lib/parsers/parse-remote-messages.ts", "../../src/lib/parsers/parse-pull.ts", "../../src/lib/parsers/parse-merge.ts", "../../src/lib/tasks/merge.ts", "../../src/lib/parsers/parse-push.ts", "../../src/lib/tasks/push.ts", "../../src/lib/tasks/show.ts", "../../src/lib/responses/FileStatusSummary.ts", "../../src/lib/responses/StatusSummary.ts", "../../src/lib/tasks/status.ts", "../../src/lib/tasks/version.ts", "../../src/lib/simple-git-api.ts", "../../src/lib/runners/scheduler.ts", "../../src/lib/tasks/apply-patch.ts", "../../src/lib/responses/BranchDeleteSummary.ts", "../../src/lib/parsers/parse-branch-delete.ts", "../../src/lib/responses/BranchSummary.ts", "../../src/lib/parsers/parse-branch.ts", "../../src/lib/tasks/branch.ts", "../../src/lib/responses/CheckIgnore.ts", "../../src/lib/tasks/check-ignore.ts", "../../src/lib/tasks/clone.ts", "../../src/lib/parsers/parse-fetch.ts", "../../src/lib/tasks/fetch.ts", "../../src/lib/parsers/parse-move.ts", "../../src/lib/tasks/move.ts", "../../src/lib/tasks/pull.ts", "../../src/lib/responses/GetRemoteSummary.ts", "../../src/lib/tasks/remote.ts", "../../src/lib/tasks/stash-list.ts", "../../src/lib/tasks/sub-module.ts", "../../src/lib/responses/TagList.ts", "../../src/lib/tasks/tag.ts", "../../src/git.js", "../../src/lib/git-factory.ts", "../../src/lib/runners/promise-wrapped.ts", "../../src/index.js"], + "sourcesContent": ["import type { SimpleGitTask } from '../types';\n\n/**\n * The `GitError` is thrown when the underlying `git` process throws a\n * fatal exception (eg an `ENOENT` exception when attempting to use a\n * non-writable directory as the root for your repo), and acts as the\n * base class for more specific errors thrown by the parsing of the\n * git response or errors in the configuration of the task about to\n * be run.\n *\n * When an exception is thrown, pending tasks in the same instance will\n * not be executed. The recommended way to run a series of tasks that\n * can independently fail without needing to prevent future tasks from\n * running is to catch them individually:\n *\n * ```typescript\n import { gitP, SimpleGit, GitError, PullResult } from 'simple-git';\n\n function catchTask (e: GitError) {\n return e.\n }\n\n const git = gitP(repoWorkingDir);\n const pulled: PullResult | GitError = await git.pull().catch(catchTask);\n const pushed: string | GitError = await git.pushTags().catch(catchTask);\n ```\n */\nexport class GitError extends Error {\n constructor(\n public task?: SimpleGitTask,\n message?: string\n ) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n", "import { GitError } from './git-error';\n\n/**\n * The `GitResponseError` is the wrapper for a parsed response that is treated as\n * a fatal error, for example attempting a `merge` can leave the repo in a corrupted\n * state when there are conflicts so the task will reject rather than resolve.\n *\n * For example, catching the merge conflict exception:\n *\n * ```typescript\n import { gitP, SimpleGit, GitResponseError, MergeSummary } from 'simple-git';\n\n const git = gitP(repoRoot);\n const mergeOptions: string[] = ['--no-ff', 'other-branch'];\n const mergeSummary: MergeSummary = await git.merge(mergeOptions)\n .catch((e: GitResponseError) => e.git);\n\n if (mergeSummary.failed) {\n // deal with the error\n }\n ```\n */\nexport class GitResponseError extends GitError {\n constructor(\n /**\n * `.git` access the parsed response that is treated as being an error\n */\n public readonly git: T,\n message?: string\n ) {\n super(undefined, message || String(git));\n }\n}\n", "const cache = new WeakMap();\n\nexport function pathspec(...paths: string[]) {\n const key = new String(paths);\n cache.set(key, paths);\n\n return key as string;\n}\n\nexport function isPathSpec(path: string | unknown): path is string {\n return path instanceof String && cache.has(path);\n}\n\nexport function toPaths(pathSpec: string): string[] {\n return cache.get(pathSpec) || [];\n}\n", "import { GitError } from './git-error';\nimport { SimpleGitOptions } from '../types';\n\n/**\n * The `GitConstructError` is thrown when an error occurs in the constructor\n * of the `simple-git` instance itself. Most commonly as a result of using\n * a `baseDir` option that points to a folder that either does not exist,\n * or cannot be read by the user the node script is running as.\n *\n * Check the `.message` property for more detail including the properties\n * passed to the constructor.\n */\nexport class GitConstructError extends GitError {\n constructor(\n public readonly config: SimpleGitOptions,\n message: string\n ) {\n super(undefined, message);\n }\n}\n", "import { SimpleGitOptions, SimpleGitTask } from '../types';\nimport { GitError } from './git-error';\n\nexport class GitPluginError extends GitError {\n constructor(\n public task?: SimpleGitTask,\n public readonly plugin?: keyof SimpleGitOptions,\n message?: string\n ) {\n super(task, message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n", "import { GitError } from './git-error';\n\n/**\n * The `TaskConfigurationError` is thrown when a command was incorrectly\n * configured. An error of this kind means that no attempt was made to\n * run your command through the underlying `git` binary.\n *\n * Check the `.message` property for more detail on why your configuration\n * resulted in an error.\n */\nexport class TaskConfigurationError extends GitError {\n constructor(message?: string) {\n super(undefined, message);\n }\n}\n", "import { exists, FOLDER } from '@kwsites/file-exists';\nimport { Maybe } from '../types';\n\nexport const NULL = '\\0';\n\nexport const NOOP: (...args: any[]) => void = () => {};\n\n/**\n * Returns either the source argument when it is a `Function`, or the default\n * `NOOP` function constant\n */\nexport function asFunction any>(source: T | any): T {\n return typeof source === 'function' ? source : NOOP;\n}\n\n/**\n * Determines whether the supplied argument is both a function, and is not\n * the `NOOP` function.\n */\nexport function isUserFunction(source: T | any): source is T {\n return typeof source === 'function' && source !== NOOP;\n}\n\nexport function splitOn(input: string, char: string): [string, string] {\n const index = input.indexOf(char);\n if (index <= 0) {\n return [input, ''];\n }\n\n return [input.substr(0, index), input.substr(index + 1)];\n}\n\nexport function first(input: T, offset?: number): Maybe;\nexport function first(input: T, offset?: number): Maybe;\nexport function first(input: any[] | IArguments, offset = 0): Maybe {\n return isArrayLike(input) && input.length > offset ? input[offset] : undefined;\n}\n\nexport function last(input: T, offset?: number): Maybe;\nexport function last(input: T, offset?: number): Maybe;\nexport function last(input: T, offset?: number): Maybe;\nexport function last(input: unknown, offset = 0) {\n if (isArrayLike(input) && input.length > offset) {\n return input[input.length - 1 - offset];\n }\n}\n\ntype ArrayLike = T[] | IArguments | { [index: number]: T; length: number };\n\nfunction isArrayLike(input: any): input is ArrayLike {\n return !!(input && typeof input.length === 'number');\n}\n\nexport function toLinesWithContent(input = '', trimmed = true, separator = '\\n'): string[] {\n return input.split(separator).reduce((output, line) => {\n const lineContent = trimmed ? line.trim() : line;\n if (lineContent) {\n output.push(lineContent);\n }\n return output;\n }, [] as string[]);\n}\n\ntype LineWithContentCallback = (line: string) => T;\n\nexport function forEachLineWithContent(\n input: string,\n callback: LineWithContentCallback\n): T[] {\n return toLinesWithContent(input, true).map((line) => callback(line));\n}\n\nexport function folderExists(path: string): boolean {\n return exists(path, FOLDER);\n}\n\n/**\n * Adds `item` into the `target` `Array` or `Set` when it is not already present and returns the `item`.\n */\nexport function append(target: T[] | Set, item: T): typeof item {\n if (Array.isArray(target)) {\n if (!target.includes(item)) {\n target.push(item);\n }\n } else {\n target.add(item);\n }\n return item;\n}\n\n/**\n * Adds `item` into the `target` `Array` when it is not already present and returns the `target`.\n */\nexport function including(target: T[], item: T): typeof target {\n if (Array.isArray(target) && !target.includes(item)) {\n target.push(item);\n }\n\n return target;\n}\n\nexport function remove(target: Set | T[], item: T): T {\n if (Array.isArray(target)) {\n const index = target.indexOf(item);\n if (index >= 0) {\n target.splice(index, 1);\n }\n } else {\n target.delete(item);\n }\n return item;\n}\n\nexport const objectToString = Object.prototype.toString.call.bind(Object.prototype.toString) as (\n input: any\n) => string;\n\nexport function asArray(source: T | T[]): T[] {\n return Array.isArray(source) ? source : [source];\n}\n\nexport function asStringArray(source: T | T[]): string[] {\n return asArray(source).map(String);\n}\n\nexport function asNumber(source: string | null | undefined, onNaN = 0) {\n if (source == null) {\n return onNaN;\n }\n\n const num = parseInt(source, 10);\n return isNaN(num) ? onNaN : num;\n}\n\nexport function prefixedArray(input: T[], prefix: T): T[] {\n const output: T[] = [];\n for (let i = 0, max = input.length; i < max; i++) {\n output.push(prefix, input[i]);\n }\n return output;\n}\n\nexport function bufferToString(input: Buffer | Buffer[]): string {\n return (Array.isArray(input) ? Buffer.concat(input) : input).toString('utf-8');\n}\n\n/**\n * Get a new object from a source object with only the listed properties.\n */\nexport function pick(source: Record, properties: string[]) {\n return Object.assign(\n {},\n ...properties.map((property) => (property in source ? { [property]: source[property] } : {}))\n );\n}\n\nexport function delay(duration = 0): Promise {\n return new Promise((done) => setTimeout(done, duration));\n}\n\nexport function orVoid(input: T | false) {\n if (input === false) {\n return undefined;\n }\n return input;\n}\n", "import { Maybe, Options, Primitives } from '../types';\nimport { objectToString } from './util';\nimport { isPathSpec } from '../args/pathspec';\n\nexport interface ArgumentFilterPredicate {\n (input: any): input is T;\n}\n\nexport function filterType(\n input: K,\n filter: ArgumentFilterPredicate\n): K extends T ? T : undefined;\nexport function filterType(input: K, filter: ArgumentFilterPredicate, def: T): T;\nexport function filterType(input: K, filter: ArgumentFilterPredicate, def?: T): Maybe {\n if (filter(input)) {\n return input;\n }\n return arguments.length > 2 ? def : undefined;\n}\n\nexport const filterArray: ArgumentFilterPredicate> = (input): input is Array => {\n return Array.isArray(input);\n};\n\nexport function filterPrimitives(\n input: unknown,\n omit?: Array<'boolean' | 'string' | 'number'>\n): input is Primitives {\n const type = isPathSpec(input) ? 'string' : typeof input;\n\n return (\n /number|string|boolean/.test(type) &&\n (!omit || !omit.includes(type as 'boolean' | 'string' | 'number'))\n );\n}\n\nexport const filterString: ArgumentFilterPredicate = (input): input is string => {\n return typeof input === 'string';\n};\n\nexport const filterStringArray: ArgumentFilterPredicate = (input): input is string[] => {\n return Array.isArray(input) && input.every(filterString);\n};\n\nexport const filterStringOrStringArray: ArgumentFilterPredicate = (\n input\n): input is string | string[] => {\n return filterString(input) || (Array.isArray(input) && input.every(filterString));\n};\n\nexport function filterPlainObject(input: T | unknown): input is T;\nexport function filterPlainObject(input: T | unknown): input is T {\n return !!input && objectToString(input) === '[object Object]';\n}\n\nexport function filterFunction(input: unknown): input is Function {\n return typeof input === 'function';\n}\n\nexport const filterHasLength: ArgumentFilterPredicate<{ length: number }> = (\n input\n): input is { length: number } => {\n if (input == null || 'number|boolean|function'.includes(typeof input)) {\n return false;\n }\n return Array.isArray(input) || typeof input === 'string' || typeof input.length === 'number';\n};\n", "/**\n * Known process exit codes used by the task parsers to determine whether an error\n * was one they can automatically handle\n */\nexport enum ExitCodes {\n SUCCESS,\n ERROR,\n NOT_FOUND = -2,\n UNCLEAN = 128,\n}\n", "import { TaskResponseFormat } from '../types';\n\nexport class GitOutputStreams {\n constructor(\n public readonly stdOut: T,\n public readonly stdErr: T\n ) {}\n\n asStrings(): GitOutputStreams {\n return new GitOutputStreams(this.stdOut.toString('utf8'), this.stdErr.toString('utf8'));\n }\n}\n", "export class LineParser {\n protected matches: string[] = [];\n\n private _regExp: RegExp[];\n\n constructor(\n regExp: RegExp | RegExp[],\n useMatches?: (target: T, match: string[]) => boolean | void\n ) {\n this._regExp = Array.isArray(regExp) ? regExp : [regExp];\n if (useMatches) {\n this.useMatches = useMatches;\n }\n }\n\n parse = (line: (offset: number) => string | undefined, target: T): boolean => {\n this.resetMatches();\n\n if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) {\n return false;\n }\n\n return this.useMatches(target, this.prepareMatches()) !== false;\n };\n\n // @ts-ignore\n protected useMatches(target: T, match: string[]): boolean | void {\n throw new Error(`LineParser:useMatches not implemented`);\n }\n\n protected resetMatches() {\n this.matches.length = 0;\n }\n\n protected prepareMatches() {\n return this.matches;\n }\n\n protected addMatch(reg: RegExp, index: number, line?: string) {\n const matched = line && reg.exec(line);\n if (matched) {\n this.pushMatch(index, matched);\n }\n\n return !!matched;\n }\n\n protected pushMatch(_index: number, matched: string[]) {\n this.matches.push(...matched.slice(1));\n }\n}\n\nexport class RemoteLineParser extends LineParser {\n protected addMatch(reg: RegExp, index: number, line?: string): boolean {\n return /^remote:\\s/.test(String(line)) && super.addMatch(reg, index, line);\n }\n\n protected pushMatch(index: number, matched: string[]) {\n if (index > 0 || matched.length > 1) {\n super.pushMatch(index, matched);\n }\n }\n}\n", "import { SimpleGitOptions } from '../types';\n\nconst defaultOptions: Omit = {\n binary: 'git',\n maxConcurrentProcesses: 5,\n config: [],\n trimmed: false,\n};\n\nexport function createInstanceConfig(\n ...options: Array | undefined>\n): SimpleGitOptions {\n const baseDir = process.cwd();\n const config: SimpleGitOptions = Object.assign(\n { baseDir, ...defaultOptions },\n ...options.filter((o) => typeof o === 'object' && o)\n );\n\n config.baseDir = config.baseDir || baseDir;\n config.trimmed = config.trimmed === true;\n\n return config;\n}\n", "import {\n filterArray,\n filterFunction,\n filterPlainObject,\n filterPrimitives,\n filterType,\n} from './argument-filters';\nimport { asFunction, isUserFunction, last } from './util';\nimport { Maybe, Options, OptionsValues } from '../types';\nimport { isPathSpec } from '../args/pathspec';\n\nexport function appendTaskOptions(\n options: Maybe,\n commands: string[] = []\n): string[] {\n if (!filterPlainObject(options)) {\n return commands;\n }\n\n return Object.keys(options).reduce((commands: string[], key: string) => {\n const value: OptionsValues = options[key];\n\n if (isPathSpec(value)) {\n commands.push(value);\n } else if (filterPrimitives(value, ['boolean'])) {\n commands.push(key + '=' + value);\n } else {\n commands.push(key);\n }\n\n return commands;\n }, commands);\n}\n\nexport function getTrailingOptions(\n args: IArguments,\n initialPrimitive = 0,\n objectOnly = false\n): string[] {\n const command: string[] = [];\n\n for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) {\n if ('string|number'.includes(typeof args[i])) {\n command.push(String(args[i]));\n }\n }\n\n appendTaskOptions(trailingOptionsArgument(args), command);\n if (!objectOnly) {\n command.push(...trailingArrayArgument(args));\n }\n\n return command;\n}\n\nfunction trailingArrayArgument(args: IArguments) {\n const hasTrailingCallback = typeof last(args) === 'function';\n return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []);\n}\n\n/**\n * Given any number of arguments, returns the trailing options argument, ignoring a trailing function argument\n * if there is one. When not found, the return value is null.\n */\nexport function trailingOptionsArgument(args: IArguments): Maybe {\n const hasTrailingCallback = filterFunction(last(args));\n return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject);\n}\n\n/**\n * Returns either the source argument when it is a `Function`, or the default\n * `NOOP` function constant\n */\nexport function trailingFunctionArgument(\n args: unknown[] | IArguments | unknown,\n includeNoop = true\n): Maybe<(...args: any[]) => unknown> {\n const callback = asFunction(last(args));\n return includeNoop || isUserFunction(callback) ? callback : undefined;\n}\n", "import type { MaybeArray, TaskParser, TaskResponseFormat } from '../types';\nimport { GitOutputStreams } from './git-output-streams';\nimport { LineParser } from './line-parser';\nimport { asArray, toLinesWithContent } from './util';\n\nexport function callTaskParser(\n parser: TaskParser,\n streams: GitOutputStreams\n) {\n return parser(streams.stdOut, streams.stdErr);\n}\n\nexport function parseStringResponse(\n result: T,\n parsers: LineParser[],\n texts: MaybeArray,\n trim = true\n): T {\n asArray(texts).forEach((text) => {\n for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) {\n const line = (offset = 0) => {\n if (i + offset >= max) {\n return;\n }\n return lines[i + offset];\n };\n\n parsers.some(({ parse }) => parse(line, result));\n }\n });\n\n return result;\n}\n", "export * from './argument-filters';\nexport * from './exit-codes';\nexport * from './git-output-streams';\nexport * from './line-parser';\nexport * from './simple-git-options';\nexport * from './task-options';\nexport * from './task-parser';\nexport * from './util';\n", "import { ExitCodes } from '../utils';\nimport { Maybe, StringTask } from '../types';\n\nexport enum CheckRepoActions {\n BARE = 'bare',\n IN_TREE = 'tree',\n IS_REPO_ROOT = 'root',\n}\n\nconst onError: StringTask['onError'] = ({ exitCode }, error, done, fail) => {\n if (exitCode === ExitCodes.UNCLEAN && isNotRepoMessage(error)) {\n return done(Buffer.from('false'));\n }\n\n fail(error);\n};\n\nconst parser: StringTask['parser'] = (text) => {\n return text.trim() === 'true';\n};\n\nexport function checkIsRepoTask(action: Maybe): StringTask {\n switch (action) {\n case CheckRepoActions.BARE:\n return checkIsBareRepoTask();\n case CheckRepoActions.IS_REPO_ROOT:\n return checkIsRepoRootTask();\n }\n\n const commands = ['rev-parse', '--is-inside-work-tree'];\n\n return {\n commands,\n format: 'utf-8',\n onError,\n parser,\n };\n}\n\nexport function checkIsRepoRootTask(): StringTask {\n const commands = ['rev-parse', '--git-dir'];\n\n return {\n commands,\n format: 'utf-8',\n onError,\n parser(path) {\n return /^\\.(git)?$/.test(path.trim());\n },\n };\n}\n\nexport function checkIsBareRepoTask(): StringTask {\n const commands = ['rev-parse', '--is-bare-repository'];\n\n return {\n commands,\n format: 'utf-8',\n onError,\n parser,\n };\n}\n\nfunction isNotRepoMessage(error: Error): boolean {\n return /(Not a git repository|Kein Git-Repository)/i.test(String(error));\n}\n", "import { CleanSummary } from '../../../typings';\nimport { toLinesWithContent } from '../utils';\n\nexport class CleanResponse implements CleanSummary {\n public paths: string[] = [];\n public files: string[] = [];\n public folders: string[] = [];\n\n constructor(public readonly dryRun: boolean) {}\n}\n\nconst removalRegexp = /^[a-z]+\\s*/i;\nconst dryRunRemovalRegexp = /^[a-z]+\\s+[a-z]+\\s*/i;\nconst isFolderRegexp = /\\/$/;\n\nexport function cleanSummaryParser(dryRun: boolean, text: string): CleanSummary {\n const summary = new CleanResponse(dryRun);\n const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp;\n\n toLinesWithContent(text).forEach((line) => {\n const removed = line.replace(regexp, '');\n\n summary.paths.push(removed);\n (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed);\n });\n\n return summary;\n}\n", "import { TaskConfigurationError } from '../errors/task-configuration-error';\nimport type { BufferTask, EmptyTaskParser, SimpleGitTask, StringTask } from '../types';\n\nexport const EMPTY_COMMANDS: [] = [];\n\nexport type EmptyTask = {\n commands: typeof EMPTY_COMMANDS;\n format: 'empty';\n parser: EmptyTaskParser;\n onError?: undefined;\n};\n\nexport function adhocExecTask(parser: EmptyTaskParser): EmptyTask {\n return {\n commands: EMPTY_COMMANDS,\n format: 'empty',\n parser,\n };\n}\n\nexport function configurationErrorTask(error: Error | string): EmptyTask {\n return {\n commands: EMPTY_COMMANDS,\n format: 'empty',\n parser() {\n throw typeof error === 'string' ? new TaskConfigurationError(error) : error;\n },\n };\n}\n\nexport function straightThroughStringTask(commands: string[], trimmed = false): StringTask {\n return {\n commands,\n format: 'utf-8',\n parser(text) {\n return trimmed ? String(text).trim() : text;\n },\n };\n}\n\nexport function straightThroughBufferTask(commands: string[]): BufferTask {\n return {\n commands,\n format: 'buffer',\n parser(buffer) {\n return buffer;\n },\n };\n}\n\nexport function isBufferTask(task: SimpleGitTask): task is BufferTask {\n return task.format === 'buffer';\n}\n\nexport function isEmptyTask(task: SimpleGitTask): task is EmptyTask {\n return task.format === 'empty' || !task.commands.length;\n}\n", "import { CleanSummary } from '../../../typings';\nimport { cleanSummaryParser } from '../responses/CleanSummary';\nimport { Maybe, StringTask } from '../types';\nimport { asStringArray } from '../utils';\nimport { configurationErrorTask } from './task';\n\nexport const CONFIG_ERROR_INTERACTIVE_MODE = 'Git clean interactive mode is not supported';\nexport const CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter (\"n\" or \"f\") is required';\nexport const CONFIG_ERROR_UNKNOWN_OPTION = 'Git clean unknown option found in: ';\n\n/**\n * All supported option switches available for use in a `git.clean` operation\n */\nexport enum CleanOptions {\n DRY_RUN = 'n',\n FORCE = 'f',\n IGNORED_INCLUDED = 'x',\n IGNORED_ONLY = 'X',\n EXCLUDING = 'e',\n QUIET = 'q',\n RECURSIVE = 'd',\n}\n\n/**\n * The two modes `git.clean` can run in - one of these must be supplied in order\n * for the command to not throw a `TaskConfigurationError`\n */\nexport type CleanMode = CleanOptions.FORCE | CleanOptions.DRY_RUN;\n\nconst CleanOptionValues: Set = new Set([\n 'i',\n ...asStringArray(Object.values(CleanOptions as any)),\n]);\n\nexport function cleanWithOptionsTask(mode: CleanMode | string, customArgs: string[]) {\n const { cleanMode, options, valid } = getCleanOptions(mode);\n\n if (!cleanMode) {\n return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED);\n }\n\n if (!valid.options) {\n return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode));\n }\n\n options.push(...customArgs);\n\n if (options.some(isInteractiveMode)) {\n return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE);\n }\n\n return cleanTask(cleanMode, options);\n}\n\nexport function cleanTask(mode: CleanMode, customArgs: string[]): StringTask {\n const commands: string[] = ['clean', `-${mode}`, ...customArgs];\n\n return {\n commands,\n format: 'utf-8',\n parser(text: string): CleanSummary {\n return cleanSummaryParser(mode === CleanOptions.DRY_RUN, text);\n },\n };\n}\n\nexport function isCleanOptionsArray(input: string[]): input is CleanOptions[] {\n return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test));\n}\n\nfunction getCleanOptions(input: string) {\n let cleanMode: Maybe;\n let options: string[] = [];\n let valid = { cleanMode: false, options: true };\n\n input\n .replace(/[^a-z]i/g, '')\n .split('')\n .forEach((char) => {\n if (isCleanMode(char)) {\n cleanMode = char;\n valid.cleanMode = true;\n } else {\n valid.options = valid.options && isKnownOption((options[options.length] = `-${char}`));\n }\n });\n\n return {\n cleanMode,\n options,\n valid,\n };\n}\n\nfunction isCleanMode(cleanMode?: string): cleanMode is CleanMode {\n return cleanMode === CleanOptions.FORCE || cleanMode === CleanOptions.DRY_RUN;\n}\n\nfunction isKnownOption(option: string): boolean {\n return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1));\n}\n\nfunction isInteractiveMode(option: string): boolean {\n if (/^-[^\\-]/.test(option)) {\n return option.indexOf('i') > 0;\n }\n\n return option === '--interactive';\n}\n", "import { ConfigGetResult, ConfigListSummary, ConfigValues } from '../../../typings';\nimport { last, splitOn } from '../utils';\n\nexport class ConfigList implements ConfigListSummary {\n public files: string[] = [];\n public values: { [fileName: string]: ConfigValues } = Object.create(null);\n\n private _all: ConfigValues | undefined;\n\n public get all(): ConfigValues {\n if (!this._all) {\n this._all = this.files.reduce((all: ConfigValues, file: string) => {\n return Object.assign(all, this.values[file]);\n }, {});\n }\n\n return this._all;\n }\n\n public addFile(file: string): ConfigValues {\n if (!(file in this.values)) {\n const latest = last(this.files);\n this.values[file] = latest ? Object.create(this.values[latest]) : {};\n\n this.files.push(file);\n }\n\n return this.values[file];\n }\n\n public addValue(file: string, key: string, value: string) {\n const values = this.addFile(file);\n\n if (!values.hasOwnProperty(key)) {\n values[key] = value;\n } else if (Array.isArray(values[key])) {\n (values[key] as string[]).push(value);\n } else {\n values[key] = [values[key] as string, value];\n }\n\n this._all = undefined;\n }\n}\n\nexport function configListParser(text: string): ConfigList {\n const config = new ConfigList();\n\n for (const item of configParser(text)) {\n config.addValue(item.file, String(item.key), item.value);\n }\n\n return config;\n}\n\nexport function configGetParser(text: string, key: string): ConfigGetResult {\n let value: string | null = null;\n const values: string[] = [];\n const scopes: Map = new Map();\n\n for (const item of configParser(text, key)) {\n if (item.key !== key) {\n continue;\n }\n\n values.push((value = item.value));\n\n if (!scopes.has(item.file)) {\n scopes.set(item.file, []);\n }\n\n scopes.get(item.file)!.push(value);\n }\n\n return {\n key,\n paths: Array.from(scopes.keys()),\n scopes,\n value,\n values,\n };\n}\n\nfunction configFilePath(filePath: string): string {\n return filePath.replace(/^(file):/, '');\n}\n\nfunction* configParser(text: string, requestedKey: string | null = null) {\n const lines = text.split('\\0');\n\n for (let i = 0, max = lines.length - 1; i < max; ) {\n const file = configFilePath(lines[i++]);\n\n let value = lines[i++];\n let key = requestedKey;\n\n if (value.includes('\\n')) {\n const line = splitOn(value, '\\n');\n key = line[0];\n value = line[1];\n }\n\n yield { file, key, value };\n }\n}\n", "import type { ConfigGetResult, ConfigListSummary, SimpleGit } from '../../../typings';\nimport { configGetParser, configListParser } from '../responses/ConfigList';\nimport type { SimpleGitApi } from '../simple-git-api';\nimport type { StringTask } from '../types';\nimport { trailingFunctionArgument } from '../utils';\n\nexport enum GitConfigScope {\n system = 'system',\n global = 'global',\n local = 'local',\n worktree = 'worktree',\n}\n\nfunction asConfigScope(\n scope: GitConfigScope | unknown,\n fallback: T\n): GitConfigScope | T {\n if (typeof scope === 'string' && GitConfigScope.hasOwnProperty(scope)) {\n return scope as GitConfigScope;\n }\n return fallback;\n}\n\nfunction addConfigTask(\n key: string,\n value: string,\n append: boolean,\n scope: GitConfigScope\n): StringTask {\n const commands: string[] = ['config', `--${scope}`];\n\n if (append) {\n commands.push('--add');\n }\n\n commands.push(key, value);\n\n return {\n commands,\n format: 'utf-8',\n parser(text: string): string {\n return text;\n },\n };\n}\n\nfunction getConfigTask(key: string, scope?: GitConfigScope): StringTask {\n const commands: string[] = ['config', '--null', '--show-origin', '--get-all', key];\n\n if (scope) {\n commands.splice(1, 0, `--${scope}`);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser(text) {\n return configGetParser(text, key);\n },\n };\n}\n\nfunction listConfigTask(scope?: GitConfigScope): StringTask {\n const commands = ['config', '--list', '--show-origin', '--null'];\n\n if (scope) {\n commands.push(`--${scope}`);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser(text: string) {\n return configListParser(text);\n },\n };\n}\n\nexport default function (): Pick {\n return {\n addConfig(this: SimpleGitApi, key: string, value: string, ...rest: unknown[]) {\n return this._runTask(\n addConfigTask(\n key,\n value,\n rest[0] === true,\n asConfigScope(rest[1], GitConfigScope.local)\n ),\n trailingFunctionArgument(arguments)\n );\n },\n\n getConfig(this: SimpleGitApi, key: string, scope?: GitConfigScope) {\n return this._runTask(\n getConfigTask(key, asConfigScope(scope, undefined)),\n trailingFunctionArgument(arguments)\n );\n },\n\n listConfig(this: SimpleGitApi, ...rest: unknown[]) {\n return this._runTask(\n listConfigTask(asConfigScope(rest[0], undefined)),\n trailingFunctionArgument(arguments)\n );\n },\n };\n}\n", "export enum DiffNameStatus {\n ADDED = 'A',\n COPIED = 'C',\n DELETED = 'D',\n MODIFIED = 'M',\n RENAMED = 'R',\n CHANGED = 'T',\n UNMERGED = 'U',\n UNKNOWN = 'X',\n BROKEN = 'B',\n}\n\nconst diffNameStatus = new Set(Object.values(DiffNameStatus));\n\nexport function isDiffNameStatus(input: string): input is DiffNameStatus {\n return diffNameStatus.has(input as DiffNameStatus);\n}\n", "import { GrepResult, SimpleGit } from '../../../typings';\nimport { SimpleGitApi } from '../simple-git-api';\nimport {\n asNumber,\n forEachLineWithContent,\n getTrailingOptions,\n NULL,\n prefixedArray,\n trailingFunctionArgument,\n} from '../utils';\n\nimport { configurationErrorTask } from './task';\n\nconst disallowedOptions = ['-h'];\n\nconst Query = Symbol('grepQuery');\n\nexport interface GitGrepQuery extends Iterable {\n /** Adds one or more terms to be grouped as an \"and\" to any other terms */\n and(...and: string[]): this;\n\n /** Adds one or more search terms - git.grep will \"or\" this to other terms */\n param(...param: string[]): this;\n}\n\nclass GrepQuery implements GitGrepQuery {\n private [Query]: string[] = [];\n\n *[Symbol.iterator]() {\n for (const query of this[Query]) {\n yield query;\n }\n }\n\n and(...and: string[]) {\n and.length && this[Query].push('--and', '(', ...prefixedArray(and, '-e'), ')');\n return this;\n }\n\n param(...param: string[]) {\n this[Query].push(...prefixedArray(param, '-e'));\n return this;\n }\n}\n\n/**\n * Creates a new builder for a `git.grep` query with optional params\n */\nexport function grepQueryBuilder(...params: string[]): GitGrepQuery {\n return new GrepQuery().param(...params);\n}\n\nfunction parseGrep(grep: string): GrepResult {\n const paths: GrepResult['paths'] = new Set();\n const results: GrepResult['results'] = {};\n\n forEachLineWithContent(grep, (input) => {\n const [path, line, preview] = input.split(NULL);\n paths.add(path);\n (results[path] = results[path] || []).push({\n line: asNumber(line),\n path,\n preview,\n });\n });\n\n return {\n paths,\n results,\n };\n}\n\nexport default function (): Pick {\n return {\n grep(this: SimpleGitApi, searchTerm: string | GitGrepQuery) {\n const then = trailingFunctionArgument(arguments);\n const options = getTrailingOptions(arguments);\n\n for (const option of disallowedOptions) {\n if (options.includes(option)) {\n return this._runTask(\n configurationErrorTask(`git.grep: use of \"${option}\" is not supported.`),\n then\n );\n }\n }\n\n if (typeof searchTerm === 'string') {\n searchTerm = grepQueryBuilder().param(searchTerm);\n }\n\n const commands = ['grep', '--null', '-n', '--full-name', ...options, ...searchTerm];\n\n return this._runTask(\n {\n commands,\n format: 'utf-8',\n parser(stdOut) {\n return parseGrep(stdOut);\n },\n },\n then\n );\n },\n };\n}\n", "import { straightThroughStringTask } from './task';\nimport { Maybe, OptionFlags, Options } from '../types';\n\nexport enum ResetMode {\n MIXED = 'mixed',\n SOFT = 'soft',\n HARD = 'hard',\n MERGE = 'merge',\n KEEP = 'keep',\n}\n\nconst ResetModes = Array.from(Object.values(ResetMode));\n\nexport type ResetOptions = Options &\n OptionFlags<'-q' | '--quiet' | '--no-quiet' | '--pathspec-from-nul'> &\n OptionFlags<'--pathspec-from-file', string>;\n\nexport function resetTask(mode: Maybe, customArgs: string[]) {\n const commands: string[] = ['reset'];\n if (isValidResetMode(mode)) {\n commands.push(`--${mode}`);\n }\n commands.push(...customArgs);\n\n return straightThroughStringTask(commands);\n}\n\nexport function getResetMode(mode: ResetMode | any): Maybe {\n if (isValidResetMode(mode)) {\n return mode;\n }\n\n switch (typeof mode) {\n case 'string':\n case 'undefined':\n return ResetMode.SOFT;\n }\n\n return;\n}\n\nfunction isValidResetMode(mode: ResetMode | any): mode is ResetMode {\n return ResetModes.includes(mode);\n}\n", "import { pathspec } from './args/pathspec';\nimport { GitConstructError } from './errors/git-construct-error';\nimport { GitError } from './errors/git-error';\nimport { GitPluginError } from './errors/git-plugin-error';\nimport { GitResponseError } from './errors/git-response-error';\nimport { TaskConfigurationError } from './errors/task-configuration-error';\nimport { CheckRepoActions } from './tasks/check-is-repo';\nimport { CleanOptions } from './tasks/clean';\nimport { GitConfigScope } from './tasks/config';\nimport { DiffNameStatus } from './tasks/diff-name-status';\nimport { grepQueryBuilder } from './tasks/grep';\nimport { ResetMode } from './tasks/reset';\n\nexport {\n CheckRepoActions,\n CleanOptions,\n DiffNameStatus,\n GitConfigScope,\n GitConstructError,\n GitError,\n GitPluginError,\n GitResponseError,\n ResetMode,\n TaskConfigurationError,\n grepQueryBuilder,\n pathspec,\n};\n", "import { SimpleGitOptions } from '../types';\nimport { SimpleGitPlugin } from './simple-git-plugin';\nimport { GitPluginError } from '../errors/git-plugin-error';\n\nexport function abortPlugin(signal: SimpleGitOptions['abort']) {\n if (!signal) {\n return;\n }\n\n const onSpawnAfter: SimpleGitPlugin<'spawn.after'> = {\n type: 'spawn.after',\n action(_data, context) {\n function kill() {\n context.kill(new GitPluginError(undefined, 'abort', 'Abort signal received'));\n }\n\n signal.addEventListener('abort', kill);\n\n context.spawned.on('close', () => signal.removeEventListener('abort', kill));\n },\n };\n\n const onSpawnBefore: SimpleGitPlugin<'spawn.before'> = {\n type: 'spawn.before',\n action(_data, context) {\n if (signal.aborted) {\n context.kill(new GitPluginError(undefined, 'abort', 'Abort already signaled'));\n }\n },\n };\n\n return [onSpawnBefore, onSpawnAfter];\n}\n", "import type { SimpleGitPlugin } from './simple-git-plugin';\n\nimport { GitPluginError } from '../errors/git-plugin-error';\nimport type { SimpleGitPluginConfig } from '../types';\n\nfunction isConfigSwitch(arg: string | unknown) {\n return typeof arg === 'string' && arg.trim().toLowerCase() === '-c';\n}\n\nfunction preventProtocolOverride(arg: string, next: string) {\n if (!isConfigSwitch(arg)) {\n return;\n }\n\n if (!/^\\s*protocol(.[a-z]+)?.allow/.test(next)) {\n return;\n }\n\n throw new GitPluginError(\n undefined,\n 'unsafe',\n 'Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol'\n );\n}\n\nfunction preventUploadPack(arg: string, method: string) {\n if (/^\\s*--(upload|receive)-pack/.test(arg)) {\n throw new GitPluginError(\n undefined,\n 'unsafe',\n `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`\n );\n }\n\n if (method === 'clone' && /^\\s*-u\\b/.test(arg)) {\n throw new GitPluginError(\n undefined,\n 'unsafe',\n `Use of clone with option -u is not permitted without enabling allowUnsafePack`\n );\n }\n\n if (method === 'push' && /^\\s*--exec\\b/.test(arg)) {\n throw new GitPluginError(\n undefined,\n 'unsafe',\n `Use of push with option --exec is not permitted without enabling allowUnsafePack`\n );\n }\n}\n\nexport function blockUnsafeOperationsPlugin({\n allowUnsafeProtocolOverride = false,\n allowUnsafePack = false,\n}: SimpleGitPluginConfig['unsafe'] = {}): SimpleGitPlugin<'spawn.args'> {\n return {\n type: 'spawn.args',\n action(args, context) {\n args.forEach((current, index) => {\n const next = index < args.length ? args[index + 1] : '';\n\n allowUnsafeProtocolOverride || preventProtocolOverride(current, next);\n allowUnsafePack || preventUploadPack(current, context.method);\n });\n\n return args;\n },\n };\n}\n", "import { prefixedArray } from '../utils';\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\nexport function commandConfigPrefixingPlugin(\n configuration: string[]\n): SimpleGitPlugin<'spawn.args'> {\n const prefix = prefixedArray(configuration, '-c');\n\n return {\n type: 'spawn.args',\n action(data) {\n return [...prefix, ...data];\n },\n };\n}\n", "import { deferred, DeferredPromise } from '@kwsites/promise-deferred';\nimport { SimpleGitPluginConfig } from '../types';\nimport { delay } from '../utils';\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\nconst never = deferred().promise;\n\nexport function completionDetectionPlugin({\n onClose = true,\n onExit = 50,\n}: SimpleGitPluginConfig['completion'] = {}): SimpleGitPlugin<'spawn.after'> {\n function createEvents() {\n let exitCode = -1;\n const events = {\n close: deferred(),\n closeTimeout: deferred(),\n exit: deferred(),\n exitTimeout: deferred(),\n };\n\n const result = Promise.race([\n onClose === false ? never : events.closeTimeout.promise,\n onExit === false ? never : events.exitTimeout.promise,\n ]);\n\n configureTimeout(onClose, events.close, events.closeTimeout);\n configureTimeout(onExit, events.exit, events.exitTimeout);\n\n return {\n close(code: number) {\n exitCode = code;\n events.close.done();\n },\n exit(code: number) {\n exitCode = code;\n events.exit.done();\n },\n get exitCode() {\n return exitCode;\n },\n result,\n };\n }\n\n function configureTimeout(\n flag: boolean | number,\n event: DeferredPromise,\n timeout: DeferredPromise\n ) {\n if (flag === false) {\n return;\n }\n\n (flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done);\n }\n\n return {\n type: 'spawn.after',\n async action(_data, { spawned, close }) {\n const events = createEvents();\n\n let deferClose = true;\n let quickClose = () => void (deferClose = false);\n\n spawned.stdout?.on('data', quickClose);\n spawned.stderr?.on('data', quickClose);\n spawned.on('error', quickClose);\n\n spawned.on('close', (code: number) => events.close(code));\n spawned.on('exit', (code: number) => events.exit(code));\n\n try {\n await events.result;\n if (deferClose) {\n await delay(50);\n }\n close(events.exitCode);\n } catch (err) {\n close(events.exitCode, err as Error);\n }\n },\n };\n}\n", "import type { SimpleGitOptions } from '../types';\n\nimport { GitPluginError } from '../errors/git-plugin-error';\nimport { asArray } from '../utils';\nimport { PluginStore } from './plugin-store';\n\nconst WRONG_NUMBER_ERR = `Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`;\nconst WRONG_CHARS_ERR = `Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`;\n\nfunction isBadArgument(arg: string) {\n return !arg || !/^([a-z]:)?([a-z0-9/.\\\\_-]+)$/i.test(arg);\n}\n\nfunction toBinaryConfig(\n input: string[],\n allowUnsafe: boolean\n): { binary: string; prefix?: string } {\n if (input.length < 1 || input.length > 2) {\n throw new GitPluginError(undefined, 'binary', WRONG_NUMBER_ERR);\n }\n\n const isBad = input.some(isBadArgument);\n if (isBad) {\n if (allowUnsafe) {\n console.warn(WRONG_CHARS_ERR);\n } else {\n throw new GitPluginError(undefined, 'binary', WRONG_CHARS_ERR);\n }\n }\n\n const [binary, prefix] = input;\n return {\n binary,\n prefix,\n };\n}\n\nexport function customBinaryPlugin(\n plugins: PluginStore,\n input: SimpleGitOptions['binary'] = ['git'],\n allowUnsafe = false\n) {\n let config = toBinaryConfig(asArray(input), allowUnsafe);\n\n plugins.on('binary', (input) => {\n config = toBinaryConfig(asArray(input), allowUnsafe);\n });\n\n plugins.append('spawn.binary', () => {\n return config.binary;\n });\n\n plugins.append('spawn.args', (data) => {\n return config.prefix ? [config.prefix, ...data] : data;\n });\n}\n", "import { GitError } from '../errors/git-error';\nimport { GitExecutorResult, SimpleGitPluginConfig } from '../types';\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\ntype TaskResult = Omit;\n\nfunction isTaskError(result: TaskResult) {\n return !!(result.exitCode && result.stdErr.length);\n}\n\nfunction getErrorMessage(result: TaskResult) {\n return Buffer.concat([...result.stdOut, ...result.stdErr]);\n}\n\nexport function errorDetectionHandler(\n overwrite = false,\n isError = isTaskError,\n errorMessage: (result: TaskResult) => Buffer | Error = getErrorMessage\n) {\n return (error: Buffer | Error | undefined, result: TaskResult) => {\n if ((!overwrite && error) || !isError(result)) {\n return error;\n }\n\n return errorMessage(result);\n };\n}\n\nexport function errorDetectionPlugin(\n config: SimpleGitPluginConfig['errors']\n): SimpleGitPlugin<'task.error'> {\n return {\n type: 'task.error',\n action(data, context) {\n const error = config(data.error, {\n stdErr: context.stdErr,\n stdOut: context.stdOut,\n exitCode: context.exitCode,\n });\n\n if (Buffer.isBuffer(error)) {\n return { error: new GitError(undefined, error.toString('utf-8')) };\n }\n\n return {\n error,\n };\n },\n };\n}\n", "import { EventEmitter } from 'node:events';\n\nimport type {\n SimpleGitPlugin,\n SimpleGitPluginType,\n SimpleGitPluginTypes,\n} from './simple-git-plugin';\nimport { append, asArray } from '../utils';\nimport type { SimpleGitPluginConfig } from '../types';\n\nexport class PluginStore {\n private plugins: Set> = new Set();\n private events = new EventEmitter();\n\n on(\n type: K,\n listener: (data: SimpleGitPluginConfig[K]) => void\n ) {\n this.events.on(type, listener);\n }\n\n reconfigure(type: K, data: SimpleGitPluginConfig[K]) {\n this.events.emit(type, data);\n }\n\n public append(type: T, action: SimpleGitPlugin['action']) {\n const plugin = append(this.plugins, { type, action });\n\n return () => this.plugins.delete(plugin);\n }\n\n public add(\n plugin: void | SimpleGitPlugin | SimpleGitPlugin[]\n ) {\n const plugins: SimpleGitPlugin[] = [];\n\n asArray(plugin).forEach((plugin) => plugin && this.plugins.add(append(plugins, plugin)));\n\n return () => {\n plugins.forEach((plugin) => this.plugins.delete(plugin));\n };\n }\n\n public exec(\n type: T,\n data: SimpleGitPluginTypes[T]['data'],\n context: SimpleGitPluginTypes[T]['context']\n ): typeof data {\n let output = data;\n const contextual = Object.freeze(Object.create(context));\n\n for (const plugin of this.plugins) {\n if (plugin.type === type) {\n output = plugin.action(output, contextual);\n }\n }\n\n return output;\n }\n}\n", "import { SimpleGitOptions } from '../types';\nimport { asNumber, including } from '../utils';\n\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\nexport function progressMonitorPlugin(progress: Exclude) {\n const progressCommand = '--progress';\n const progressMethods = ['checkout', 'clone', 'fetch', 'pull', 'push'];\n\n const onProgress: SimpleGitPlugin<'spawn.after'> = {\n type: 'spawn.after',\n action(_data, context) {\n if (!context.commands.includes(progressCommand)) {\n return;\n }\n\n context.spawned.stderr?.on('data', (chunk: Buffer) => {\n const message = /^([\\s\\S]+?):\\s*(\\d+)% \\((\\d+)\\/(\\d+)\\)/.exec(chunk.toString('utf8'));\n if (!message) {\n return;\n }\n\n progress({\n method: context.method,\n stage: progressEventStage(message[1]),\n progress: asNumber(message[2]),\n processed: asNumber(message[3]),\n total: asNumber(message[4]),\n });\n });\n },\n };\n\n const onArgs: SimpleGitPlugin<'spawn.args'> = {\n type: 'spawn.args',\n action(args, context) {\n if (!progressMethods.includes(context.method)) {\n return args;\n }\n\n return including(args, progressCommand);\n },\n };\n\n return [onArgs, onProgress];\n}\n\nfunction progressEventStage(input: string) {\n return String(input.toLowerCase().split(' ', 1)) || 'unknown';\n}\n", "import { ChildProcess, SpawnOptions } from 'child_process';\nimport { GitExecutorResult } from '../types';\n\ntype SimpleGitTaskPluginContext = {\n readonly method: string;\n readonly commands: string[];\n};\n\nexport interface SimpleGitPluginTypes {\n 'spawn.args': {\n data: string[];\n context: SimpleGitTaskPluginContext & {};\n };\n 'spawn.binary': {\n data: string;\n context: SimpleGitTaskPluginContext & {};\n };\n 'spawn.options': {\n data: Partial;\n context: SimpleGitTaskPluginContext & {};\n };\n 'spawn.before': {\n data: void;\n context: SimpleGitTaskPluginContext & {\n kill(reason: Error): void;\n };\n };\n 'spawn.after': {\n data: void;\n context: SimpleGitTaskPluginContext & {\n spawned: ChildProcess;\n close(exitCode: number, reason?: Error): void;\n kill(reason: Error): void;\n };\n };\n 'task.error': {\n data: { error?: Error };\n context: SimpleGitTaskPluginContext & GitExecutorResult;\n };\n}\n\nexport type SimpleGitPluginType = keyof SimpleGitPluginTypes;\n\nexport interface SimpleGitPlugin {\n action(\n data: SimpleGitPluginTypes[T]['data'],\n context: SimpleGitPluginTypes[T]['context']\n ): typeof data;\n\n type: T;\n}\n", "import { SpawnOptions } from 'child_process';\nimport { pick } from '../utils';\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\nexport function spawnOptionsPlugin(\n spawnOptions: Partial\n): SimpleGitPlugin<'spawn.options'> {\n const options = pick(spawnOptions, ['uid', 'gid']);\n\n return {\n type: 'spawn.options',\n action(data) {\n return { ...options, ...data };\n },\n };\n}\n", "import type { SimpleGitPlugin } from './simple-git-plugin';\n\nimport type { SimpleGitOptions } from '../types';\nimport { GitPluginError } from '../errors/git-plugin-error';\n\nexport function timeoutPlugin({\n block,\n stdErr = true,\n stdOut = true,\n}: Exclude): SimpleGitPlugin<'spawn.after'> | void {\n if (block > 0) {\n return {\n type: 'spawn.after',\n action(_data, context) {\n let timeout: NodeJS.Timeout;\n\n function wait() {\n timeout && clearTimeout(timeout);\n timeout = setTimeout(kill, block);\n }\n\n function stop() {\n context.spawned.stdout?.off('data', wait);\n context.spawned.stderr?.off('data', wait);\n context.spawned.off('exit', stop);\n context.spawned.off('close', stop);\n timeout && clearTimeout(timeout);\n }\n\n function kill() {\n stop();\n context.kill(new GitPluginError(undefined, 'timeout', `block timeout reached`));\n }\n\n stdOut && context.spawned.stdout?.on('data', wait);\n stdErr && context.spawned.stderr?.on('data', wait);\n context.spawned.on('exit', stop);\n context.spawned.on('close', stop);\n\n wait();\n },\n };\n }\n}\n", "export * from './abort-plugin';\nexport * from './block-unsafe-operations-plugin';\nexport * from './command-config-prefixing-plugin';\nexport * from './completion-detection.plugin';\nexport * from './custom-binary.plugin';\nexport * from './error-detection.plugin';\nexport * from './plugin-store';\nexport * from './progress-monitor-plugin';\nexport * from './simple-git-plugin';\nexport * from './spawn-options-plugin';\nexport * from './timout-plugin';\n", "import { SimpleGitPlugin } from './simple-git-plugin';\nimport { isPathSpec, toPaths } from '../args/pathspec';\n\nexport function suffixPathsPlugin(): SimpleGitPlugin<'spawn.args'> {\n return {\n type: 'spawn.args',\n action(data) {\n const prefix: string[] = [];\n let suffix: undefined | string[];\n function append(args: string[]) {\n (suffix = suffix || []).push(...args);\n }\n\n for (let i = 0; i < data.length; i++) {\n const param = data[i];\n\n if (isPathSpec(param)) {\n append(toPaths(param));\n continue;\n }\n\n if (param === '--') {\n append(\n data.slice(i + 1).flatMap((item) => (isPathSpec(item) && toPaths(item)) || item)\n );\n break;\n }\n\n prefix.push(param);\n }\n\n return !suffix ? prefix : [...prefix, '--', ...suffix.map(String)];\n },\n };\n}\n", "import debug, { Debugger } from 'debug';\nimport {\n append,\n filterHasLength,\n filterString,\n filterType,\n NOOP,\n objectToString,\n remove,\n} from './utils';\nimport { Maybe } from './types';\n\ndebug.formatters.L = (value: any) => String(filterHasLength(value) ? value.length : '-');\ndebug.formatters.B = (value: Buffer) => {\n if (Buffer.isBuffer(value)) {\n return value.toString('utf8');\n }\n return objectToString(value);\n};\n\ntype OutputLoggingHandler = (message: string, ...args: any[]) => void;\n\nfunction createLog() {\n return debug('simple-git');\n}\n\nexport interface OutputLogger extends OutputLoggingHandler {\n readonly label: string;\n\n info: OutputLoggingHandler;\n step(nextStep?: string): OutputLogger;\n sibling(name: string): OutputLogger;\n}\n\nfunction prefixedLogger(\n to: Debugger,\n prefix: string,\n forward?: OutputLoggingHandler\n): OutputLoggingHandler {\n if (!prefix || !String(prefix).replace(/\\s*/, '')) {\n return !forward\n ? to\n : (message, ...args) => {\n to(message, ...args);\n forward(message, ...args);\n };\n }\n\n return (message, ...args) => {\n to(`%s ${message}`, prefix, ...args);\n if (forward) {\n forward(message, ...args);\n }\n };\n}\n\nfunction childLoggerName(\n name: Maybe,\n childDebugger: Maybe,\n { namespace: parentNamespace }: Debugger\n): string {\n if (typeof name === 'string') {\n return name;\n }\n const childNamespace = (childDebugger && childDebugger.namespace) || '';\n\n if (childNamespace.startsWith(parentNamespace)) {\n return childNamespace.substr(parentNamespace.length + 1);\n }\n\n return childNamespace || parentNamespace;\n}\n\nexport function createLogger(\n label: string,\n verbose?: string | Debugger,\n initialStep?: string,\n infoDebugger = createLog()\n): OutputLogger {\n const labelPrefix = (label && `[${label}]`) || '';\n\n const spawned: OutputLogger[] = [];\n const debugDebugger: Maybe =\n typeof verbose === 'string' ? infoDebugger.extend(verbose) : verbose;\n const key = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger);\n\n return step(initialStep);\n\n function sibling(name: string, initial?: string) {\n return append(\n spawned,\n createLogger(label, key.replace(/^[^:]+/, name), initial, infoDebugger)\n );\n }\n\n function step(phase?: string) {\n const stepPrefix = (phase && `[${phase}]`) || '';\n const debug = (debugDebugger && prefixedLogger(debugDebugger, stepPrefix)) || NOOP;\n const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug);\n\n return Object.assign(debugDebugger ? debug : info, {\n label,\n sibling,\n info,\n step,\n });\n }\n}\n\n/**\n * The `GitLogger` is used by the main `SimpleGit` runner to handle logging\n * any warnings or errors.\n */\nexport class GitLogger {\n public error: OutputLoggingHandler;\n\n public warn: OutputLoggingHandler;\n\n constructor(private _out: Debugger = createLog()) {\n this.error = prefixedLogger(_out, '[ERROR]');\n this.warn = prefixedLogger(_out, '[WARN]');\n }\n\n silent(silence = false) {\n if (silence !== this._out.enabled) {\n return;\n }\n\n const { namespace } = this._out;\n const env = (process.env.DEBUG || '').split(',').filter((s) => !!s);\n const hasOn = env.includes(namespace);\n const hasOff = env.includes(`-${namespace}`);\n\n // enabling the log\n if (!silence) {\n if (hasOff) {\n remove(env, `-${namespace}`);\n } else {\n env.push(namespace);\n }\n } else {\n if (hasOn) {\n remove(env, namespace);\n } else {\n env.push(`-${namespace}`);\n }\n }\n\n debug.enable(env.join(','));\n }\n}\n", "import { SimpleGitTask } from '../types';\nimport { GitError } from '../errors/git-error';\nimport { createLogger, OutputLogger } from '../git-logger';\n\ntype AnySimpleGitTask = SimpleGitTask;\n\ntype TaskInProgress = {\n name: string;\n logger: OutputLogger;\n task: AnySimpleGitTask;\n};\n\nexport class TasksPendingQueue {\n private _queue: Map = new Map();\n\n constructor(private logLabel = 'GitExecutor') {}\n\n private withProgress(task: AnySimpleGitTask) {\n return this._queue.get(task);\n }\n\n private createProgress(task: AnySimpleGitTask): TaskInProgress {\n const name = TasksPendingQueue.getName(task.commands[0]);\n const logger = createLogger(this.logLabel, name);\n\n return {\n task,\n logger,\n name,\n };\n }\n\n push(task: AnySimpleGitTask): TaskInProgress {\n const progress = this.createProgress(task);\n progress.logger('Adding task to the queue, commands = %o', task.commands);\n\n this._queue.set(task, progress);\n\n return progress;\n }\n\n fatal(err: GitError) {\n for (const [task, { logger }] of Array.from(this._queue.entries())) {\n if (task === err.task) {\n logger.info(`Failed %o`, err);\n logger(\n `Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`\n );\n } else {\n logger.info(\n `A fatal exception occurred in a previous task, the queue has been purged: %o`,\n err.message\n );\n }\n\n this.complete(task);\n }\n\n if (this._queue.size !== 0) {\n throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`);\n }\n }\n\n complete(task: AnySimpleGitTask) {\n const progress = this.withProgress(task);\n if (progress) {\n this._queue.delete(task);\n }\n }\n\n attempt(task: AnySimpleGitTask): TaskInProgress {\n const progress = this.withProgress(task);\n if (!progress) {\n throw new GitError(undefined, 'TasksPendingQueue: attempt called for an unknown task');\n }\n progress.logger('Starting task');\n\n return progress;\n }\n\n static getName(name = 'empty') {\n return `task:${name}:${++TasksPendingQueue.counter}`;\n }\n\n private static counter = 0;\n}\n", "import { spawn, SpawnOptions } from 'child_process';\nimport { GitError } from '../errors/git-error';\nimport { OutputLogger } from '../git-logger';\nimport { PluginStore } from '../plugins';\nimport { EmptyTask, isBufferTask, isEmptyTask } from '../tasks/task';\nimport {\n GitExecutorResult,\n Maybe,\n outputHandler,\n RunnableTask,\n SimpleGitExecutor,\n SimpleGitTask,\n} from '../types';\nimport { callTaskParser, first, GitOutputStreams, objectToString } from '../utils';\nimport { Scheduler } from './scheduler';\nimport { TasksPendingQueue } from './tasks-pending-queue';\n\nexport class GitExecutorChain implements SimpleGitExecutor {\n private _chain: Promise = Promise.resolve();\n private _queue = new TasksPendingQueue();\n private _cwd: string | undefined;\n\n public get cwd() {\n return this._cwd || this._executor.cwd;\n }\n\n public set cwd(cwd: string) {\n this._cwd = cwd;\n }\n\n public get env() {\n return this._executor.env;\n }\n\n public get outputHandler() {\n return this._executor.outputHandler;\n }\n\n constructor(\n private _executor: SimpleGitExecutor,\n private _scheduler: Scheduler,\n private _plugins: PluginStore\n ) {}\n\n public chain() {\n return this;\n }\n\n public push(task: SimpleGitTask): Promise {\n this._queue.push(task);\n\n return (this._chain = this._chain.then(() => this.attemptTask(task)));\n }\n\n private async attemptTask(task: SimpleGitTask): Promise {\n const onScheduleComplete = await this._scheduler.next();\n const onQueueComplete = () => this._queue.complete(task);\n\n try {\n const { logger } = this._queue.attempt(task);\n return (await (isEmptyTask(task)\n ? this.attemptEmptyTask(task, logger)\n : this.attemptRemoteTask(task, logger))) as R;\n } catch (e) {\n throw this.onFatalException(task, e as Error);\n } finally {\n onQueueComplete();\n onScheduleComplete();\n }\n }\n\n private onFatalException(task: SimpleGitTask, e: Error) {\n const gitError =\n e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e));\n\n this._chain = Promise.resolve();\n this._queue.fatal(gitError);\n\n return gitError;\n }\n\n private async attemptRemoteTask(task: RunnableTask, logger: OutputLogger) {\n const binary = this._plugins.exec('spawn.binary', '', pluginContext(task, task.commands));\n const args = this._plugins.exec(\n 'spawn.args',\n [...task.commands],\n pluginContext(task, task.commands)\n );\n\n const raw = await this.gitResponse(\n task,\n binary,\n args,\n this.outputHandler,\n logger.step('SPAWN')\n );\n const outputStreams = await this.handleTaskData(task, args, raw, logger.step('HANDLE'));\n\n logger(`passing response to task's parser as a %s`, task.format);\n\n if (isBufferTask(task)) {\n return callTaskParser(task.parser, outputStreams);\n }\n\n return callTaskParser(task.parser, outputStreams.asStrings());\n }\n\n private async attemptEmptyTask(task: EmptyTask, logger: OutputLogger) {\n logger(`empty task bypassing child process to call to task's parser`);\n return task.parser(this);\n }\n\n private handleTaskData(\n task: SimpleGitTask,\n args: string[],\n result: GitExecutorResult,\n logger: OutputLogger\n ): Promise {\n const { exitCode, rejection, stdOut, stdErr } = result;\n\n return new Promise((done, fail) => {\n logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode);\n\n const { error } = this._plugins.exec(\n 'task.error',\n { error: rejection },\n {\n ...pluginContext(task, args),\n ...result,\n }\n );\n\n if (error && task.onError) {\n logger.info(`exitCode=%s handling with custom error handler`);\n\n return task.onError(\n result,\n error,\n (newStdOut) => {\n logger.info(`custom error handler treated as success`);\n logger(`custom error returned a %s`, objectToString(newStdOut));\n\n done(\n new GitOutputStreams(\n Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut,\n Buffer.concat(stdErr)\n )\n );\n },\n fail\n );\n }\n\n if (error) {\n logger.info(\n `handling as error: exitCode=%s stdErr=%s rejection=%o`,\n exitCode,\n stdErr.length,\n rejection\n );\n return fail(error);\n }\n\n logger.info(`retrieving task output complete`);\n done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr)));\n });\n }\n\n private async gitResponse(\n task: SimpleGitTask,\n command: string,\n args: string[],\n outputHandler: Maybe,\n logger: OutputLogger\n ): Promise {\n const outputLogger = logger.sibling('output');\n const spawnOptions: SpawnOptions = this._plugins.exec(\n 'spawn.options',\n {\n cwd: this.cwd,\n env: this.env,\n windowsHide: true,\n },\n pluginContext(task, task.commands)\n );\n\n return new Promise((done) => {\n const stdOut: Buffer[] = [];\n const stdErr: Buffer[] = [];\n\n logger.info(`%s %o`, command, args);\n logger('%O', spawnOptions);\n\n let rejection = this._beforeSpawn(task, args);\n if (rejection) {\n return done({\n stdOut,\n stdErr,\n exitCode: 9901,\n rejection,\n });\n }\n\n this._plugins.exec('spawn.before', undefined, {\n ...pluginContext(task, args),\n kill(reason) {\n rejection = reason || rejection;\n },\n });\n\n const spawned = spawn(command, args, spawnOptions);\n\n spawned.stdout!.on(\n 'data',\n onDataReceived(stdOut, 'stdOut', logger, outputLogger.step('stdOut'))\n );\n spawned.stderr!.on(\n 'data',\n onDataReceived(stdErr, 'stdErr', logger, outputLogger.step('stdErr'))\n );\n\n spawned.on('error', onErrorReceived(stdErr, logger));\n\n if (outputHandler) {\n logger(`Passing child process stdOut/stdErr to custom outputHandler`);\n outputHandler(command, spawned.stdout!, spawned.stderr!, [...args]);\n }\n\n this._plugins.exec('spawn.after', undefined, {\n ...pluginContext(task, args),\n spawned,\n close(exitCode: number, reason?: Error) {\n done({\n stdOut,\n stdErr,\n exitCode,\n rejection: rejection || reason,\n });\n },\n kill(reason: Error) {\n if (spawned.killed) {\n return;\n }\n\n rejection = reason;\n spawned.kill('SIGINT');\n },\n });\n });\n }\n\n private _beforeSpawn(task: SimpleGitTask, args: string[]) {\n let rejection: Maybe;\n this._plugins.exec('spawn.before', undefined, {\n ...pluginContext(task, args),\n kill(reason) {\n rejection = reason || rejection;\n },\n });\n\n return rejection;\n }\n}\n\nfunction pluginContext(task: SimpleGitTask, commands: string[]) {\n return {\n method: first(task.commands) || '',\n commands,\n };\n}\n\nfunction onErrorReceived(target: Buffer[], logger: OutputLogger) {\n return (err: Error) => {\n logger(`[ERROR] child process exception %o`, err);\n target.push(Buffer.from(String(err.stack), 'ascii'));\n };\n}\n\nfunction onDataReceived(\n target: Buffer[],\n name: string,\n logger: OutputLogger,\n output: OutputLogger\n) {\n return (buffer: Buffer) => {\n logger(`%s received %L bytes`, name, buffer);\n output(`%B`, buffer);\n target.push(buffer);\n };\n}\n", "import type { PluginStore } from '../plugins';\nimport type { GitExecutorEnv, outputHandler, SimpleGitExecutor, SimpleGitTask } from '../types';\n\nimport { GitExecutorChain } from './git-executor-chain';\nimport { Scheduler } from './scheduler';\n\nexport class GitExecutor implements SimpleGitExecutor {\n private _chain = new GitExecutorChain(this, this._scheduler, this._plugins);\n\n public env: GitExecutorEnv;\n public outputHandler?: outputHandler;\n\n constructor(\n public cwd: string,\n private _scheduler: Scheduler,\n private _plugins: PluginStore\n ) {}\n\n chain(): SimpleGitExecutor {\n return new GitExecutorChain(this, this._scheduler, this._plugins);\n }\n\n push(task: SimpleGitTask): Promise {\n return this._chain.push(task);\n }\n}\n", "import { GitError } from './errors/git-error';\nimport { GitResponseError } from './errors/git-response-error';\nimport { SimpleGitTask, SimpleGitTaskCallback } from './types';\nimport { NOOP } from './utils';\n\nexport function taskCallback(\n task: SimpleGitTask,\n response: Promise,\n callback: SimpleGitTaskCallback = NOOP\n) {\n const onSuccess = (data: R) => {\n callback(null, data);\n };\n\n const onError = (err: GitError | GitResponseError) => {\n if (err?.task === task) {\n callback(\n err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err,\n undefined as any\n );\n }\n };\n\n response.then(onSuccess, onError);\n}\n\nfunction addDeprecationNoticeToError(err: GitResponseError) {\n let log = (name: string) => {\n console.warn(\n `simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3`\n );\n log = NOOP;\n };\n\n return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {}));\n\n function descriptorReducer(all: PropertyDescriptorMap, name: string): typeof all {\n if (name in err) {\n return all;\n }\n\n all[name] = {\n enumerable: false,\n configurable: false,\n get() {\n log(name);\n return err.git[name];\n },\n };\n\n return all;\n }\n}\n", "import { folderExists } from '../utils';\nimport { SimpleGitExecutor } from '../types';\nimport { adhocExecTask } from './task';\n\nexport function changeWorkingDirectoryTask(directory: string, root?: SimpleGitExecutor) {\n return adhocExecTask((instance: SimpleGitExecutor) => {\n if (!folderExists(directory)) {\n throw new Error(`Git.cwd: cannot change to non-directory \"${directory}\"`);\n }\n\n return ((root || instance).cwd = directory);\n });\n}\n", "import type { SimpleGit } from '../../../typings';\nimport type { SimpleGitApi } from '../simple-git-api';\nimport { getTrailingOptions, remove, trailingFunctionArgument } from '../utils';\nimport { straightThroughStringTask } from './task';\n\nfunction checkoutTask(args: string[]) {\n const commands = ['checkout', ...args];\n if (commands[1] === '-b' && commands.includes('-B')) {\n commands[1] = remove(commands, '-B');\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport default function (): Pick {\n return {\n checkout(this: SimpleGitApi) {\n return this._runTask(\n checkoutTask(getTrailingOptions(arguments, 1)),\n trailingFunctionArgument(arguments)\n );\n },\n\n checkoutBranch(this: SimpleGitApi, branchName, startPoint) {\n return this._runTask(\n checkoutTask(['-b', branchName, startPoint, ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments)\n );\n },\n\n checkoutLocalBranch(this: SimpleGitApi, branchName) {\n return this._runTask(\n checkoutTask(['-b', branchName, ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments)\n );\n },\n };\n}\n", "import { CommitResult } from '../../../typings';\nimport { LineParser, parseStringResponse } from '../utils';\n\nconst parsers: LineParser[] = [\n new LineParser(/^\\[([^\\s]+)( \\([^)]+\\))? ([^\\]]+)/, (result, [branch, root, commit]) => {\n result.branch = branch;\n result.commit = commit;\n result.root = !!root;\n }),\n new LineParser(/\\s*Author:\\s(.+)/i, (result, [author]) => {\n const parts = author.split('<');\n const email = parts.pop();\n\n if (!email || !email.includes('@')) {\n return;\n }\n\n result.author = {\n email: email.substr(0, email.length - 1),\n name: parts.join('<').trim(),\n };\n }),\n new LineParser(\n /(\\d+)[^,]*(?:,\\s*(\\d+)[^,]*)(?:,\\s*(\\d+))/g,\n (result, [changes, insertions, deletions]) => {\n result.summary.changes = parseInt(changes, 10) || 0;\n result.summary.insertions = parseInt(insertions, 10) || 0;\n result.summary.deletions = parseInt(deletions, 10) || 0;\n }\n ),\n new LineParser(\n /^(\\d+)[^,]*(?:,\\s*(\\d+)[^(]+\\(([+-]))?/,\n (result, [changes, lines, direction]) => {\n result.summary.changes = parseInt(changes, 10) || 0;\n const count = parseInt(lines, 10) || 0;\n if (direction === '-') {\n result.summary.deletions = count;\n } else if (direction === '+') {\n result.summary.insertions = count;\n }\n }\n ),\n];\n\nexport function parseCommitResult(stdOut: string): CommitResult {\n const result: CommitResult = {\n author: null,\n branch: '',\n commit: '',\n root: false,\n summary: {\n changes: 0,\n insertions: 0,\n deletions: 0,\n },\n };\n return parseStringResponse(result, parsers, stdOut);\n}\n", "import type { CommitResult, SimpleGit } from '../../../typings';\nimport type { SimpleGitApi } from '../simple-git-api';\nimport type { StringTask } from '../types';\nimport { parseCommitResult } from '../parsers/parse-commit';\nimport {\n asArray,\n filterArray,\n filterStringOrStringArray,\n filterType,\n getTrailingOptions,\n prefixedArray,\n trailingFunctionArgument,\n} from '../utils';\nimport { configurationErrorTask } from './task';\n\nexport function commitTask(\n message: string[],\n files: string[],\n customArgs: string[]\n): StringTask {\n const commands: string[] = [\n '-c',\n 'core.abbrev=40',\n 'commit',\n ...prefixedArray(message, '-m'),\n ...files,\n ...customArgs,\n ];\n\n return {\n commands,\n format: 'utf-8',\n parser: parseCommitResult,\n };\n}\n\nexport default function (): Pick {\n return {\n commit(this: SimpleGitApi, message: string | string[], ...rest: unknown[]) {\n const next = trailingFunctionArgument(arguments);\n const task =\n rejectDeprecatedSignatures(message) ||\n commitTask(\n asArray(message),\n asArray(filterType(rest[0], filterStringOrStringArray, [])),\n [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)]\n );\n\n return this._runTask(task, next);\n },\n };\n\n function rejectDeprecatedSignatures(message?: unknown) {\n return (\n !filterStringOrStringArray(message) &&\n configurationErrorTask(\n `git.commit: requires the commit message to be supplied as a string/string[]`\n )\n );\n }\n}\n", "import { Response, SimpleGit } from '../../../typings';\nimport { SimpleGitApi } from '../simple-git-api';\nimport { trailingFunctionArgument } from '../utils';\nimport { straightThroughStringTask } from './task';\n\nexport default function (): Pick {\n return {\n firstCommit(this: SimpleGitApi): Response {\n return this._runTask(\n straightThroughStringTask(['rev-list', '--max-parents=0', 'HEAD'], true),\n trailingFunctionArgument(arguments)\n );\n },\n };\n}\n", "import { straightThroughStringTask } from './task';\nimport { StringTask } from '../types';\n\n/**\n * Task used by `git.hashObject`\n */\nexport function hashObjectTask(filePath: string, write: boolean): StringTask {\n const commands = ['hash-object', filePath];\n if (write) {\n commands.push('-w');\n }\n\n return straightThroughStringTask(commands, true);\n}\n", "import { InitResult } from '../../../typings';\n\nexport class InitSummary implements InitResult {\n constructor(\n public readonly bare: boolean,\n public readonly path: string,\n public readonly existing: boolean,\n public readonly gitDir: string\n ) {}\n}\n\nconst initResponseRegex = /^Init.+ repository in (.+)$/;\nconst reInitResponseRegex = /^Rein.+ in (.+)$/;\n\nexport function parseInit(bare: boolean, path: string, text: string) {\n const response = String(text).trim();\n let result;\n\n if ((result = initResponseRegex.exec(response))) {\n return new InitSummary(bare, path, false, result[1]);\n }\n\n if ((result = reInitResponseRegex.exec(response))) {\n return new InitSummary(bare, path, true, result[1]);\n }\n\n let gitDir = '';\n const tokens = response.split(' ');\n while (tokens.length) {\n const token = tokens.shift();\n if (token === 'in') {\n gitDir = tokens.join(' ');\n break;\n }\n }\n\n return new InitSummary(bare, path, /^re/i.test(response), gitDir);\n}\n", "import { InitResult } from '../../../typings';\nimport { parseInit } from '../responses/InitSummary';\nimport { StringTask } from '../types';\n\nconst bareCommand = '--bare';\n\nfunction hasBareCommand(command: string[]) {\n return command.includes(bareCommand);\n}\n\nexport function initTask(bare = false, path: string, customArgs: string[]): StringTask {\n const commands = ['init', ...customArgs];\n if (bare && !hasBareCommand(commands)) {\n commands.splice(1, 0, bareCommand);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser(text: string): InitResult {\n return parseInit(commands.includes('--bare'), path, text);\n },\n };\n}\n", "export enum LogFormat {\n NONE = '',\n STAT = '--stat',\n NUM_STAT = '--numstat',\n NAME_ONLY = '--name-only',\n NAME_STATUS = '--name-status',\n}\n\nconst logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/;\n\nexport function logFormatFromCommand(customArgs: string[]) {\n for (let i = 0; i < customArgs.length; i++) {\n const format = logFormatRegex.exec(customArgs[i]);\n if (format) {\n return `--${format[1]}` as LogFormat;\n }\n }\n\n return LogFormat.NONE;\n}\n\nexport function isLogFormat(customArg: string | unknown) {\n return logFormatRegex.test(customArg as string);\n}\n", "import { DiffResult, DiffResultBinaryFile, DiffResultTextFile } from '../../../typings';\n\n/***\n * The DiffSummary is returned as a response to getting `git().status()`\n */\nexport class DiffSummary implements DiffResult {\n changed = 0;\n deletions = 0;\n insertions = 0;\n\n files: Array = [];\n}\n", "import { DiffResult } from '../../../typings';\nimport { LogFormat } from '../args/log-format';\nimport { DiffSummary } from '../responses/DiffSummary';\nimport { isDiffNameStatus } from '../tasks/diff-name-status';\nimport { asNumber, LineParser, orVoid, parseStringResponse } from '../utils';\n\nconst statParser = [\n new LineParser(\n /^(.+)\\s+\\|\\s+(\\d+)(\\s+[+\\-]+)?$/,\n (result, [file, changes, alterations = '']) => {\n result.files.push({\n file: file.trim(),\n changes: asNumber(changes),\n insertions: alterations.replace(/[^+]/g, '').length,\n deletions: alterations.replace(/[^-]/g, '').length,\n binary: false,\n });\n }\n ),\n new LineParser(\n /^(.+) \\|\\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,\n (result, [file, before, after]) => {\n result.files.push({\n file: file.trim(),\n before: asNumber(before),\n after: asNumber(after),\n binary: true,\n });\n }\n ),\n new LineParser(\n /(\\d+) files? changed\\s*((?:, \\d+ [^,]+){0,2})/,\n (result, [changed, summary]) => {\n const inserted = /(\\d+) i/.exec(summary);\n const deleted = /(\\d+) d/.exec(summary);\n\n result.changed = asNumber(changed);\n result.insertions = asNumber(inserted?.[1]);\n result.deletions = asNumber(deleted?.[1]);\n }\n ),\n];\n\nconst numStatParser = [\n new LineParser(\n /(\\d+)\\t(\\d+)\\t(.+)$/,\n (result, [changesInsert, changesDelete, file]) => {\n const insertions = asNumber(changesInsert);\n const deletions = asNumber(changesDelete);\n\n result.changed++;\n result.insertions += insertions;\n result.deletions += deletions;\n\n result.files.push({\n file,\n changes: insertions + deletions,\n insertions,\n deletions,\n binary: false,\n });\n }\n ),\n new LineParser(/-\\t-\\t(.+)$/, (result, [file]) => {\n result.changed++;\n\n result.files.push({\n file,\n after: 0,\n before: 0,\n binary: true,\n });\n }),\n];\n\nconst nameOnlyParser = [\n new LineParser(/(.+)$/, (result, [file]) => {\n result.changed++;\n result.files.push({\n file,\n changes: 0,\n insertions: 0,\n deletions: 0,\n binary: false,\n });\n }),\n];\n\nconst nameStatusParser = [\n new LineParser(\n /([ACDMRTUXB])([0-9]{0,3})\\t(.[^\\t]*)(\\t(.[^\\t]*))?$/,\n (result, [status, _similarity, from, _to, to]) => {\n result.changed++;\n result.files.push({\n file: to ?? from,\n changes: 0,\n status: orVoid(isDiffNameStatus(status) && status),\n insertions: 0,\n deletions: 0,\n binary: false,\n });\n }\n ),\n];\n\nconst diffSummaryParsers: Record[]> = {\n [LogFormat.NONE]: statParser,\n [LogFormat.STAT]: statParser,\n [LogFormat.NUM_STAT]: numStatParser,\n [LogFormat.NAME_STATUS]: nameStatusParser,\n [LogFormat.NAME_ONLY]: nameOnlyParser,\n};\n\nexport function getDiffParser(format = LogFormat.NONE) {\n const parser = diffSummaryParsers[format];\n\n return (stdOut: string) => parseStringResponse(new DiffSummary(), parser, stdOut, false);\n}\n", "import { ListLogLine, LogResult } from '../../../typings';\nimport { toLinesWithContent } from '../utils';\nimport { getDiffParser } from './parse-diff-summary';\nimport { LogFormat } from '../args/log-format';\n\nexport const START_BOUNDARY = '\u00F2\u00F2\u00F2\u00F2\u00F2\u00F2 ';\n\nexport const COMMIT_BOUNDARY = ' \u00F2\u00F2';\n\nexport const SPLITTER = ' \u00F2 ';\n\nconst defaultFieldNames = ['hash', 'date', 'message', 'refs', 'author_name', 'author_email'];\n\nfunction lineBuilder(tokens: string[], fields: string[]): any {\n return fields.reduce(\n (line, field, index) => {\n line[field] = tokens[index] || '';\n return line;\n },\n Object.create({ diff: null }) as any\n );\n}\n\nexport function createListLogSummaryParser(\n splitter = SPLITTER,\n fields = defaultFieldNames,\n logFormat = LogFormat.NONE\n) {\n const parseDiffResult = getDiffParser(logFormat);\n\n return function (stdOut: string): LogResult {\n const all: ReadonlyArray = toLinesWithContent(\n stdOut,\n true,\n START_BOUNDARY\n ).map(function (item) {\n const lineDetail = item.trim().split(COMMIT_BOUNDARY);\n const listLogLine: T & ListLogLine = lineBuilder(\n lineDetail[0].trim().split(splitter),\n fields\n );\n\n if (lineDetail.length > 1 && !!lineDetail[1].trim()) {\n listLogLine.diff = parseDiffResult(lineDetail[1]);\n }\n\n return listLogLine;\n });\n\n return {\n all,\n latest: (all.length && all[0]) || null,\n total: all.length,\n };\n };\n}\n", "import { StringTask } from '../types';\nimport { DiffResult } from '../../../typings';\nimport { isLogFormat, LogFormat, logFormatFromCommand } from '../args/log-format';\nimport { getDiffParser } from '../parsers/parse-diff-summary';\nimport { configurationErrorTask, EmptyTask } from './task';\n\nexport function diffSummaryTask(customArgs: string[]): StringTask | EmptyTask {\n let logFormat = logFormatFromCommand(customArgs);\n\n const commands = ['diff'];\n\n if (logFormat === LogFormat.NONE) {\n logFormat = LogFormat.STAT;\n commands.push('--stat=4096');\n }\n\n commands.push(...customArgs);\n\n return (\n validateLogFormatConfig(commands) || {\n commands,\n format: 'utf-8',\n parser: getDiffParser(logFormat),\n }\n );\n}\n\nexport function validateLogFormatConfig(customArgs: unknown[]): EmptyTask | void {\n const flags = customArgs.filter(isLogFormat);\n\n if (flags.length > 1) {\n return configurationErrorTask(\n `Summary flags are mutually exclusive - pick one of ${flags.join(',')}`\n );\n }\n\n if (flags.length && customArgs.includes('-z')) {\n return configurationErrorTask(\n `Summary flag ${flags} parsing is not compatible with null termination option '-z'`\n );\n }\n}\n", "import type { Options, StringTask } from '../types';\nimport type { LogResult, SimpleGit } from '../../../typings';\nimport { logFormatFromCommand } from '../args/log-format';\nimport { pathspec } from '../args/pathspec';\nimport {\n COMMIT_BOUNDARY,\n createListLogSummaryParser,\n SPLITTER,\n START_BOUNDARY,\n} from '../parsers/parse-list-log-summary';\nimport {\n appendTaskOptions,\n filterArray,\n filterPrimitives,\n filterString,\n filterType,\n trailingFunctionArgument,\n trailingOptionsArgument,\n} from '../utils';\nimport { SimpleGitApi } from '../simple-git-api';\nimport { configurationErrorTask } from './task';\nimport { validateLogFormatConfig } from './diff';\n\nenum excludeOptions {\n '--pretty',\n 'max-count',\n 'maxCount',\n 'n',\n 'file',\n 'format',\n 'from',\n 'to',\n 'splitter',\n 'symmetric',\n 'mailMap',\n 'multiLine',\n 'strictDate',\n}\n\nexport interface DefaultLogFields {\n hash: string;\n date: string;\n message: string;\n refs: string;\n body: string;\n author_name: string;\n author_email: string;\n}\n\nexport type LogOptions = {\n file?: string;\n format?: T;\n from?: string;\n mailMap?: boolean;\n maxCount?: number;\n multiLine?: boolean;\n splitter?: string;\n strictDate?: boolean;\n symmetric?: boolean;\n to?: string;\n};\n\ninterface ParsedLogOptions {\n fields: string[];\n splitter: string;\n commands: string[];\n}\n\nfunction prettyFormat(\n format: Record,\n splitter: string\n): [string[], string] {\n const fields: string[] = [];\n const formatStr: string[] = [];\n\n Object.keys(format).forEach((field) => {\n fields.push(field);\n formatStr.push(String(format[field]));\n });\n\n return [fields, formatStr.join(splitter)];\n}\n\nfunction userOptions(input: T): Options {\n return Object.keys(input).reduce((out, key) => {\n if (!(key in excludeOptions)) {\n out[key] = input[key];\n }\n return out;\n }, {} as Options);\n}\n\nexport function parseLogOptions(\n opt: Options | LogOptions = {},\n customArgs: string[] = []\n): ParsedLogOptions {\n const splitter = filterType(opt.splitter, filterString, SPLITTER);\n const format =\n !filterPrimitives(opt.format) && opt.format\n ? opt.format\n : {\n hash: '%H',\n date: opt.strictDate === false ? '%ai' : '%aI',\n message: '%s',\n refs: '%D',\n body: opt.multiLine ? '%B' : '%b',\n author_name: opt.mailMap !== false ? '%aN' : '%an',\n author_email: opt.mailMap !== false ? '%aE' : '%ae',\n };\n\n const [fields, formatStr] = prettyFormat(format, splitter);\n\n const suffix: string[] = [];\n const command: string[] = [\n `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`,\n ...customArgs,\n ];\n\n const maxCount: number | undefined = (opt as any).n || (opt as any)['max-count'] || opt.maxCount;\n if (maxCount) {\n command.push(`--max-count=${maxCount}`);\n }\n\n if (opt.from || opt.to) {\n const rangeOperator = opt.symmetric !== false ? '...' : '..';\n suffix.push(`${opt.from || ''}${rangeOperator}${opt.to || ''}`);\n }\n\n if (filterString(opt.file)) {\n command.push('--follow', pathspec(opt.file));\n }\n\n appendTaskOptions(userOptions(opt as Options), command);\n\n return {\n fields,\n splitter,\n commands: [...command, ...suffix],\n };\n}\n\nexport function logTask(\n splitter: string,\n fields: string[],\n customArgs: string[]\n): StringTask> {\n const parser = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs));\n\n return {\n commands: ['log', ...customArgs],\n format: 'utf-8',\n parser,\n };\n}\n\nexport default function (): Pick {\n return {\n log(this: SimpleGitApi, ...rest: unknown[]) {\n const next = trailingFunctionArgument(arguments);\n const options = parseLogOptions(\n trailingOptionsArgument(arguments),\n filterType(arguments[0], filterArray)\n );\n const task =\n rejectDeprecatedSignatures(...rest) ||\n validateLogFormatConfig(options.commands) ||\n createLogTask(options);\n\n return this._runTask(task, next);\n },\n };\n\n function createLogTask(options: ParsedLogOptions) {\n return logTask(options.splitter, options.fields, options.commands);\n }\n\n function rejectDeprecatedSignatures(from?: unknown, to?: unknown) {\n return (\n filterString(from) &&\n filterString(to) &&\n configurationErrorTask(\n `git.log(string, string) should be replaced with git.log({ from: string, to: string })`\n )\n );\n }\n}\n", "import {\n MergeConflict,\n MergeConflictDeletion,\n MergeDetail,\n MergeResultStatus,\n} from '../../../typings';\n\nexport class MergeSummaryConflict implements MergeConflict {\n constructor(\n public readonly reason: string,\n public readonly file: string | null = null,\n public readonly meta?: MergeConflictDeletion\n ) {}\n\n toString() {\n return `${this.file}:${this.reason}`;\n }\n}\n\nexport class MergeSummaryDetail implements MergeDetail {\n public conflicts: MergeConflict[] = [];\n public merges: string[] = [];\n public result: MergeResultStatus = 'success';\n\n get failed() {\n return this.conflicts.length > 0;\n }\n\n get reason() {\n return this.result;\n }\n\n toString() {\n if (this.conflicts.length) {\n return `CONFLICTS: ${this.conflicts.join(', ')}`;\n }\n\n return 'OK';\n }\n}\n", "import {\n PullDetailFileChanges,\n PullDetailSummary,\n PullFailedResult,\n PullResult,\n} from '../../../typings';\n\nexport class PullSummary implements PullResult {\n public remoteMessages = {\n all: [],\n };\n public created = [];\n public deleted: string[] = [];\n public files: string[] = [];\n public deletions: PullDetailFileChanges = {};\n public insertions: PullDetailFileChanges = {};\n public summary: PullDetailSummary = {\n changes: 0,\n deletions: 0,\n insertions: 0,\n };\n}\n\nexport class PullFailedSummary implements PullFailedResult {\n remote = '';\n hash = {\n local: '',\n remote: '',\n };\n branch = {\n local: '',\n remote: '',\n };\n message = '';\n\n toString() {\n return this.message;\n }\n}\n", "import {\n RemoteMessageResult,\n RemoteMessages,\n RemoteMessagesObjectEnumeration,\n} from '../../../typings';\nimport { asNumber, RemoteLineParser } from '../utils';\n\nfunction objectEnumerationResult(\n remoteMessages: T\n): RemoteMessagesObjectEnumeration {\n return (remoteMessages.objects = remoteMessages.objects || {\n compressing: 0,\n counting: 0,\n enumerating: 0,\n packReused: 0,\n reused: { count: 0, delta: 0 },\n total: { count: 0, delta: 0 },\n });\n}\n\nfunction asObjectCount(source: string) {\n const count = /^\\s*(\\d+)/.exec(source);\n const delta = /delta (\\d+)/i.exec(source);\n\n return {\n count: asNumber((count && count[1]) || '0'),\n delta: asNumber((delta && delta[1]) || '0'),\n };\n}\n\nexport const remoteMessagesObjectParsers: RemoteLineParser>[] =\n [\n new RemoteLineParser(\n /^remote:\\s*(enumerating|counting|compressing) objects: (\\d+),/i,\n (result, [action, count]) => {\n const key = action.toLowerCase();\n const enumeration = objectEnumerationResult(result.remoteMessages);\n\n Object.assign(enumeration, { [key]: asNumber(count) });\n }\n ),\n new RemoteLineParser(\n /^remote:\\s*(enumerating|counting|compressing) objects: \\d+% \\(\\d+\\/(\\d+)\\),/i,\n (result, [action, count]) => {\n const key = action.toLowerCase();\n const enumeration = objectEnumerationResult(result.remoteMessages);\n\n Object.assign(enumeration, { [key]: asNumber(count) });\n }\n ),\n new RemoteLineParser(\n /total ([^,]+), reused ([^,]+), pack-reused (\\d+)/i,\n (result, [total, reused, packReused]) => {\n const objects = objectEnumerationResult(result.remoteMessages);\n objects.total = asObjectCount(total);\n objects.reused = asObjectCount(reused);\n objects.packReused = asNumber(packReused);\n }\n ),\n ];\n", "import { PushResultRemoteMessages, RemoteMessageResult, RemoteMessages } from '../../../typings';\nimport { asNumber, parseStringResponse, RemoteLineParser } from '../utils';\nimport { remoteMessagesObjectParsers } from './parse-remote-objects';\n\nconst parsers: RemoteLineParser>[] =\n [\n new RemoteLineParser(/^remote:\\s*(.+)$/, (result, [text]) => {\n result.remoteMessages.all.push(text.trim());\n return false;\n }),\n ...remoteMessagesObjectParsers,\n new RemoteLineParser(\n [/create a (?:pull|merge) request/i, /\\s(https?:\\/\\/\\S+)$/],\n (result, [pullRequestUrl]) => {\n (result.remoteMessages as PushResultRemoteMessages).pullRequestUrl = pullRequestUrl;\n }\n ),\n new RemoteLineParser(\n [/found (\\d+) vulnerabilities.+\\(([^)]+)\\)/i, /\\s(https?:\\/\\/\\S+)$/],\n (result, [count, summary, url]) => {\n (result.remoteMessages as PushResultRemoteMessages).vulnerabilities = {\n count: asNumber(count),\n summary,\n url,\n };\n }\n ),\n ];\n\nexport function parseRemoteMessages(\n _stdOut: string,\n stdErr: string\n): RemoteMessageResult {\n return parseStringResponse({ remoteMessages: new RemoteMessageSummary() as T }, parsers, stdErr);\n}\n\nexport class RemoteMessageSummary implements RemoteMessages {\n public readonly all: string[] = [];\n}\n", "import { PullDetail, PullFailedResult, PullResult, RemoteMessages } from '../../../typings';\nimport { PullFailedSummary, PullSummary } from '../responses/PullSummary';\nimport { TaskParser } from '../types';\nimport { append, LineParser, parseStringResponse } from '../utils';\nimport { parseRemoteMessages } from './parse-remote-messages';\n\nconst FILE_UPDATE_REGEX = /^\\s*(.+?)\\s+\\|\\s+\\d+\\s*(\\+*)(-*)/;\nconst SUMMARY_REGEX = /(\\d+)\\D+((\\d+)\\D+\\(\\+\\))?(\\D+(\\d+)\\D+\\(-\\))?/;\nconst ACTION_REGEX = /^(create|delete) mode \\d+ (.+)/;\n\nconst parsers: LineParser[] = [\n new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => {\n result.files.push(file);\n\n if (insertions) {\n result.insertions[file] = insertions.length;\n }\n\n if (deletions) {\n result.deletions[file] = deletions.length;\n }\n }),\n new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => {\n if (insertions !== undefined || deletions !== undefined) {\n result.summary.changes = +changes || 0;\n result.summary.insertions = +insertions || 0;\n result.summary.deletions = +deletions || 0;\n return true;\n }\n return false;\n }),\n new LineParser(ACTION_REGEX, (result, [action, file]) => {\n append(result.files, file);\n append(action === 'create' ? result.created : result.deleted, file);\n }),\n];\n\nconst errorParsers: LineParser[] = [\n new LineParser(/^from\\s(.+)$/i, (result, [remote]) => void (result.remote = remote)),\n new LineParser(/^fatal:\\s(.+)$/, (result, [message]) => void (result.message = message)),\n new LineParser(\n /([a-z0-9]+)\\.\\.([a-z0-9]+)\\s+(\\S+)\\s+->\\s+(\\S+)$/,\n (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => {\n result.branch.local = branchLocal;\n result.hash.local = hashLocal;\n result.branch.remote = branchRemote;\n result.hash.remote = hashRemote;\n }\n ),\n];\n\nexport const parsePullDetail: TaskParser = (stdOut, stdErr) => {\n return parseStringResponse(new PullSummary(), parsers, [stdOut, stdErr]);\n};\n\nexport const parsePullResult: TaskParser = (stdOut, stdErr) => {\n return Object.assign(\n new PullSummary(),\n parsePullDetail(stdOut, stdErr),\n parseRemoteMessages(stdOut, stdErr)\n );\n};\n\nexport function parsePullErrorResult(stdOut: string, stdErr: string) {\n const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]);\n\n return pullError.message && pullError;\n}\n", "import { MergeDetail, MergeResult } from '../../../typings';\nimport { MergeSummaryConflict, MergeSummaryDetail } from '../responses/MergeSummary';\nimport { TaskParser } from '../types';\nimport { LineParser, parseStringResponse } from '../utils';\nimport { parsePullResult } from './parse-pull';\n\nconst parsers: LineParser[] = [\n new LineParser(/^Auto-merging\\s+(.+)$/, (summary, [autoMerge]) => {\n summary.merges.push(autoMerge);\n }),\n new LineParser(/^CONFLICT\\s+\\((.+)\\): Merge conflict in (.+)$/, (summary, [reason, file]) => {\n summary.conflicts.push(new MergeSummaryConflict(reason, file));\n }),\n new LineParser(\n /^CONFLICT\\s+\\((.+\\/delete)\\): (.+) deleted in (.+) and/,\n (summary, [reason, file, deleteRef]) => {\n summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef }));\n }\n ),\n new LineParser(/^CONFLICT\\s+\\((.+)\\):/, (summary, [reason]) => {\n summary.conflicts.push(new MergeSummaryConflict(reason, null));\n }),\n new LineParser(/^Automatic merge failed;\\s+(.+)$/, (summary, [result]) => {\n summary.result = result;\n }),\n];\n\n/**\n * Parse the complete response from `git.merge`\n */\nexport const parseMergeResult: TaskParser = (stdOut, stdErr) => {\n return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr));\n};\n\n/**\n * Parse the merge specific detail (ie: not the content also available in the pull detail) from `git.mnerge`\n * @param stdOut\n */\nexport const parseMergeDetail: TaskParser = (stdOut) => {\n return parseStringResponse(new MergeSummaryDetail(), parsers, stdOut);\n};\n", "import { MergeResult } from '../../../typings';\nimport { GitResponseError } from '../errors/git-response-error';\nimport { parseMergeResult } from '../parsers/parse-merge';\nimport { StringTask } from '../types';\nimport { configurationErrorTask, EmptyTask } from './task';\n\nexport function mergeTask(customArgs: string[]): EmptyTask | StringTask {\n if (!customArgs.length) {\n return configurationErrorTask('Git.merge requires at least one option');\n }\n\n return {\n commands: ['merge', ...customArgs],\n format: 'utf-8',\n parser(stdOut, stdErr): MergeResult {\n const merge = parseMergeResult(stdOut, stdErr);\n if (merge.failed) {\n throw new GitResponseError(merge);\n }\n\n return merge;\n },\n };\n}\n", "import {\n PushDetail,\n PushResult,\n PushResultPushedItem,\n PushResultRemoteMessages,\n} from '../../../typings';\nimport { TaskParser } from '../types';\nimport { LineParser, parseStringResponse } from '../utils';\nimport { parseRemoteMessages } from './parse-remote-messages';\n\nfunction pushResultPushedItem(local: string, remote: string, status: string): PushResultPushedItem {\n const deleted = status.includes('deleted');\n const tag = status.includes('tag') || /^refs\\/tags/.test(local);\n const alreadyUpdated = !status.includes('new');\n\n return {\n deleted,\n tag,\n branch: !tag,\n new: !alreadyUpdated,\n alreadyUpdated,\n local,\n remote,\n };\n}\n\nconst parsers: LineParser[] = [\n new LineParser(/^Pushing to (.+)$/, (result, [repo]) => {\n result.repo = repo;\n }),\n new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => {\n result.ref = {\n ...(result.ref || {}),\n local,\n };\n }),\n new LineParser(/^[=*-]\\s+([^:]+):(\\S+)\\s+\\[(.+)]$/, (result, [local, remote, type]) => {\n result.pushed.push(pushResultPushedItem(local, remote, type));\n }),\n new LineParser(\n /^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,\n (result, [local, remote, remoteName]) => {\n result.branch = {\n ...(result.branch || {}),\n local,\n remote,\n remoteName,\n };\n }\n ),\n new LineParser(\n /^([^:]+):(\\S+)\\s+([a-z0-9]+)\\.\\.([a-z0-9]+)$/,\n (result, [local, remote, from, to]) => {\n result.update = {\n head: {\n local,\n remote,\n },\n hash: {\n from,\n to,\n },\n };\n }\n ),\n];\n\nexport const parsePushResult: TaskParser = (stdOut, stdErr) => {\n const pushDetail = parsePushDetail(stdOut, stdErr);\n const responseDetail = parseRemoteMessages(stdOut, stdErr);\n\n return {\n ...pushDetail,\n ...responseDetail,\n };\n};\n\nexport const parsePushDetail: TaskParser = (stdOut, stdErr) => {\n return parseStringResponse({ pushed: [] }, parsers, [stdOut, stdErr]);\n};\n", "import { PushResult } from '../../../typings';\nimport { parsePushResult as parser } from '../parsers/parse-push';\nimport { StringTask } from '../types';\nimport { append, remove } from '../utils';\n\ntype PushRef = { remote?: string; branch?: string };\n\nexport function pushTagsTask(ref: PushRef = {}, customArgs: string[]): StringTask {\n append(customArgs, '--tags');\n return pushTask(ref, customArgs);\n}\n\nexport function pushTask(ref: PushRef = {}, customArgs: string[]): StringTask {\n const commands = ['push', ...customArgs];\n if (ref.branch) {\n commands.splice(1, 0, ref.branch);\n }\n if (ref.remote) {\n commands.splice(1, 0, ref.remote);\n }\n\n remove(commands, '-v');\n append(commands, '--verbose');\n append(commands, '--porcelain');\n\n return {\n commands,\n format: 'utf-8',\n parser,\n };\n}\n", "import { SimpleGit } from '../../../typings';\nimport { SimpleGitApi } from '../simple-git-api';\nimport { getTrailingOptions, trailingFunctionArgument } from '../utils';\nimport { straightThroughBufferTask, straightThroughStringTask } from './task';\n\nexport default function (): Pick {\n return {\n showBuffer(this: SimpleGitApi) {\n const commands = ['show', ...getTrailingOptions(arguments, 1)];\n if (!commands.includes('--binary')) {\n commands.splice(1, 0, '--binary');\n }\n\n return this._runTask(\n straightThroughBufferTask(commands),\n trailingFunctionArgument(arguments)\n );\n },\n\n show(this: SimpleGitApi) {\n const commands = ['show', ...getTrailingOptions(arguments, 1)];\n return this._runTask(\n straightThroughStringTask(commands),\n trailingFunctionArgument(arguments)\n );\n },\n };\n}\n", "import { FileStatusResult } from '../../../typings';\n\nexport const fromPathRegex = /^(.+) -> (.+)$/;\n\nexport class FileStatusSummary implements FileStatusResult {\n public readonly from: string | undefined;\n\n constructor(\n public path: string,\n public index: string,\n public working_dir: string\n ) {\n if ('R' === index + working_dir) {\n const detail = fromPathRegex.exec(path) || [null, path, path];\n this.from = detail[1] || '';\n this.path = detail[2] || '';\n }\n }\n}\n", "import { StatusResult } from '../../../typings';\nimport { append, NULL } from '../utils';\nimport { FileStatusSummary } from './FileStatusSummary';\n\ntype StatusLineParser = (result: StatusResult, file: string) => void;\n\nexport class StatusSummary implements StatusResult {\n public not_added = [];\n public conflicted = [];\n public created = [];\n public deleted = [];\n public ignored = undefined;\n public modified = [];\n public renamed = [];\n public files = [];\n public staged = [];\n public ahead = 0;\n public behind = 0;\n public current = null;\n public tracking = null;\n public detached = false;\n\n public isClean = () => {\n return !this.files.length;\n };\n}\n\nenum PorcelainFileStatus {\n ADDED = 'A',\n DELETED = 'D',\n MODIFIED = 'M',\n RENAMED = 'R',\n COPIED = 'C',\n UNMERGED = 'U',\n UNTRACKED = '?',\n IGNORED = '!',\n NONE = ' ',\n}\n\nfunction renamedFile(line: string) {\n const [to, from] = line.split(NULL);\n\n return {\n from: from || to,\n to,\n };\n}\n\nfunction parser(\n indexX: PorcelainFileStatus,\n indexY: PorcelainFileStatus,\n handler: StatusLineParser\n): [string, StatusLineParser] {\n return [`${indexX}${indexY}`, handler];\n}\n\nfunction conflicts(indexX: PorcelainFileStatus, ...indexY: PorcelainFileStatus[]) {\n return indexY.map((y) => parser(indexX, y, (result, file) => append(result.conflicted, file)));\n}\n\nconst parsers: Map = new Map([\n parser(PorcelainFileStatus.NONE, PorcelainFileStatus.ADDED, (result, file) =>\n append(result.created, file)\n ),\n parser(PorcelainFileStatus.NONE, PorcelainFileStatus.DELETED, (result, file) =>\n append(result.deleted, file)\n ),\n parser(PorcelainFileStatus.NONE, PorcelainFileStatus.MODIFIED, (result, file) =>\n append(result.modified, file)\n ),\n\n parser(\n PorcelainFileStatus.ADDED,\n PorcelainFileStatus.NONE,\n (result, file) => append(result.created, file) && append(result.staged, file)\n ),\n parser(\n PorcelainFileStatus.ADDED,\n PorcelainFileStatus.MODIFIED,\n (result, file) =>\n append(result.created, file) &&\n append(result.staged, file) &&\n append(result.modified, file)\n ),\n\n parser(\n PorcelainFileStatus.DELETED,\n PorcelainFileStatus.NONE,\n (result, file) => append(result.deleted, file) && append(result.staged, file)\n ),\n\n parser(\n PorcelainFileStatus.MODIFIED,\n PorcelainFileStatus.NONE,\n (result, file) => append(result.modified, file) && append(result.staged, file)\n ),\n parser(\n PorcelainFileStatus.MODIFIED,\n PorcelainFileStatus.MODIFIED,\n (result, file) => append(result.modified, file) && append(result.staged, file)\n ),\n\n parser(PorcelainFileStatus.RENAMED, PorcelainFileStatus.NONE, (result, file) => {\n append(result.renamed, renamedFile(file));\n }),\n parser(PorcelainFileStatus.RENAMED, PorcelainFileStatus.MODIFIED, (result, file) => {\n const renamed = renamedFile(file);\n append(result.renamed, renamed);\n append(result.modified, renamed.to);\n }),\n parser(PorcelainFileStatus.IGNORED, PorcelainFileStatus.IGNORED, (_result, _file) => {\n append((_result.ignored = _result.ignored || []), _file);\n }),\n\n parser(PorcelainFileStatus.UNTRACKED, PorcelainFileStatus.UNTRACKED, (result, file) =>\n append(result.not_added, file)\n ),\n\n ...conflicts(PorcelainFileStatus.ADDED, PorcelainFileStatus.ADDED, PorcelainFileStatus.UNMERGED),\n ...conflicts(\n PorcelainFileStatus.DELETED,\n PorcelainFileStatus.DELETED,\n PorcelainFileStatus.UNMERGED\n ),\n ...conflicts(\n PorcelainFileStatus.UNMERGED,\n PorcelainFileStatus.ADDED,\n PorcelainFileStatus.DELETED,\n PorcelainFileStatus.UNMERGED\n ),\n\n [\n '##',\n (result, line) => {\n const aheadReg = /ahead (\\d+)/;\n const behindReg = /behind (\\d+)/;\n const currentReg = /^(.+?(?=(?:\\.{3}|\\s|$)))/;\n const trackingReg = /\\.{3}(\\S*)/;\n const onEmptyBranchReg = /\\son\\s([\\S]+)$/;\n let regexResult;\n\n regexResult = aheadReg.exec(line);\n result.ahead = (regexResult && +regexResult[1]) || 0;\n\n regexResult = behindReg.exec(line);\n result.behind = (regexResult && +regexResult[1]) || 0;\n\n regexResult = currentReg.exec(line);\n result.current = regexResult && regexResult[1];\n\n regexResult = trackingReg.exec(line);\n result.tracking = regexResult && regexResult[1];\n\n regexResult = onEmptyBranchReg.exec(line);\n result.current = (regexResult && regexResult[1]) || result.current;\n\n result.detached = /\\(no branch\\)/.test(line);\n },\n ],\n]);\n\nexport const parseStatusSummary = function (text: string): StatusResult {\n const lines = text.split(NULL);\n const status = new StatusSummary();\n\n for (let i = 0, l = lines.length; i < l; ) {\n let line = lines[i++].trim();\n\n if (!line) {\n continue;\n }\n\n if (line.charAt(0) === PorcelainFileStatus.RENAMED) {\n line += NULL + (lines[i++] || '');\n }\n\n splitLine(status, line);\n }\n\n return status;\n};\n\nfunction splitLine(result: StatusResult, lineStr: string) {\n const trimmed = lineStr.trim();\n switch (' ') {\n case trimmed.charAt(2):\n return data(trimmed.charAt(0), trimmed.charAt(1), trimmed.substr(3));\n case trimmed.charAt(1):\n return data(PorcelainFileStatus.NONE, trimmed.charAt(0), trimmed.substr(2));\n default:\n return;\n }\n\n function data(index: string, workingDir: string, path: string) {\n const raw = `${index}${workingDir}`;\n const handler = parsers.get(raw);\n\n if (handler) {\n handler(result, path);\n }\n\n if (raw !== '##' && raw !== '!!') {\n result.files.push(new FileStatusSummary(path.replace(/\\0.+$/, ''), index, workingDir));\n }\n }\n}\n", "import { StatusResult } from '../../../typings';\nimport { parseStatusSummary } from '../responses/StatusSummary';\nimport { StringTask } from '../types';\n\nconst ignoredOptions = ['--null', '-z'];\n\nexport function statusTask(customArgs: string[]): StringTask {\n const commands = [\n 'status',\n '--porcelain',\n '-b',\n '-u',\n '--null',\n ...customArgs.filter((arg) => !ignoredOptions.includes(arg)),\n ];\n\n return {\n format: 'utf-8',\n commands,\n parser(text: string) {\n return parseStatusSummary(text);\n },\n };\n}\n", "import type { SimpleGitApi } from '../simple-git-api';\nimport type { SimpleGit } from '../../../typings';\nimport { asNumber, ExitCodes, LineParser, parseStringResponse } from '../utils';\n\nexport interface VersionResult {\n major: number;\n minor: number;\n patch: number | string;\n agent: string;\n installed: boolean;\n}\n\nconst NOT_INSTALLED = 'installed=false';\n\nfunction versionResponse(\n major = 0,\n minor = 0,\n patch: string | number = 0,\n agent = '',\n installed = true\n): VersionResult {\n return Object.defineProperty(\n {\n major,\n minor,\n patch,\n agent,\n installed,\n },\n 'toString',\n {\n value() {\n return `${this.major}.${this.minor}.${this.patch}`;\n },\n configurable: false,\n enumerable: false,\n }\n );\n}\n\nfunction notInstalledResponse() {\n return versionResponse(0, 0, 0, '', false);\n}\n\nexport default function (): Pick {\n return {\n version(this: SimpleGitApi) {\n return this._runTask({\n commands: ['--version'],\n format: 'utf-8',\n parser: versionParser,\n onError(result, error, done, fail) {\n if (result.exitCode === ExitCodes.NOT_FOUND) {\n return done(Buffer.from(NOT_INSTALLED));\n }\n\n fail(error);\n },\n });\n },\n };\n}\n\nconst parsers: LineParser[] = [\n new LineParser(\n /version (\\d+)\\.(\\d+)\\.(\\d+)(?:\\s*\\((.+)\\))?/,\n (result, [major, minor, patch, agent = '']) => {\n Object.assign(\n result,\n versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent)\n );\n }\n ),\n new LineParser(\n /version (\\d+)\\.(\\d+)\\.(\\D+)(.+)?$/,\n (result, [major, minor, patch, agent = '']) => {\n Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent));\n }\n ),\n];\n\nfunction versionParser(stdOut: string) {\n if (stdOut === NOT_INSTALLED) {\n return notInstalledResponse();\n }\n\n return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers, stdOut);\n}\n", "import { SimpleGitBase } from '../../typings';\nimport { taskCallback } from './task-callback';\nimport { changeWorkingDirectoryTask } from './tasks/change-working-directory';\nimport checkout from './tasks/checkout';\nimport commit from './tasks/commit';\nimport config from './tasks/config';\nimport firstCommit from './tasks/first-commit';\nimport grep from './tasks/grep';\nimport { hashObjectTask } from './tasks/hash-object';\nimport { initTask } from './tasks/init';\nimport log from './tasks/log';\nimport { mergeTask } from './tasks/merge';\nimport { pushTask } from './tasks/push';\nimport show from './tasks/show';\nimport { statusTask } from './tasks/status';\nimport { configurationErrorTask, straightThroughStringTask } from './tasks/task';\nimport version from './tasks/version';\nimport { outputHandler, SimpleGitExecutor, SimpleGitTask, SimpleGitTaskCallback } from './types';\nimport {\n asArray,\n filterString,\n filterType,\n getTrailingOptions,\n trailingFunctionArgument,\n} from './utils';\n\nexport class SimpleGitApi implements SimpleGitBase {\n constructor(private _executor: SimpleGitExecutor) {}\n\n protected _runTask(task: SimpleGitTask, then?: SimpleGitTaskCallback) {\n const chain = this._executor.chain();\n const promise = chain.push(task);\n\n if (then) {\n taskCallback(task, promise, then);\n }\n\n return Object.create(this, {\n then: { value: promise.then.bind(promise) },\n catch: { value: promise.catch.bind(promise) },\n _executor: { value: chain },\n });\n }\n\n add(files: string | string[]) {\n return this._runTask(\n straightThroughStringTask(['add', ...asArray(files)]),\n trailingFunctionArgument(arguments)\n );\n }\n\n cwd(directory: string | { path: string; root?: boolean }) {\n const next = trailingFunctionArgument(arguments);\n\n if (typeof directory === 'string') {\n return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next);\n }\n\n if (typeof directory?.path === 'string') {\n return this._runTask(\n changeWorkingDirectoryTask(\n directory.path,\n (directory.root && this._executor) || undefined\n ),\n next\n );\n }\n\n return this._runTask(\n configurationErrorTask('Git.cwd: workingDirectory must be supplied as a string'),\n next\n );\n }\n\n hashObject(path: string, write: boolean | unknown) {\n return this._runTask(\n hashObjectTask(path, write === true),\n trailingFunctionArgument(arguments)\n );\n }\n\n init(bare?: boolean | unknown) {\n return this._runTask(\n initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n }\n\n merge() {\n return this._runTask(\n mergeTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n }\n\n mergeFromTo(remote: string, branch: string) {\n if (!(filterString(remote) && filterString(branch))) {\n return this._runTask(\n configurationErrorTask(\n `Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`\n )\n );\n }\n\n return this._runTask(\n mergeTask([remote, branch, ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments, false)\n );\n }\n\n outputHandler(handler: outputHandler) {\n this._executor.outputHandler = handler;\n return this;\n }\n\n push() {\n const task = pushTask(\n {\n remote: filterType(arguments[0], filterString),\n branch: filterType(arguments[1], filterString),\n },\n getTrailingOptions(arguments)\n );\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n }\n\n stash() {\n return this._runTask(\n straightThroughStringTask(['stash', ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments)\n );\n }\n\n status() {\n return this._runTask(\n statusTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n }\n}\n\nObject.assign(\n SimpleGitApi.prototype,\n checkout(),\n commit(),\n config(),\n firstCommit(),\n grep(),\n log(),\n show(),\n version()\n);\n", "import { append, remove } from '../utils';\nimport { createDeferred, DeferredPromise } from '@kwsites/promise-deferred';\nimport { createLogger } from '../git-logger';\n\ntype ScheduleCompleteCallback = () => void;\ntype ScheduledTask = Pick, 'promise' | 'done'> & {\n id: number;\n};\n\nconst createScheduledTask: () => ScheduledTask = (() => {\n let id = 0;\n return () => {\n id++;\n const { promise, done } = createDeferred();\n\n return {\n promise,\n done,\n id,\n };\n };\n})();\n\nexport class Scheduler {\n private logger = createLogger('', 'scheduler');\n private pending: ScheduledTask[] = [];\n private running: ScheduledTask[] = [];\n\n constructor(private concurrency = 2) {\n this.logger(`Constructed, concurrency=%s`, concurrency);\n }\n\n private schedule() {\n if (!this.pending.length || this.running.length >= this.concurrency) {\n this.logger(\n `Schedule attempt ignored, pending=%s running=%s concurrency=%s`,\n this.pending.length,\n this.running.length,\n this.concurrency\n );\n return;\n }\n\n const task = append(this.running, this.pending.shift()!);\n this.logger(`Attempting id=%s`, task.id);\n task.done(() => {\n this.logger(`Completing id=`, task.id);\n remove(this.running, task);\n this.schedule();\n });\n }\n\n next(): Promise {\n const { promise, id } = append(this.pending, createScheduledTask());\n this.logger(`Scheduling id=%s`, id);\n\n this.schedule();\n\n return promise;\n }\n}\n", "import { straightThroughStringTask } from './task';\nimport { OptionFlags, Options, StringTask } from '../types';\n\nexport type ApplyOptions = Options &\n OptionFlags<\n | '--stat'\n | '--numstat'\n | '--summary'\n | '--check'\n | '--index'\n | '--intent-to-add'\n | '--3way'\n | '--apply'\n | '--no-add'\n | '-R'\n | '--reverse'\n | '--allow-binary-replacement'\n | '--binary'\n | '--reject'\n | '-z'\n | '--inaccurate-eof'\n | '--recount'\n | '--cached'\n | '--ignore-space-change'\n | '--ignore-whitespace'\n | '--verbose'\n | '--unsafe-paths'\n > &\n OptionFlags<'--whitespace', 'nowarn' | 'warn' | 'fix' | 'error' | 'error-all'> &\n OptionFlags<'--build-fake-ancestor' | '--exclude' | '--include' | '--directory', string> &\n OptionFlags<'-p' | '-C', number>;\n\nexport function applyPatchTask(patches: string[], customArgs: string[]): StringTask {\n return straightThroughStringTask(['apply', ...customArgs, ...patches]);\n}\n", "import {\n BranchMultiDeleteResult,\n BranchSingleDeleteFailure,\n BranchSingleDeleteResult,\n BranchSingleDeleteSuccess,\n} from '../../../typings';\n\nexport class BranchDeletionBatch implements BranchMultiDeleteResult {\n all: BranchSingleDeleteResult[] = [];\n branches: { [branchName: string]: BranchSingleDeleteResult } = {};\n errors: BranchSingleDeleteResult[] = [];\n\n get success(): boolean {\n return !this.errors.length;\n }\n}\n\nexport function branchDeletionSuccess(branch: string, hash: string): BranchSingleDeleteSuccess {\n return {\n branch,\n hash,\n success: true,\n };\n}\n\nexport function branchDeletionFailure(branch: string): BranchSingleDeleteFailure {\n return {\n branch,\n hash: null,\n success: false,\n };\n}\n\nexport function isSingleBranchDeleteFailure(\n test: BranchSingleDeleteResult\n): test is BranchSingleDeleteSuccess {\n return test.success;\n}\n", "import { BranchMultiDeleteResult } from '../../../typings';\nimport {\n BranchDeletionBatch,\n branchDeletionFailure,\n branchDeletionSuccess,\n} from '../responses/BranchDeleteSummary';\nimport { TaskParser } from '../types';\nimport { ExitCodes, LineParser, parseStringResponse } from '../utils';\n\nconst deleteSuccessRegex = /(\\S+)\\s+\\(\\S+\\s([^)]+)\\)/;\nconst deleteErrorRegex = /^error[^']+'([^']+)'/m;\n\nconst parsers: LineParser[] = [\n new LineParser(deleteSuccessRegex, (result, [branch, hash]) => {\n const deletion = branchDeletionSuccess(branch, hash);\n\n result.all.push(deletion);\n result.branches[branch] = deletion;\n }),\n new LineParser(deleteErrorRegex, (result, [branch]) => {\n const deletion = branchDeletionFailure(branch);\n\n result.errors.push(deletion);\n result.all.push(deletion);\n result.branches[branch] = deletion;\n }),\n];\n\nexport const parseBranchDeletions: TaskParser = (\n stdOut,\n stdErr\n) => {\n return parseStringResponse(new BranchDeletionBatch(), parsers, [stdOut, stdErr]);\n};\n\nexport function hasBranchDeletionError(data: string, processExitCode: ExitCodes): boolean {\n return processExitCode === ExitCodes.ERROR && deleteErrorRegex.test(data);\n}\n", "import type { BranchSummary, BranchSummaryBranch } from '../../../typings';\n\nexport enum BranchStatusIdentifier {\n CURRENT = '*',\n LINKED = '+',\n}\n\nexport class BranchSummaryResult implements BranchSummary {\n public all: string[] = [];\n public branches: { [p: string]: BranchSummaryBranch } = {};\n public current: string = '';\n public detached: boolean = false;\n\n push(\n status: BranchStatusIdentifier | unknown,\n detached: boolean,\n name: string,\n commit: string,\n label: string\n ) {\n if (status === BranchStatusIdentifier.CURRENT) {\n this.detached = detached;\n this.current = name;\n }\n\n this.all.push(name);\n this.branches[name] = {\n current: status === BranchStatusIdentifier.CURRENT,\n linkedWorkTree: status === BranchStatusIdentifier.LINKED,\n name,\n commit,\n label,\n };\n }\n}\n", "import type { BranchSummary } from '../../../typings';\nimport { BranchSummaryResult } from '../responses/BranchSummary';\nimport { LineParser, parseStringResponse } from '../utils';\n\nconst parsers: LineParser[] = [\n new LineParser(\n /^([*+]\\s)?\\((?:HEAD )?detached (?:from|at) (\\S+)\\)\\s+([a-z0-9]+)\\s(.*)$/,\n (result, [current, name, commit, label]) => {\n result.push(branchStatus(current), true, name, commit, label);\n }\n ),\n new LineParser(\n /^([*+]\\s)?(\\S+)\\s+([a-z0-9]+)\\s?(.*)$/s,\n (result, [current, name, commit, label]) => {\n result.push(branchStatus(current), false, name, commit, label);\n }\n ),\n];\n\nfunction branchStatus(input?: string) {\n return input ? input.charAt(0) : '';\n}\n\nexport function parseBranchSummary(stdOut: string): BranchSummary {\n return parseStringResponse(new BranchSummaryResult(), parsers, stdOut);\n}\n", "import { BranchMultiDeleteResult, BranchSingleDeleteResult, BranchSummary } from '../../../typings';\nimport { StringTask } from '../types';\nimport { GitResponseError } from '../errors/git-response-error';\nimport { hasBranchDeletionError, parseBranchDeletions } from '../parsers/parse-branch-delete';\nimport { parseBranchSummary } from '../parsers/parse-branch';\nimport { bufferToString } from '../utils';\n\nexport function containsDeleteBranchCommand(commands: string[]) {\n const deleteCommands = ['-d', '-D', '--delete'];\n return commands.some((command) => deleteCommands.includes(command));\n}\n\nexport function branchTask(\n customArgs: string[]\n): StringTask {\n const isDelete = containsDeleteBranchCommand(customArgs);\n const commands = ['branch', ...customArgs];\n\n if (commands.length === 1) {\n commands.push('-a');\n }\n\n if (!commands.includes('-v')) {\n commands.splice(1, 0, '-v');\n }\n\n return {\n format: 'utf-8',\n commands,\n parser(stdOut, stdErr) {\n if (isDelete) {\n return parseBranchDeletions(stdOut, stdErr).all[0];\n }\n\n return parseBranchSummary(stdOut);\n },\n };\n}\n\nexport function branchLocalTask(): StringTask {\n const parser = parseBranchSummary;\n\n return {\n format: 'utf-8',\n commands: ['branch', '-v'],\n parser,\n };\n}\n\nexport function deleteBranchesTask(\n branches: string[],\n forceDelete = false\n): StringTask {\n return {\n format: 'utf-8',\n commands: ['branch', '-v', forceDelete ? '-D' : '-d', ...branches],\n parser(stdOut, stdErr) {\n return parseBranchDeletions(stdOut, stdErr);\n },\n onError({ exitCode, stdOut }, error, done, fail) {\n if (!hasBranchDeletionError(String(error), exitCode)) {\n return fail(error);\n }\n\n done(stdOut);\n },\n };\n}\n\nexport function deleteBranchTask(\n branch: string,\n forceDelete = false\n): StringTask {\n const task: StringTask = {\n format: 'utf-8',\n commands: ['branch', '-v', forceDelete ? '-D' : '-d', branch],\n parser(stdOut, stdErr) {\n return parseBranchDeletions(stdOut, stdErr).branches[branch]!;\n },\n onError({ exitCode, stdErr, stdOut }, error, _, fail) {\n if (!hasBranchDeletionError(String(error), exitCode)) {\n return fail(error);\n }\n\n throw new GitResponseError(\n task.parser(bufferToString(stdOut), bufferToString(stdErr)),\n String(error)\n );\n },\n };\n\n return task;\n}\n", "/**\n * Parser for the `check-ignore` command - returns each file as a string array\n */\nexport const parseCheckIgnore = (text: string): string[] => {\n return text\n .split(/\\n/g)\n .map((line) => line.trim())\n .filter((file) => !!file);\n};\n", "import { StringTask } from '../types';\nimport { parseCheckIgnore } from '../responses/CheckIgnore';\n\nexport function checkIgnoreTask(paths: string[]): StringTask {\n return {\n commands: ['check-ignore', ...paths],\n format: 'utf-8',\n parser: parseCheckIgnore,\n };\n}\n", "import { configurationErrorTask, EmptyTask, straightThroughStringTask } from './task';\nimport { OptionFlags, Options, StringTask } from '../types';\nimport { append, filterString } from '../utils';\n\nexport type CloneOptions = Options &\n OptionFlags<\n | '--bare'\n | '--dissociate'\n | '--mirror'\n | '--no-checkout'\n | '--no-remote-submodules'\n | '--no-shallow-submodules'\n | '--no-single-branch'\n | '--no-tags'\n | '--remote-submodules'\n | '--single-branch'\n | '--shallow-submodules'\n | '--verbose'\n > &\n OptionFlags<'--depth' | '-j' | '--jobs', number> &\n OptionFlags<\n | '--branch'\n | '--origin'\n | '--recurse-submodules'\n | '--separate-git-dir'\n | '--shallow-exclude'\n | '--shallow-since'\n | '--template',\n string\n >;\n\nfunction disallowedCommand(command: string) {\n return /^--upload-pack(=|$)/.test(command);\n}\n\nexport function cloneTask(\n repo: string | undefined,\n directory: string | undefined,\n customArgs: string[]\n): StringTask | EmptyTask {\n const commands = ['clone', ...customArgs];\n\n filterString(repo) && commands.push(repo);\n filterString(directory) && commands.push(directory);\n\n const banned = commands.find(disallowedCommand);\n if (banned) {\n return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport function cloneMirrorTask(\n repo: string | undefined,\n directory: string | undefined,\n customArgs: string[]\n) {\n append(customArgs, '--mirror');\n\n return cloneTask(repo, directory, customArgs);\n}\n", "import { FetchResult } from '../../../typings';\nimport { LineParser, parseStringResponse } from '../utils';\n\nconst parsers: LineParser[] = [\n new LineParser(/From (.+)$/, (result, [remote]) => {\n result.remote = remote;\n }),\n new LineParser(/\\* \\[new branch]\\s+(\\S+)\\s*-> (.+)$/, (result, [name, tracking]) => {\n result.branches.push({\n name,\n tracking,\n });\n }),\n new LineParser(/\\* \\[new tag]\\s+(\\S+)\\s*-> (.+)$/, (result, [name, tracking]) => {\n result.tags.push({\n name,\n tracking,\n });\n }),\n new LineParser(/- \\[deleted]\\s+\\S+\\s*-> (.+)$/, (result, [tracking]) => {\n result.deleted.push({\n tracking,\n });\n }),\n new LineParser(\n /\\s*([^.]+)\\.\\.(\\S+)\\s+(\\S+)\\s*-> (.+)$/,\n (result, [from, to, name, tracking]) => {\n result.updated.push({\n name,\n tracking,\n to,\n from,\n });\n }\n ),\n];\n\nexport function parseFetchResult(stdOut: string, stdErr: string): FetchResult {\n const result: FetchResult = {\n raw: stdOut,\n remote: null,\n branches: [],\n tags: [],\n updated: [],\n deleted: [],\n };\n return parseStringResponse(result, parsers, [stdOut, stdErr]);\n}\n", "import { FetchResult } from '../../../typings';\nimport { parseFetchResult } from '../parsers/parse-fetch';\nimport { StringTask } from '../types';\n\nimport { configurationErrorTask, EmptyTask } from './task';\n\nfunction disallowedCommand(command: string) {\n return /^--upload-pack(=|$)/.test(command);\n}\n\nexport function fetchTask(\n remote: string,\n branch: string,\n customArgs: string[]\n): StringTask | EmptyTask {\n const commands = ['fetch', ...customArgs];\n if (remote && branch) {\n commands.push(remote, branch);\n }\n\n const banned = commands.find(disallowedCommand);\n if (banned) {\n return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser: parseFetchResult,\n };\n}\n", "import { MoveResult } from '../../../typings';\nimport { LineParser, parseStringResponse } from '../utils';\n\nconst parsers: LineParser[] = [\n new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => {\n result.moves.push({ from, to });\n }),\n];\n\nexport function parseMoveResult(stdOut: string): MoveResult {\n return parseStringResponse({ moves: [] }, parsers, stdOut);\n}\n", "import { MoveResult } from '../../../typings';\nimport { parseMoveResult } from '../parsers/parse-move';\nimport { StringTask } from '../types';\nimport { asArray } from '../utils';\n\nexport function moveTask(from: string | string[], to: string): StringTask {\n return {\n commands: ['mv', '-v', ...asArray(from), to],\n format: 'utf-8',\n parser: parseMoveResult,\n };\n}\n", "import { PullResult } from '../../../typings';\nimport { GitResponseError } from '../errors/git-response-error';\nimport { parsePullErrorResult, parsePullResult } from '../parsers/parse-pull';\nimport { Maybe, StringTask } from '../types';\nimport { bufferToString } from '../utils';\n\nexport function pullTask(\n remote: Maybe,\n branch: Maybe,\n customArgs: string[]\n): StringTask {\n const commands: string[] = ['pull', ...customArgs];\n if (remote && branch) {\n commands.splice(1, 0, remote, branch);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser(stdOut, stdErr): PullResult {\n return parsePullResult(stdOut, stdErr);\n },\n onError(result, _error, _done, fail) {\n const pullError = parsePullErrorResult(\n bufferToString(result.stdOut),\n bufferToString(result.stdErr)\n );\n if (pullError) {\n return fail(new GitResponseError(pullError));\n }\n\n fail(_error);\n },\n };\n}\n", "import { forEachLineWithContent } from '../utils';\n\nexport interface RemoteWithoutRefs {\n name: string;\n}\n\nexport interface RemoteWithRefs extends RemoteWithoutRefs {\n refs: {\n fetch: string;\n push: string;\n };\n}\n\nexport function parseGetRemotes(text: string): RemoteWithoutRefs[] {\n const remotes: { [name: string]: RemoteWithoutRefs } = {};\n\n forEach(text, ([name]) => (remotes[name] = { name }));\n\n return Object.values(remotes);\n}\n\nexport function parseGetRemotesVerbose(text: string): RemoteWithRefs[] {\n const remotes: { [name: string]: RemoteWithRefs } = {};\n\n forEach(text, ([name, url, purpose]) => {\n if (!remotes.hasOwnProperty(name)) {\n remotes[name] = {\n name: name,\n refs: { fetch: '', push: '' },\n };\n }\n\n if (purpose && url) {\n remotes[name].refs[purpose.replace(/[^a-z]/g, '') as keyof RemoteWithRefs['refs']] = url;\n }\n });\n\n return Object.values(remotes);\n}\n\nfunction forEach(text: string, handler: (line: string[]) => void) {\n forEachLineWithContent(text, (line) => handler(line.split(/\\s+/)));\n}\n", "import { parseGetRemotes, parseGetRemotesVerbose } from '../responses/GetRemoteSummary';\nimport { StringTask } from '../types';\nimport { straightThroughStringTask } from './task';\n\nexport function addRemoteTask(\n remoteName: string,\n remoteRepo: string,\n customArgs: string[]\n): StringTask {\n return straightThroughStringTask(['remote', 'add', ...customArgs, remoteName, remoteRepo]);\n}\n\nexport function getRemotesTask(verbose: boolean): StringTask {\n const commands = ['remote'];\n if (verbose) {\n commands.push('-v');\n }\n\n return {\n commands,\n format: 'utf-8',\n parser: verbose ? parseGetRemotesVerbose : parseGetRemotes,\n };\n}\n\nexport function listRemotesTask(customArgs: string[]): StringTask {\n const commands = [...customArgs];\n if (commands[0] !== 'ls-remote') {\n commands.unshift('ls-remote');\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport function remoteTask(customArgs: string[]): StringTask {\n const commands = [...customArgs];\n if (commands[0] !== 'remote') {\n commands.unshift('remote');\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport function removeRemoteTask(remoteName: string) {\n return straightThroughStringTask(['remote', 'remove', remoteName]);\n}\n", "import { LogOptions, LogResult } from '../../../typings';\nimport { logFormatFromCommand } from '../args/log-format';\nimport { createListLogSummaryParser } from '../parsers/parse-list-log-summary';\nimport type { StringTask } from '../types';\nimport { validateLogFormatConfig } from './diff';\nimport { parseLogOptions } from './log';\nimport type { EmptyTask } from './task';\n\nexport function stashListTask(\n opt: LogOptions = {},\n customArgs: string[]\n): EmptyTask | StringTask {\n const options = parseLogOptions(opt);\n const commands = ['stash', 'list', ...options.commands, ...customArgs];\n const parser = createListLogSummaryParser(\n options.splitter,\n options.fields,\n logFormatFromCommand(commands)\n );\n\n return (\n validateLogFormatConfig(commands) || {\n commands,\n format: 'utf-8',\n parser,\n }\n );\n}\n", "import { StringTask } from '../types';\nimport { straightThroughStringTask } from './task';\n\nexport function addSubModuleTask(repo: string, path: string): StringTask {\n return subModuleTask(['add', repo, path]);\n}\n\nexport function initSubModuleTask(customArgs: string[]): StringTask {\n return subModuleTask(['init', ...customArgs]);\n}\n\nexport function subModuleTask(customArgs: string[]): StringTask {\n const commands = [...customArgs];\n if (commands[0] !== 'submodule') {\n commands.unshift('submodule');\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport function updateSubModuleTask(customArgs: string[]): StringTask {\n return subModuleTask(['update', ...customArgs]);\n}\n", "import { TagResult } from '../../../typings';\n\nexport class TagList implements TagResult {\n constructor(\n public readonly all: string[],\n public readonly latest: string | undefined\n ) {}\n}\n\nexport const parseTagList = function (data: string, customSort = false) {\n const tags = data.split('\\n').map(trimmed).filter(Boolean);\n\n if (!customSort) {\n tags.sort(function (tagA, tagB) {\n const partsA = tagA.split('.');\n const partsB = tagB.split('.');\n\n if (partsA.length === 1 || partsB.length === 1) {\n return singleSorted(toNumber(partsA[0]), toNumber(partsB[0]));\n }\n\n for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) {\n const diff = sorted(toNumber(partsA[i]), toNumber(partsB[i]));\n\n if (diff) {\n return diff;\n }\n }\n\n return 0;\n });\n }\n\n const latest = customSort ? tags[0] : [...tags].reverse().find((tag) => tag.indexOf('.') >= 0);\n\n return new TagList(tags, latest);\n};\n\nfunction singleSorted(a: number, b: number): number {\n const aIsNum = isNaN(a);\n const bIsNum = isNaN(b);\n\n if (aIsNum !== bIsNum) {\n return aIsNum ? 1 : -1;\n }\n\n return aIsNum ? sorted(a, b) : 0;\n}\n\nfunction sorted(a: number, b: number) {\n return a === b ? 0 : a > b ? 1 : -1;\n}\n\nfunction trimmed(input: string) {\n return input.trim();\n}\n\nfunction toNumber(input: string | undefined) {\n if (typeof input === 'string') {\n return parseInt(input.replace(/^\\D+/g, ''), 10) || 0;\n }\n\n return 0;\n}\n", "import { TagResult } from '../../../typings';\nimport { parseTagList } from '../responses/TagList';\nimport { StringTask } from '../types';\n\n/**\n * Task used by `git.tags`\n */\nexport function tagListTask(customArgs: string[] = []): StringTask {\n const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option));\n\n return {\n format: 'utf-8',\n commands: ['tag', '-l', ...customArgs],\n parser(text: string) {\n return parseTagList(text, hasCustomSort);\n },\n };\n}\n\n/**\n * Task used by `git.addTag`\n */\nexport function addTagTask(name: string): StringTask<{ name: string }> {\n return {\n format: 'utf-8',\n commands: ['tag', name],\n parser() {\n return { name };\n },\n };\n}\n\n/**\n * Task used by `git.addTag`\n */\nexport function addAnnotatedTagTask(\n name: string,\n tagMessage: string\n): StringTask<{ name: string }> {\n return {\n format: 'utf-8',\n commands: ['tag', '-a', '-m', tagMessage, name],\n parser() {\n return { name };\n },\n };\n}\n", "const { GitExecutor } = require('./lib/runners/git-executor');\nconst { SimpleGitApi } = require('./lib/simple-git-api');\n\nconst { Scheduler } = require('./lib/runners/scheduler');\nconst { configurationErrorTask } = require('./lib/tasks/task');\nconst {\n asArray,\n filterArray,\n filterPrimitives,\n filterString,\n filterStringOrStringArray,\n filterType,\n getTrailingOptions,\n trailingFunctionArgument,\n trailingOptionsArgument,\n} = require('./lib/utils');\nconst { applyPatchTask } = require('./lib/tasks/apply-patch');\nconst {\n branchTask,\n branchLocalTask,\n deleteBranchesTask,\n deleteBranchTask,\n} = require('./lib/tasks/branch');\nconst { checkIgnoreTask } = require('./lib/tasks/check-ignore');\nconst { checkIsRepoTask } = require('./lib/tasks/check-is-repo');\nconst { cloneTask, cloneMirrorTask } = require('./lib/tasks/clone');\nconst { cleanWithOptionsTask, isCleanOptionsArray } = require('./lib/tasks/clean');\nconst { diffSummaryTask } = require('./lib/tasks/diff');\nconst { fetchTask } = require('./lib/tasks/fetch');\nconst { moveTask } = require('./lib/tasks/move');\nconst { pullTask } = require('./lib/tasks/pull');\nconst { pushTagsTask } = require('./lib/tasks/push');\nconst {\n addRemoteTask,\n getRemotesTask,\n listRemotesTask,\n remoteTask,\n removeRemoteTask,\n} = require('./lib/tasks/remote');\nconst { getResetMode, resetTask } = require('./lib/tasks/reset');\nconst { stashListTask } = require('./lib/tasks/stash-list');\nconst {\n addSubModuleTask,\n initSubModuleTask,\n subModuleTask,\n updateSubModuleTask,\n} = require('./lib/tasks/sub-module');\nconst { addAnnotatedTagTask, addTagTask, tagListTask } = require('./lib/tasks/tag');\nconst { straightThroughBufferTask, straightThroughStringTask } = require('./lib/tasks/task');\n\nfunction Git(options, plugins) {\n this._plugins = plugins;\n this._executor = new GitExecutor(\n options.baseDir,\n new Scheduler(options.maxConcurrentProcesses),\n plugins\n );\n\n this._trimmed = options.trimmed;\n}\n\n(Git.prototype = Object.create(SimpleGitApi.prototype)).constructor = Git;\n\n/**\n * Sets the path to a custom git binary, should either be `git` when there is an installation of git available on\n * the system path, or a fully qualified path to the executable.\n */\nGit.prototype.customBinary = function (command) {\n this._plugins.reconfigure('binary', command);\n return this;\n};\n\n/**\n * Sets an environment variable for the spawned child process, either supply both a name and value as strings or\n * a single object to entirely replace the current environment variables.\n *\n * @param {string|Object} name\n * @param {string} [value]\n * @returns {Git}\n */\nGit.prototype.env = function (name, value) {\n if (arguments.length === 1 && typeof name === 'object') {\n this._executor.env = name;\n } else {\n (this._executor.env = this._executor.env || {})[name] = value;\n }\n\n return this;\n};\n\n/**\n * List the stash(s) of the local repo\n */\nGit.prototype.stashList = function (options) {\n return this._runTask(\n stashListTask(\n trailingOptionsArgument(arguments) || {},\n (filterArray(options) && options) || []\n ),\n trailingFunctionArgument(arguments)\n );\n};\n\nfunction createCloneTask(api, task, repoPath, localPath) {\n if (typeof repoPath !== 'string') {\n return configurationErrorTask(`git.${api}() requires a string 'repoPath'`);\n }\n\n return task(repoPath, filterType(localPath, filterString), getTrailingOptions(arguments));\n}\n\n/**\n * Clone a git repo\n */\nGit.prototype.clone = function () {\n return this._runTask(\n createCloneTask('clone', cloneTask, ...arguments),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Mirror a git repo\n */\nGit.prototype.mirror = function () {\n return this._runTask(\n createCloneTask('mirror', cloneMirrorTask, ...arguments),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Moves one or more files to a new destination.\n *\n * @see https://git-scm.com/docs/git-mv\n *\n * @param {string|string[]} from\n * @param {string} to\n */\nGit.prototype.mv = function (from, to) {\n return this._runTask(moveTask(from, to), trailingFunctionArgument(arguments));\n};\n\n/**\n * Internally uses pull and tags to get the list of tags then checks out the latest tag.\n *\n * @param {Function} [then]\n */\nGit.prototype.checkoutLatestTag = function (then) {\n var git = this;\n return this.pull(function () {\n git.tags(function (err, tags) {\n git.checkout(tags.latest, then);\n });\n });\n};\n\n/**\n * Pull the updated contents of the current repo\n */\nGit.prototype.pull = function (remote, branch, options, then) {\n return this._runTask(\n pullTask(\n filterType(remote, filterString),\n filterType(branch, filterString),\n getTrailingOptions(arguments)\n ),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Fetch the updated contents of the current repo.\n *\n * @example\n * .fetch('upstream', 'master') // fetches from master on remote named upstream\n * .fetch(function () {}) // runs fetch against default remote and branch and calls function\n *\n * @param {string} [remote]\n * @param {string} [branch]\n */\nGit.prototype.fetch = function (remote, branch) {\n return this._runTask(\n fetchTask(\n filterType(remote, filterString),\n filterType(branch, filterString),\n getTrailingOptions(arguments)\n ),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Disables/enables the use of the console for printing warnings and errors, by default messages are not shown in\n * a production environment.\n *\n * @param {boolean} silence\n * @returns {Git}\n */\nGit.prototype.silent = function (silence) {\n console.warn(\n 'simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3'\n );\n return this;\n};\n\n/**\n * List all tags. When using git 2.7.0 or above, include an options object with `\"--sort\": \"property-name\"` to\n * sort the tags by that property instead of using the default semantic versioning sort.\n *\n * Note, supplying this option when it is not supported by your Git version will cause the operation to fail.\n *\n * @param {Object} [options]\n * @param {Function} [then]\n */\nGit.prototype.tags = function (options, then) {\n return this._runTask(\n tagListTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Rebases the current working copy. Options can be supplied either as an array of string parameters\n * to be sent to the `git rebase` command, or a standard options object.\n */\nGit.prototype.rebase = function () {\n return this._runTask(\n straightThroughStringTask(['rebase', ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Reset a repo\n */\nGit.prototype.reset = function (mode) {\n return this._runTask(\n resetTask(getResetMode(mode), getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Revert one or more commits in the local working copy\n */\nGit.prototype.revert = function (commit) {\n const next = trailingFunctionArgument(arguments);\n\n if (typeof commit !== 'string') {\n return this._runTask(configurationErrorTask('Commit must be a string'), next);\n }\n\n return this._runTask(\n straightThroughStringTask(['revert', ...getTrailingOptions(arguments, 0, true), commit]),\n next\n );\n};\n\n/**\n * Add a lightweight tag to the head of the current branch\n */\nGit.prototype.addTag = function (name) {\n const task =\n typeof name === 'string'\n ? addTagTask(name)\n : configurationErrorTask('Git.addTag requires a tag name');\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n};\n\n/**\n * Add an annotated tag to the head of the current branch\n */\nGit.prototype.addAnnotatedTag = function (tagName, tagMessage) {\n return this._runTask(\n addAnnotatedTagTask(tagName, tagMessage),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Delete a local branch\n */\nGit.prototype.deleteLocalBranch = function (branchName, forceDelete, then) {\n return this._runTask(\n deleteBranchTask(branchName, typeof forceDelete === 'boolean' ? forceDelete : false),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Delete one or more local branches\n */\nGit.prototype.deleteLocalBranches = function (branchNames, forceDelete, then) {\n return this._runTask(\n deleteBranchesTask(branchNames, typeof forceDelete === 'boolean' ? forceDelete : false),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * List all branches\n *\n * @param {Object | string[]} [options]\n * @param {Function} [then]\n */\nGit.prototype.branch = function (options, then) {\n return this._runTask(\n branchTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Return list of local branches\n *\n * @param {Function} [then]\n */\nGit.prototype.branchLocal = function (then) {\n return this._runTask(branchLocalTask(), trailingFunctionArgument(arguments));\n};\n\n/**\n * Executes any command against the git binary.\n */\nGit.prototype.raw = function (commands) {\n const createRestCommands = !Array.isArray(commands);\n const command = [].slice.call(createRestCommands ? arguments : commands, 0);\n\n for (let i = 0; i < command.length && createRestCommands; i++) {\n if (!filterPrimitives(command[i])) {\n command.splice(i, command.length - i);\n break;\n }\n }\n\n command.push(...getTrailingOptions(arguments, 0, true));\n\n var next = trailingFunctionArgument(arguments);\n\n if (!command.length) {\n return this._runTask(\n configurationErrorTask('Raw: must supply one or more command to execute'),\n next\n );\n }\n\n return this._runTask(straightThroughStringTask(command, this._trimmed), next);\n};\n\nGit.prototype.submoduleAdd = function (repo, path, then) {\n return this._runTask(addSubModuleTask(repo, path), trailingFunctionArgument(arguments));\n};\n\nGit.prototype.submoduleUpdate = function (args, then) {\n return this._runTask(\n updateSubModuleTask(getTrailingOptions(arguments, true)),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.submoduleInit = function (args, then) {\n return this._runTask(\n initSubModuleTask(getTrailingOptions(arguments, true)),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.subModule = function (options, then) {\n return this._runTask(\n subModuleTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.listRemote = function () {\n return this._runTask(\n listRemotesTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Adds a remote to the list of remotes.\n */\nGit.prototype.addRemote = function (remoteName, remoteRepo, then) {\n return this._runTask(\n addRemoteTask(remoteName, remoteRepo, getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Removes an entry by name from the list of remotes.\n */\nGit.prototype.removeRemote = function (remoteName, then) {\n return this._runTask(removeRemoteTask(remoteName), trailingFunctionArgument(arguments));\n};\n\n/**\n * Gets the currently available remotes, setting the optional verbose argument to true includes additional\n * detail on the remotes themselves.\n */\nGit.prototype.getRemotes = function (verbose, then) {\n return this._runTask(getRemotesTask(verbose === true), trailingFunctionArgument(arguments));\n};\n\n/**\n * Call any `git remote` function with arguments passed as an array of strings.\n *\n * @param {string[]} options\n * @param {Function} [then]\n */\nGit.prototype.remote = function (options, then) {\n return this._runTask(\n remoteTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Call any `git tag` function with arguments passed as an array of strings.\n *\n * @param {string[]} options\n * @param {Function} [then]\n */\nGit.prototype.tag = function (options, then) {\n const command = getTrailingOptions(arguments);\n\n if (command[0] !== 'tag') {\n command.unshift('tag');\n }\n\n return this._runTask(straightThroughStringTask(command), trailingFunctionArgument(arguments));\n};\n\n/**\n * Updates repository server info\n *\n * @param {Function} [then]\n */\nGit.prototype.updateServerInfo = function (then) {\n return this._runTask(\n straightThroughStringTask(['update-server-info']),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Pushes the current tag changes to a remote which can be either a URL or named remote. When not specified uses the\n * default configured remote spec.\n *\n * @param {string} [remote]\n * @param {Function} [then]\n */\nGit.prototype.pushTags = function (remote, then) {\n const task = pushTagsTask(\n { remote: filterType(remote, filterString) },\n getTrailingOptions(arguments)\n );\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n};\n\n/**\n * Removes the named files from source control.\n */\nGit.prototype.rm = function (files) {\n return this._runTask(\n straightThroughStringTask(['rm', '-f', ...asArray(files)]),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Removes the named files from source control but keeps them on disk rather than deleting them entirely. To\n * completely remove the files, use `rm`.\n *\n * @param {string|string[]} files\n */\nGit.prototype.rmKeepLocal = function (files) {\n return this._runTask(\n straightThroughStringTask(['rm', '--cached', ...asArray(files)]),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Returns a list of objects in a tree based on commit hash. Passing in an object hash returns the object's content,\n * size, and type.\n *\n * Passing \"-p\" will instruct cat-file to determine the object type, and display its formatted contents.\n *\n * @param {string[]} [options]\n * @param {Function} [then]\n */\nGit.prototype.catFile = function (options, then) {\n return this._catFile('utf-8', arguments);\n};\n\nGit.prototype.binaryCatFile = function () {\n return this._catFile('buffer', arguments);\n};\n\nGit.prototype._catFile = function (format, args) {\n var handler = trailingFunctionArgument(args);\n var command = ['cat-file'];\n var options = args[0];\n\n if (typeof options === 'string') {\n return this._runTask(\n configurationErrorTask('Git.catFile: options must be supplied as an array of strings'),\n handler\n );\n }\n\n if (Array.isArray(options)) {\n command.push.apply(command, options);\n }\n\n const task =\n format === 'buffer' ? straightThroughBufferTask(command) : straightThroughStringTask(command);\n\n return this._runTask(task, handler);\n};\n\nGit.prototype.diff = function (options, then) {\n const task = filterString(options)\n ? configurationErrorTask(\n 'git.diff: supplying options as a single string is no longer supported, switch to an array of strings'\n )\n : straightThroughStringTask(['diff', ...getTrailingOptions(arguments)]);\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n};\n\nGit.prototype.diffSummary = function () {\n return this._runTask(\n diffSummaryTask(getTrailingOptions(arguments, 1)),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.applyPatch = function (patches) {\n const task = !filterStringOrStringArray(patches)\n ? configurationErrorTask(\n `git.applyPatch requires one or more string patches as the first argument`\n )\n : applyPatchTask(asArray(patches), getTrailingOptions([].slice.call(arguments, 1)));\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n};\n\nGit.prototype.revparse = function () {\n const commands = ['rev-parse', ...getTrailingOptions(arguments, true)];\n return this._runTask(\n straightThroughStringTask(commands, true),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n */\nGit.prototype.clean = function (mode, options, then) {\n const usingCleanOptionsArray = isCleanOptionsArray(mode);\n const cleanMode =\n (usingCleanOptionsArray && mode.join('')) || filterType(mode, filterString) || '';\n const customArgs = getTrailingOptions([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0));\n\n return this._runTask(\n cleanWithOptionsTask(cleanMode, customArgs),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.exec = function (then) {\n const task = {\n commands: [],\n format: 'utf-8',\n parser() {\n if (typeof then === 'function') {\n then();\n }\n },\n };\n\n return this._runTask(task);\n};\n\n/**\n * Clears the queue of pending commands and returns the wrapper instance for chaining.\n *\n * @returns {Git}\n */\nGit.prototype.clearQueue = function () {\n // TODO:\n // this._executor.clear();\n return this;\n};\n\n/**\n * Check if a pathname or pathnames are excluded by .gitignore\n *\n * @param {string|string[]} pathnames\n * @param {Function} [then]\n */\nGit.prototype.checkIgnore = function (pathnames, then) {\n return this._runTask(\n checkIgnoreTask(asArray(filterType(pathnames, filterStringOrStringArray, []))),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.checkIsRepo = function (checkType, then) {\n return this._runTask(\n checkIsRepoTask(filterType(checkType, filterString)),\n trailingFunctionArgument(arguments)\n );\n};\n\nmodule.exports = Git;\n", "import { SimpleGitFactory } from '../../typings';\n\nimport * as api from './api';\nimport {\n abortPlugin,\n blockUnsafeOperationsPlugin,\n commandConfigPrefixingPlugin,\n completionDetectionPlugin,\n customBinaryPlugin,\n errorDetectionHandler,\n errorDetectionPlugin,\n PluginStore,\n progressMonitorPlugin,\n spawnOptionsPlugin,\n timeoutPlugin,\n} from './plugins';\nimport { suffixPathsPlugin } from './plugins/suffix-paths.plugin';\nimport { createInstanceConfig, folderExists } from './utils';\nimport { SimpleGitOptions } from './types';\n\nconst Git = require('../git');\n\n/**\n * Adds the necessary properties to the supplied object to enable it for use as\n * the default export of a module.\n *\n * Eg: `module.exports = esModuleFactory({ something () {} })`\n */\nexport function esModuleFactory(defaultExport: T) {\n return Object.defineProperties(defaultExport, {\n __esModule: { value: true },\n default: { value: defaultExport },\n }) as T & { __esModule: true; default: T };\n}\n\nexport function gitExportFactory(factory: SimpleGitFactory) {\n return Object.assign(factory.bind(null), api);\n}\n\nexport function gitInstanceFactory(\n baseDir?: string | Partial,\n options?: Partial\n) {\n const plugins = new PluginStore();\n const config = createInstanceConfig(\n (baseDir && (typeof baseDir === 'string' ? { baseDir } : baseDir)) || {},\n options\n );\n\n if (!folderExists(config.baseDir)) {\n throw new api.GitConstructError(\n config,\n `Cannot use simple-git on a directory that does not exist`\n );\n }\n\n if (Array.isArray(config.config)) {\n plugins.add(commandConfigPrefixingPlugin(config.config));\n }\n\n plugins.add(blockUnsafeOperationsPlugin(config.unsafe));\n plugins.add(suffixPathsPlugin());\n plugins.add(completionDetectionPlugin(config.completion));\n config.abort && plugins.add(abortPlugin(config.abort));\n config.progress && plugins.add(progressMonitorPlugin(config.progress));\n config.timeout && plugins.add(timeoutPlugin(config.timeout));\n config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions));\n\n plugins.add(errorDetectionPlugin(errorDetectionHandler(true)));\n config.errors && plugins.add(errorDetectionPlugin(config.errors));\n\n customBinaryPlugin(plugins, config.binary, config.unsafe?.allowUnsafeCustomBinary);\n\n return new Git(config, plugins);\n}\n", "import { SimpleGit, SimpleGitOptions } from '../../../typings';\n\nimport { GitResponseError } from '../errors/git-response-error';\nimport { gitInstanceFactory } from '../git-factory';\nimport { SimpleGitTaskCallback } from '../types';\n\nconst functionNamesBuilderApi = ['customBinary', 'env', 'outputHandler', 'silent'];\n\nconst functionNamesPromiseApi = [\n 'add',\n 'addAnnotatedTag',\n 'addConfig',\n 'addRemote',\n 'addTag',\n 'applyPatch',\n 'binaryCatFile',\n 'branch',\n 'branchLocal',\n 'catFile',\n 'checkIgnore',\n 'checkIsRepo',\n 'checkout',\n 'checkoutBranch',\n 'checkoutLatestTag',\n 'checkoutLocalBranch',\n 'clean',\n 'clone',\n 'commit',\n 'cwd',\n 'deleteLocalBranch',\n 'deleteLocalBranches',\n 'diff',\n 'diffSummary',\n 'exec',\n 'fetch',\n 'getRemotes',\n 'init',\n 'listConfig',\n 'listRemote',\n 'log',\n 'merge',\n 'mergeFromTo',\n 'mirror',\n 'mv',\n 'pull',\n 'push',\n 'pushTags',\n 'raw',\n 'rebase',\n 'remote',\n 'removeRemote',\n 'reset',\n 'revert',\n 'revparse',\n 'rm',\n 'rmKeepLocal',\n 'show',\n 'stash',\n 'stashList',\n 'status',\n 'subModule',\n 'submoduleAdd',\n 'submoduleInit',\n 'submoduleUpdate',\n 'tag',\n 'tags',\n 'updateServerInfo',\n];\n\nexport function gitP(\n ...args: [] | [string] | [Partial] | [string, Partial]\n): SimpleGit {\n let git: any;\n\n let chain = Promise.resolve();\n\n try {\n git = gitInstanceFactory(...args);\n } catch (e) {\n chain = Promise.reject(e);\n }\n\n function builderReturn() {\n return promiseApi;\n }\n\n function chainReturn() {\n return chain;\n }\n\n const promiseApi = [...functionNamesBuilderApi, ...functionNamesPromiseApi].reduce(\n (api: any, name: string) => {\n const isAsync = functionNamesPromiseApi.includes(name);\n\n const valid = isAsync ? asyncWrapper(name, git) : syncWrapper(name, git, api);\n const alternative = isAsync ? chainReturn : builderReturn;\n\n Object.defineProperty(api, name, {\n enumerable: false,\n configurable: false,\n value: git ? valid : alternative,\n });\n\n return api;\n },\n {}\n );\n\n return promiseApi as SimpleGit;\n\n function asyncWrapper(fn: string, git: any): (...args: any[]) => Promise {\n return function (...args: any[]) {\n if (typeof args[args.length] === 'function') {\n throw new TypeError(\n 'Promise interface requires that handlers are not supplied inline, ' +\n 'trailing function not allowed in call to ' +\n fn\n );\n }\n\n return chain.then(function () {\n return new Promise(function (resolve, reject) {\n const callback: SimpleGitTaskCallback = (err: Error | null, result?: any) => {\n if (err) {\n return reject(toError(err));\n }\n\n resolve(result);\n };\n args.push(callback);\n\n git[fn].apply(git, args);\n });\n });\n };\n }\n\n function syncWrapper(fn: string, git: any, api: SimpleGit) {\n return (...args: any[]) => {\n git[fn](...args);\n\n return api;\n };\n }\n}\n\nfunction toError(error: Error | string | any): Error {\n if (error instanceof Error) {\n return error;\n }\n\n if (typeof error === 'string') {\n return new Error(error);\n }\n\n return new GitResponseError(error);\n}\n", "const { gitP } = require('./lib/runners/promise-wrapped');\nconst { esModuleFactory, gitInstanceFactory, gitExportFactory } = require('./lib/git-factory');\n\nconst simpleGit = esModuleFactory(gitExportFactory(gitInstanceFactory));\n\nmodule.exports = Object.assign(simpleGit, { gitP, simpleGit });\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IA2Ba;AA3Bb;AAAA;AAAA;AA2BO,IAAM,WAAN,cAAuB,MAAM;AAAA,MACjC,YACU,MACP,SACD;AACC,cAAM,OAAO;AAHN;AAIP,eAAO,eAAe,MAAM,WAAW,SAAS;AAAA,MACnD;AAAA,IACH;AAAA;AAAA;;;ACnCA,IAsBa;AAtBb;AAAA;AAAA;AAAA;AAsBO,IAAM,mBAAN,cAAwC,SAAS;AAAA,MACrD,YAImB,KAChB,SACD;AACC,cAAM,QAAW,WAAW,OAAO,GAAG,CAAC;AAHvB;AAAA,MAInB;AAAA,IACH;AAAA;AAAA;;;AC9BO,SAAS,YAAY,OAAiB;AAC1C,QAAM,MAAM,IAAI,OAAO,KAAK;AAC5B,QAAM,IAAI,KAAK,KAAK;AAEpB,SAAO;AACV;AAEO,SAAS,WAAW,MAAwC;AAChE,SAAO,gBAAgB,UAAU,MAAM,IAAI,IAAI;AAClD;AAEO,SAAS,QAAQ,UAA4B;AACjD,SAAO,MAAM,IAAI,QAAQ,KAAK,CAAC;AAClC;AAfA,IAAM;AAAN;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A;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACH;AAAA;AAAA;;;ACnEA,IAAM,EAAE,MAAAC,MAAK,IAAI;AACjB,IAAM,EAAE,iBAAAC,kBAAiB,oBAAAC,qBAAoB,kBAAAC,kBAAiB,IAAI;AAElE,IAAM,YAAYF,iBAAgBE,kBAAiBD,mBAAkB,CAAC;AAEtE,OAAO,UAAU,OAAO,OAAO,WAAW,EAAE,MAAAF,OAAM,UAAU,CAAC;", + "names": ["trimmed", "ExitCodes", "commands", "parser", "parsers", "CheckRepoActions", "parser", "trimmed", "CleanOptions", "append", "GitConfigScope", "DiffNameStatus", "ResetMode", "_a", "input", "plugin", "_a", "_a", "_b", "append", "debug", "onError", "parser", "parser", "excludeOptions", "parsers", "parsers", "parsers", "parsers", "parser", "trimmed", "parsers", "parsers", "import_promise_deferred", "parsers", "parsers", "parser", "parsers", "disallowedCommand", "parsers", "parser", "exports", "module", "GitExecutor", "SimpleGitApi", "Scheduler", "configurationErrorTask", "asArray", "filterArray", "filterPrimitives", "filterString", "filterStringOrStringArray", "filterType", "getTrailingOptions", "trailingFunctionArgument", "trailingOptionsArgument", "applyPatchTask", "branchTask", "branchLocalTask", "deleteBranchesTask", "deleteBranchTask", "checkIgnoreTask", "checkIsRepoTask", "cloneTask", "cloneMirrorTask", "cleanWithOptionsTask", "isCleanOptionsArray", "diffSummaryTask", "fetchTask", "moveTask", "pullTask", "pushTagsTask", "addRemoteTask", "getRemotesTask", "listRemotesTask", "remoteTask", "removeRemoteTask", "getResetMode", "resetTask", "stashListTask", "addSubModuleTask", "initSubModuleTask", "subModuleTask", "updateSubModuleTask", "addAnnotatedTagTask", "addTagTask", "tagListTask", "straightThroughBufferTask", "straightThroughStringTask", "Git", "_a", "git", "args", "gitP", "esModuleFactory", "gitInstanceFactory", "gitExportFactory"] +} diff --git a/node_modules/simple-git/dist/esm/index.js b/node_modules/simple-git/dist/esm/index.js new file mode 100644 index 0000000..ae7a564 --- /dev/null +++ b/node_modules/simple-git/dist/esm/index.js @@ -0,0 +1,4762 @@ +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +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); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +// src/lib/args/pathspec.ts +function pathspec(...paths) { + const key = new String(paths); + cache.set(key, paths); + return key; +} +function isPathSpec(path) { + return path instanceof String && cache.has(path); +} +function toPaths(pathSpec) { + return cache.get(pathSpec) || []; +} +var cache; +var init_pathspec = __esm({ + "src/lib/args/pathspec.ts"() { + "use strict"; + cache = /* @__PURE__ */ new WeakMap(); + } +}); + +// src/lib/errors/git-error.ts +var GitError; +var init_git_error = __esm({ + "src/lib/errors/git-error.ts"() { + "use strict"; + GitError = class extends Error { + constructor(task, message) { + super(message); + this.task = task; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + } +}); + +// src/lib/errors/git-response-error.ts +var GitResponseError; +var init_git_response_error = __esm({ + "src/lib/errors/git-response-error.ts"() { + "use strict"; + init_git_error(); + GitResponseError = class extends GitError { + constructor(git, message) { + super(void 0, message || String(git)); + this.git = git; + } + }; + } +}); + +// src/lib/errors/task-configuration-error.ts +var TaskConfigurationError; +var init_task_configuration_error = __esm({ + "src/lib/errors/task-configuration-error.ts"() { + "use strict"; + init_git_error(); + TaskConfigurationError = class extends GitError { + constructor(message) { + super(void 0, message); + } + }; + } +}); + +// src/lib/utils/util.ts +import { exists, FOLDER } from "@kwsites/file-exists"; +function asFunction(source) { + return typeof source === "function" ? source : NOOP; +} +function isUserFunction(source) { + return typeof source === "function" && source !== NOOP; +} +function splitOn(input, char) { + const index = input.indexOf(char); + if (index <= 0) { + return [input, ""]; + } + return [input.substr(0, index), input.substr(index + 1)]; +} +function first(input, offset = 0) { + return isArrayLike(input) && input.length > offset ? input[offset] : void 0; +} +function last(input, offset = 0) { + if (isArrayLike(input) && input.length > offset) { + return input[input.length - 1 - offset]; + } +} +function isArrayLike(input) { + return !!(input && typeof input.length === "number"); +} +function toLinesWithContent(input = "", trimmed2 = true, separator = "\n") { + return input.split(separator).reduce((output, line) => { + const lineContent = trimmed2 ? line.trim() : line; + if (lineContent) { + output.push(lineContent); + } + return output; + }, []); +} +function forEachLineWithContent(input, callback) { + return toLinesWithContent(input, true).map((line) => callback(line)); +} +function folderExists(path) { + return exists(path, FOLDER); +} +function append(target, item) { + if (Array.isArray(target)) { + if (!target.includes(item)) { + target.push(item); + } + } else { + target.add(item); + } + return item; +} +function including(target, item) { + if (Array.isArray(target) && !target.includes(item)) { + target.push(item); + } + return target; +} +function remove(target, item) { + if (Array.isArray(target)) { + const index = target.indexOf(item); + if (index >= 0) { + target.splice(index, 1); + } + } else { + target.delete(item); + } + return item; +} +function asArray(source) { + return Array.isArray(source) ? source : [source]; +} +function asStringArray(source) { + return asArray(source).map(String); +} +function asNumber(source, onNaN = 0) { + if (source == null) { + return onNaN; + } + const num = parseInt(source, 10); + return isNaN(num) ? onNaN : num; +} +function prefixedArray(input, prefix) { + const output = []; + for (let i = 0, max = input.length; i < max; i++) { + output.push(prefix, input[i]); + } + return output; +} +function bufferToString(input) { + return (Array.isArray(input) ? Buffer.concat(input) : input).toString("utf-8"); +} +function pick(source, properties) { + return Object.assign( + {}, + ...properties.map((property) => property in source ? { [property]: source[property] } : {}) + ); +} +function delay(duration = 0) { + return new Promise((done) => setTimeout(done, duration)); +} +function orVoid(input) { + if (input === false) { + return void 0; + } + return input; +} +var NULL, NOOP, objectToString; +var init_util = __esm({ + "src/lib/utils/util.ts"() { + "use strict"; + NULL = "\0"; + NOOP = () => { + }; + objectToString = Object.prototype.toString.call.bind(Object.prototype.toString); + } +}); + +// src/lib/utils/argument-filters.ts +function filterType(input, filter, def) { + if (filter(input)) { + return input; + } + return arguments.length > 2 ? def : void 0; +} +function filterPrimitives(input, omit) { + const type = isPathSpec(input) ? "string" : typeof input; + return /number|string|boolean/.test(type) && (!omit || !omit.includes(type)); +} +function filterPlainObject(input) { + return !!input && objectToString(input) === "[object Object]"; +} +function filterFunction(input) { + return typeof input === "function"; +} +var filterArray, filterString, filterStringArray, filterStringOrStringArray, filterHasLength; +var init_argument_filters = __esm({ + "src/lib/utils/argument-filters.ts"() { + "use strict"; + init_util(); + init_pathspec(); + filterArray = (input) => { + return Array.isArray(input); + }; + filterString = (input) => { + return typeof input === "string"; + }; + filterStringArray = (input) => { + return Array.isArray(input) && input.every(filterString); + }; + filterStringOrStringArray = (input) => { + return filterString(input) || Array.isArray(input) && input.every(filterString); + }; + filterHasLength = (input) => { + if (input == null || "number|boolean|function".includes(typeof input)) { + return false; + } + return Array.isArray(input) || typeof input === "string" || typeof input.length === "number"; + }; + } +}); + +// src/lib/utils/exit-codes.ts +var ExitCodes; +var init_exit_codes = __esm({ + "src/lib/utils/exit-codes.ts"() { + "use strict"; + ExitCodes = /* @__PURE__ */ ((ExitCodes2) => { + ExitCodes2[ExitCodes2["SUCCESS"] = 0] = "SUCCESS"; + ExitCodes2[ExitCodes2["ERROR"] = 1] = "ERROR"; + ExitCodes2[ExitCodes2["NOT_FOUND"] = -2] = "NOT_FOUND"; + ExitCodes2[ExitCodes2["UNCLEAN"] = 128] = "UNCLEAN"; + return ExitCodes2; + })(ExitCodes || {}); + } +}); + +// src/lib/utils/git-output-streams.ts +var GitOutputStreams; +var init_git_output_streams = __esm({ + "src/lib/utils/git-output-streams.ts"() { + "use strict"; + GitOutputStreams = class { + constructor(stdOut, stdErr) { + this.stdOut = stdOut; + this.stdErr = stdErr; + } + asStrings() { + return new GitOutputStreams(this.stdOut.toString("utf8"), this.stdErr.toString("utf8")); + } + }; + } +}); + +// src/lib/utils/line-parser.ts +var LineParser, RemoteLineParser; +var init_line_parser = __esm({ + "src/lib/utils/line-parser.ts"() { + "use strict"; + LineParser = class { + constructor(regExp, useMatches) { + this.matches = []; + this.parse = (line, target) => { + this.resetMatches(); + if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) { + return false; + } + return this.useMatches(target, this.prepareMatches()) !== false; + }; + this._regExp = Array.isArray(regExp) ? regExp : [regExp]; + if (useMatches) { + this.useMatches = useMatches; + } + } + useMatches(target, match) { + throw new Error(`LineParser:useMatches not implemented`); + } + resetMatches() { + this.matches.length = 0; + } + prepareMatches() { + return this.matches; + } + addMatch(reg, index, line) { + const matched = line && reg.exec(line); + if (matched) { + this.pushMatch(index, matched); + } + return !!matched; + } + pushMatch(_index, matched) { + this.matches.push(...matched.slice(1)); + } + }; + RemoteLineParser = class extends LineParser { + addMatch(reg, index, line) { + return /^remote:\s/.test(String(line)) && super.addMatch(reg, index, line); + } + pushMatch(index, matched) { + if (index > 0 || matched.length > 1) { + super.pushMatch(index, matched); + } + } + }; + } +}); + +// src/lib/utils/simple-git-options.ts +function createInstanceConfig(...options) { + const baseDir = process.cwd(); + const config = Object.assign( + __spreadValues({ baseDir }, defaultOptions), + ...options.filter((o) => typeof o === "object" && o) + ); + config.baseDir = config.baseDir || baseDir; + config.trimmed = config.trimmed === true; + return config; +} +var defaultOptions; +var init_simple_git_options = __esm({ + "src/lib/utils/simple-git-options.ts"() { + "use strict"; + defaultOptions = { + binary: "git", + maxConcurrentProcesses: 5, + config: [], + trimmed: false + }; + } +}); + +// src/lib/utils/task-options.ts +function appendTaskOptions(options, commands = []) { + if (!filterPlainObject(options)) { + return commands; + } + return Object.keys(options).reduce((commands2, key) => { + const value = options[key]; + if (isPathSpec(value)) { + commands2.push(value); + } else if (filterPrimitives(value, ["boolean"])) { + commands2.push(key + "=" + value); + } else { + commands2.push(key); + } + return commands2; + }, commands); +} +function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) { + const command = []; + for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) { + if ("string|number".includes(typeof args[i])) { + command.push(String(args[i])); + } + } + appendTaskOptions(trailingOptionsArgument(args), command); + if (!objectOnly) { + command.push(...trailingArrayArgument(args)); + } + return command; +} +function trailingArrayArgument(args) { + const hasTrailingCallback = typeof last(args) === "function"; + return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []); +} +function trailingOptionsArgument(args) { + const hasTrailingCallback = filterFunction(last(args)); + return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject); +} +function trailingFunctionArgument(args, includeNoop = true) { + const callback = asFunction(last(args)); + return includeNoop || isUserFunction(callback) ? callback : void 0; +} +var init_task_options = __esm({ + "src/lib/utils/task-options.ts"() { + "use strict"; + init_argument_filters(); + init_util(); + init_pathspec(); + } +}); + +// src/lib/utils/task-parser.ts +function callTaskParser(parser3, streams) { + return parser3(streams.stdOut, streams.stdErr); +} +function parseStringResponse(result, parsers12, texts, trim = true) { + asArray(texts).forEach((text) => { + for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) { + const line = (offset = 0) => { + if (i + offset >= max) { + return; + } + return lines[i + offset]; + }; + parsers12.some(({ parse }) => parse(line, result)); + } + }); + return result; +} +var init_task_parser = __esm({ + "src/lib/utils/task-parser.ts"() { + "use strict"; + init_util(); + } +}); + +// src/lib/utils/index.ts +var utils_exports = {}; +__export(utils_exports, { + ExitCodes: () => ExitCodes, + GitOutputStreams: () => GitOutputStreams, + LineParser: () => LineParser, + NOOP: () => NOOP, + NULL: () => NULL, + RemoteLineParser: () => RemoteLineParser, + append: () => append, + appendTaskOptions: () => appendTaskOptions, + asArray: () => asArray, + asFunction: () => asFunction, + asNumber: () => asNumber, + asStringArray: () => asStringArray, + bufferToString: () => bufferToString, + callTaskParser: () => callTaskParser, + createInstanceConfig: () => createInstanceConfig, + delay: () => delay, + filterArray: () => filterArray, + filterFunction: () => filterFunction, + filterHasLength: () => filterHasLength, + filterPlainObject: () => filterPlainObject, + filterPrimitives: () => filterPrimitives, + filterString: () => filterString, + filterStringArray: () => filterStringArray, + filterStringOrStringArray: () => filterStringOrStringArray, + filterType: () => filterType, + first: () => first, + folderExists: () => folderExists, + forEachLineWithContent: () => forEachLineWithContent, + getTrailingOptions: () => getTrailingOptions, + including: () => including, + isUserFunction: () => isUserFunction, + last: () => last, + objectToString: () => objectToString, + orVoid: () => orVoid, + parseStringResponse: () => parseStringResponse, + pick: () => pick, + prefixedArray: () => prefixedArray, + remove: () => remove, + splitOn: () => splitOn, + toLinesWithContent: () => toLinesWithContent, + trailingFunctionArgument: () => trailingFunctionArgument, + trailingOptionsArgument: () => trailingOptionsArgument +}); +var init_utils = __esm({ + "src/lib/utils/index.ts"() { + "use strict"; + init_argument_filters(); + init_exit_codes(); + init_git_output_streams(); + init_line_parser(); + init_simple_git_options(); + init_task_options(); + init_task_parser(); + init_util(); + } +}); + +// src/lib/tasks/check-is-repo.ts +var check_is_repo_exports = {}; +__export(check_is_repo_exports, { + CheckRepoActions: () => CheckRepoActions, + checkIsBareRepoTask: () => checkIsBareRepoTask, + checkIsRepoRootTask: () => checkIsRepoRootTask, + checkIsRepoTask: () => checkIsRepoTask +}); +function checkIsRepoTask(action) { + switch (action) { + case "bare" /* BARE */: + return checkIsBareRepoTask(); + case "root" /* IS_REPO_ROOT */: + return checkIsRepoRootTask(); + } + const commands = ["rev-parse", "--is-inside-work-tree"]; + return { + commands, + format: "utf-8", + onError, + parser + }; +} +function checkIsRepoRootTask() { + const commands = ["rev-parse", "--git-dir"]; + return { + commands, + format: "utf-8", + onError, + parser(path) { + return /^\.(git)?$/.test(path.trim()); + } + }; +} +function checkIsBareRepoTask() { + const commands = ["rev-parse", "--is-bare-repository"]; + return { + commands, + format: "utf-8", + onError, + parser + }; +} +function isNotRepoMessage(error) { + return /(Not a git repository|Kein Git-Repository)/i.test(String(error)); +} +var CheckRepoActions, onError, parser; +var init_check_is_repo = __esm({ + "src/lib/tasks/check-is-repo.ts"() { + "use strict"; + init_utils(); + CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => { + CheckRepoActions2["BARE"] = "bare"; + CheckRepoActions2["IN_TREE"] = "tree"; + CheckRepoActions2["IS_REPO_ROOT"] = "root"; + return CheckRepoActions2; + })(CheckRepoActions || {}); + onError = ({ exitCode }, error, done, fail) => { + if (exitCode === 128 /* UNCLEAN */ && isNotRepoMessage(error)) { + return done(Buffer.from("false")); + } + fail(error); + }; + parser = (text) => { + return text.trim() === "true"; + }; + } +}); + +// src/lib/responses/CleanSummary.ts +function cleanSummaryParser(dryRun, text) { + const summary = new CleanResponse(dryRun); + const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp; + toLinesWithContent(text).forEach((line) => { + const removed = line.replace(regexp, ""); + summary.paths.push(removed); + (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed); + }); + return summary; +} +var CleanResponse, removalRegexp, dryRunRemovalRegexp, isFolderRegexp; +var init_CleanSummary = __esm({ + "src/lib/responses/CleanSummary.ts"() { + "use strict"; + init_utils(); + CleanResponse = class { + constructor(dryRun) { + this.dryRun = dryRun; + this.paths = []; + this.files = []; + this.folders = []; + } + }; + removalRegexp = /^[a-z]+\s*/i; + dryRunRemovalRegexp = /^[a-z]+\s+[a-z]+\s*/i; + isFolderRegexp = /\/$/; + } +}); + +// src/lib/tasks/task.ts +var task_exports = {}; +__export(task_exports, { + EMPTY_COMMANDS: () => EMPTY_COMMANDS, + adhocExecTask: () => adhocExecTask, + configurationErrorTask: () => configurationErrorTask, + isBufferTask: () => isBufferTask, + isEmptyTask: () => isEmptyTask, + straightThroughBufferTask: () => straightThroughBufferTask, + straightThroughStringTask: () => straightThroughStringTask +}); +function adhocExecTask(parser3) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser: parser3 + }; +} +function configurationErrorTask(error) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser() { + throw typeof error === "string" ? new TaskConfigurationError(error) : error; + } + }; +} +function straightThroughStringTask(commands, trimmed2 = false) { + return { + commands, + format: "utf-8", + parser(text) { + return trimmed2 ? String(text).trim() : text; + } + }; +} +function straightThroughBufferTask(commands) { + return { + commands, + format: "buffer", + parser(buffer) { + return buffer; + } + }; +} +function isBufferTask(task) { + return task.format === "buffer"; +} +function isEmptyTask(task) { + return task.format === "empty" || !task.commands.length; +} +var EMPTY_COMMANDS; +var init_task = __esm({ + "src/lib/tasks/task.ts"() { + "use strict"; + init_task_configuration_error(); + EMPTY_COMMANDS = []; + } +}); + +// src/lib/tasks/clean.ts +var clean_exports = {}; +__export(clean_exports, { + CONFIG_ERROR_INTERACTIVE_MODE: () => CONFIG_ERROR_INTERACTIVE_MODE, + CONFIG_ERROR_MODE_REQUIRED: () => CONFIG_ERROR_MODE_REQUIRED, + CONFIG_ERROR_UNKNOWN_OPTION: () => CONFIG_ERROR_UNKNOWN_OPTION, + CleanOptions: () => CleanOptions, + cleanTask: () => cleanTask, + cleanWithOptionsTask: () => cleanWithOptionsTask, + isCleanOptionsArray: () => isCleanOptionsArray +}); +function cleanWithOptionsTask(mode, customArgs) { + const { cleanMode, options, valid } = getCleanOptions(mode); + if (!cleanMode) { + return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED); + } + if (!valid.options) { + return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode)); + } + options.push(...customArgs); + if (options.some(isInteractiveMode)) { + return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE); + } + return cleanTask(cleanMode, options); +} +function cleanTask(mode, customArgs) { + const commands = ["clean", `-${mode}`, ...customArgs]; + return { + commands, + format: "utf-8", + parser(text) { + return cleanSummaryParser(mode === "n" /* DRY_RUN */, text); + } + }; +} +function isCleanOptionsArray(input) { + return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test)); +} +function getCleanOptions(input) { + let cleanMode; + let options = []; + let valid = { cleanMode: false, options: true }; + input.replace(/[^a-z]i/g, "").split("").forEach((char) => { + if (isCleanMode(char)) { + cleanMode = char; + valid.cleanMode = true; + } else { + valid.options = valid.options && isKnownOption(options[options.length] = `-${char}`); + } + }); + return { + cleanMode, + options, + valid + }; +} +function isCleanMode(cleanMode) { + return cleanMode === "f" /* FORCE */ || cleanMode === "n" /* DRY_RUN */; +} +function isKnownOption(option) { + return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1)); +} +function isInteractiveMode(option) { + if (/^-[^\-]/.test(option)) { + return option.indexOf("i") > 0; + } + return option === "--interactive"; +} +var CONFIG_ERROR_INTERACTIVE_MODE, CONFIG_ERROR_MODE_REQUIRED, CONFIG_ERROR_UNKNOWN_OPTION, CleanOptions, CleanOptionValues; +var init_clean = __esm({ + "src/lib/tasks/clean.ts"() { + "use strict"; + init_CleanSummary(); + init_utils(); + init_task(); + CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported"; + CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required'; + CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: "; + CleanOptions = /* @__PURE__ */ ((CleanOptions2) => { + CleanOptions2["DRY_RUN"] = "n"; + CleanOptions2["FORCE"] = "f"; + CleanOptions2["IGNORED_INCLUDED"] = "x"; + CleanOptions2["IGNORED_ONLY"] = "X"; + CleanOptions2["EXCLUDING"] = "e"; + CleanOptions2["QUIET"] = "q"; + CleanOptions2["RECURSIVE"] = "d"; + return CleanOptions2; + })(CleanOptions || {}); + CleanOptionValues = /* @__PURE__ */ new Set([ + "i", + ...asStringArray(Object.values(CleanOptions)) + ]); + } +}); + +// src/lib/responses/ConfigList.ts +function configListParser(text) { + const config = new ConfigList(); + for (const item of configParser(text)) { + config.addValue(item.file, String(item.key), item.value); + } + return config; +} +function configGetParser(text, key) { + let value = null; + const values = []; + const scopes = /* @__PURE__ */ new Map(); + for (const item of configParser(text, key)) { + if (item.key !== key) { + continue; + } + values.push(value = item.value); + if (!scopes.has(item.file)) { + scopes.set(item.file, []); + } + scopes.get(item.file).push(value); + } + return { + key, + paths: Array.from(scopes.keys()), + scopes, + value, + values + }; +} +function configFilePath(filePath) { + return filePath.replace(/^(file):/, ""); +} +function* configParser(text, requestedKey = null) { + const lines = text.split("\0"); + for (let i = 0, max = lines.length - 1; i < max; ) { + const file = configFilePath(lines[i++]); + let value = lines[i++]; + let key = requestedKey; + if (value.includes("\n")) { + const line = splitOn(value, "\n"); + key = line[0]; + value = line[1]; + } + yield { file, key, value }; + } +} +var ConfigList; +var init_ConfigList = __esm({ + "src/lib/responses/ConfigList.ts"() { + "use strict"; + init_utils(); + ConfigList = class { + constructor() { + this.files = []; + this.values = /* @__PURE__ */ Object.create(null); + } + get all() { + if (!this._all) { + this._all = this.files.reduce((all, file) => { + return Object.assign(all, this.values[file]); + }, {}); + } + return this._all; + } + addFile(file) { + if (!(file in this.values)) { + const latest = last(this.files); + this.values[file] = latest ? Object.create(this.values[latest]) : {}; + this.files.push(file); + } + return this.values[file]; + } + addValue(file, key, value) { + const values = this.addFile(file); + if (!values.hasOwnProperty(key)) { + values[key] = value; + } else if (Array.isArray(values[key])) { + values[key].push(value); + } else { + values[key] = [values[key], value]; + } + this._all = void 0; + } + }; + } +}); + +// src/lib/tasks/config.ts +function asConfigScope(scope, fallback) { + if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) { + return scope; + } + return fallback; +} +function addConfigTask(key, value, append2, scope) { + const commands = ["config", `--${scope}`]; + if (append2) { + commands.push("--add"); + } + commands.push(key, value); + return { + commands, + format: "utf-8", + parser(text) { + return text; + } + }; +} +function getConfigTask(key, scope) { + const commands = ["config", "--null", "--show-origin", "--get-all", key]; + if (scope) { + commands.splice(1, 0, `--${scope}`); + } + return { + commands, + format: "utf-8", + parser(text) { + return configGetParser(text, key); + } + }; +} +function listConfigTask(scope) { + const commands = ["config", "--list", "--show-origin", "--null"]; + if (scope) { + commands.push(`--${scope}`); + } + return { + commands, + format: "utf-8", + parser(text) { + return configListParser(text); + } + }; +} +function config_default() { + return { + addConfig(key, value, ...rest) { + return this._runTask( + addConfigTask( + key, + value, + rest[0] === true, + asConfigScope(rest[1], "local" /* local */) + ), + trailingFunctionArgument(arguments) + ); + }, + getConfig(key, scope) { + return this._runTask( + getConfigTask(key, asConfigScope(scope, void 0)), + trailingFunctionArgument(arguments) + ); + }, + listConfig(...rest) { + return this._runTask( + listConfigTask(asConfigScope(rest[0], void 0)), + trailingFunctionArgument(arguments) + ); + } + }; +} +var GitConfigScope; +var init_config = __esm({ + "src/lib/tasks/config.ts"() { + "use strict"; + init_ConfigList(); + init_utils(); + GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => { + GitConfigScope2["system"] = "system"; + GitConfigScope2["global"] = "global"; + GitConfigScope2["local"] = "local"; + GitConfigScope2["worktree"] = "worktree"; + return GitConfigScope2; + })(GitConfigScope || {}); + } +}); + +// src/lib/tasks/diff-name-status.ts +function isDiffNameStatus(input) { + return diffNameStatus.has(input); +} +var DiffNameStatus, diffNameStatus; +var init_diff_name_status = __esm({ + "src/lib/tasks/diff-name-status.ts"() { + "use strict"; + DiffNameStatus = /* @__PURE__ */ ((DiffNameStatus2) => { + DiffNameStatus2["ADDED"] = "A"; + DiffNameStatus2["COPIED"] = "C"; + DiffNameStatus2["DELETED"] = "D"; + DiffNameStatus2["MODIFIED"] = "M"; + DiffNameStatus2["RENAMED"] = "R"; + DiffNameStatus2["CHANGED"] = "T"; + DiffNameStatus2["UNMERGED"] = "U"; + DiffNameStatus2["UNKNOWN"] = "X"; + DiffNameStatus2["BROKEN"] = "B"; + return DiffNameStatus2; + })(DiffNameStatus || {}); + diffNameStatus = new Set(Object.values(DiffNameStatus)); + } +}); + +// src/lib/tasks/grep.ts +function grepQueryBuilder(...params) { + return new GrepQuery().param(...params); +} +function parseGrep(grep) { + const paths = /* @__PURE__ */ new Set(); + const results = {}; + forEachLineWithContent(grep, (input) => { + const [path, line, preview] = input.split(NULL); + paths.add(path); + (results[path] = results[path] || []).push({ + line: asNumber(line), + path, + preview + }); + }); + return { + paths, + results + }; +} +function grep_default() { + return { + grep(searchTerm) { + const then = trailingFunctionArgument(arguments); + const options = getTrailingOptions(arguments); + for (const option of disallowedOptions) { + if (options.includes(option)) { + return this._runTask( + configurationErrorTask(`git.grep: use of "${option}" is not supported.`), + then + ); + } + } + if (typeof searchTerm === "string") { + searchTerm = grepQueryBuilder().param(searchTerm); + } + const commands = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm]; + return this._runTask( + { + commands, + format: "utf-8", + parser(stdOut) { + return parseGrep(stdOut); + } + }, + then + ); + } + }; +} +var disallowedOptions, Query, _a, GrepQuery; +var init_grep = __esm({ + "src/lib/tasks/grep.ts"() { + "use strict"; + init_utils(); + init_task(); + disallowedOptions = ["-h"]; + Query = Symbol("grepQuery"); + GrepQuery = class { + constructor() { + this[_a] = []; + } + *[(_a = Query, Symbol.iterator)]() { + for (const query of this[Query]) { + yield query; + } + } + and(...and) { + and.length && this[Query].push("--and", "(", ...prefixedArray(and, "-e"), ")"); + return this; + } + param(...param) { + this[Query].push(...prefixedArray(param, "-e")); + return this; + } + }; + } +}); + +// src/lib/tasks/reset.ts +var reset_exports = {}; +__export(reset_exports, { + ResetMode: () => ResetMode, + getResetMode: () => getResetMode, + resetTask: () => resetTask +}); +function resetTask(mode, customArgs) { + const commands = ["reset"]; + if (isValidResetMode(mode)) { + commands.push(`--${mode}`); + } + commands.push(...customArgs); + return straightThroughStringTask(commands); +} +function getResetMode(mode) { + if (isValidResetMode(mode)) { + return mode; + } + switch (typeof mode) { + case "string": + case "undefined": + return "soft" /* SOFT */; + } + return; +} +function isValidResetMode(mode) { + return ResetModes.includes(mode); +} +var ResetMode, ResetModes; +var init_reset = __esm({ + "src/lib/tasks/reset.ts"() { + "use strict"; + init_task(); + ResetMode = /* @__PURE__ */ ((ResetMode2) => { + ResetMode2["MIXED"] = "mixed"; + ResetMode2["SOFT"] = "soft"; + ResetMode2["HARD"] = "hard"; + ResetMode2["MERGE"] = "merge"; + ResetMode2["KEEP"] = "keep"; + return ResetMode2; + })(ResetMode || {}); + ResetModes = Array.from(Object.values(ResetMode)); + } +}); + +// src/lib/git-logger.ts +import debug from "debug"; +function createLog() { + return debug("simple-git"); +} +function prefixedLogger(to, prefix, forward) { + if (!prefix || !String(prefix).replace(/\s*/, "")) { + return !forward ? to : (message, ...args) => { + to(message, ...args); + forward(message, ...args); + }; + } + return (message, ...args) => { + to(`%s ${message}`, prefix, ...args); + if (forward) { + forward(message, ...args); + } + }; +} +function childLoggerName(name, childDebugger, { namespace: parentNamespace }) { + if (typeof name === "string") { + return name; + } + const childNamespace = childDebugger && childDebugger.namespace || ""; + if (childNamespace.startsWith(parentNamespace)) { + return childNamespace.substr(parentNamespace.length + 1); + } + return childNamespace || parentNamespace; +} +function createLogger(label, verbose, initialStep, infoDebugger = createLog()) { + const labelPrefix = label && `[${label}]` || ""; + const spawned = []; + const debugDebugger = typeof verbose === "string" ? infoDebugger.extend(verbose) : verbose; + const key = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger); + return step(initialStep); + function sibling(name, initial) { + return append( + spawned, + createLogger(label, key.replace(/^[^:]+/, name), initial, infoDebugger) + ); + } + function step(phase) { + const stepPrefix = phase && `[${phase}]` || ""; + const debug2 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP; + const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug2); + return Object.assign(debugDebugger ? debug2 : info, { + label, + sibling, + info, + step + }); + } +} +var init_git_logger = __esm({ + "src/lib/git-logger.ts"() { + "use strict"; + init_utils(); + debug.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-"); + debug.formatters.B = (value) => { + if (Buffer.isBuffer(value)) { + return value.toString("utf8"); + } + return objectToString(value); + }; + } +}); + +// src/lib/runners/tasks-pending-queue.ts +var _TasksPendingQueue, TasksPendingQueue; +var init_tasks_pending_queue = __esm({ + "src/lib/runners/tasks-pending-queue.ts"() { + "use strict"; + init_git_error(); + init_git_logger(); + _TasksPendingQueue = class { + constructor(logLabel = "GitExecutor") { + this.logLabel = logLabel; + this._queue = /* @__PURE__ */ new Map(); + } + withProgress(task) { + return this._queue.get(task); + } + createProgress(task) { + const name = _TasksPendingQueue.getName(task.commands[0]); + const logger = createLogger(this.logLabel, name); + return { + task, + logger, + name + }; + } + push(task) { + const progress = this.createProgress(task); + progress.logger("Adding task to the queue, commands = %o", task.commands); + this._queue.set(task, progress); + return progress; + } + fatal(err) { + for (const [task, { logger }] of Array.from(this._queue.entries())) { + if (task === err.task) { + logger.info(`Failed %o`, err); + logger( + `Fatal exception, any as-yet un-started tasks run through this executor will not be attempted` + ); + } else { + logger.info( + `A fatal exception occurred in a previous task, the queue has been purged: %o`, + err.message + ); + } + this.complete(task); + } + if (this._queue.size !== 0) { + throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`); + } + } + complete(task) { + const progress = this.withProgress(task); + if (progress) { + this._queue.delete(task); + } + } + attempt(task) { + const progress = this.withProgress(task); + if (!progress) { + throw new GitError(void 0, "TasksPendingQueue: attempt called for an unknown task"); + } + progress.logger("Starting task"); + return progress; + } + static getName(name = "empty") { + return `task:${name}:${++_TasksPendingQueue.counter}`; + } + }; + TasksPendingQueue = _TasksPendingQueue; + TasksPendingQueue.counter = 0; + } +}); + +// src/lib/runners/git-executor-chain.ts +import { spawn } from "child_process"; +function pluginContext(task, commands) { + return { + method: first(task.commands) || "", + commands + }; +} +function onErrorReceived(target, logger) { + return (err) => { + logger(`[ERROR] child process exception %o`, err); + target.push(Buffer.from(String(err.stack), "ascii")); + }; +} +function onDataReceived(target, name, logger, output) { + return (buffer) => { + logger(`%s received %L bytes`, name, buffer); + output(`%B`, buffer); + target.push(buffer); + }; +} +var GitExecutorChain; +var init_git_executor_chain = __esm({ + "src/lib/runners/git-executor-chain.ts"() { + "use strict"; + init_git_error(); + init_task(); + init_utils(); + init_tasks_pending_queue(); + GitExecutorChain = class { + constructor(_executor, _scheduler, _plugins) { + this._executor = _executor; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = Promise.resolve(); + this._queue = new TasksPendingQueue(); + } + get cwd() { + return this._cwd || this._executor.cwd; + } + set cwd(cwd) { + this._cwd = cwd; + } + get env() { + return this._executor.env; + } + get outputHandler() { + return this._executor.outputHandler; + } + chain() { + return this; + } + push(task) { + this._queue.push(task); + return this._chain = this._chain.then(() => this.attemptTask(task)); + } + attemptTask(task) { + return __async(this, null, function* () { + const onScheduleComplete = yield this._scheduler.next(); + const onQueueComplete = () => this._queue.complete(task); + try { + const { logger } = this._queue.attempt(task); + return yield isEmptyTask(task) ? this.attemptEmptyTask(task, logger) : this.attemptRemoteTask(task, logger); + } catch (e) { + throw this.onFatalException(task, e); + } finally { + onQueueComplete(); + onScheduleComplete(); + } + }); + } + onFatalException(task, e) { + const gitError = e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e)); + this._chain = Promise.resolve(); + this._queue.fatal(gitError); + return gitError; + } + attemptRemoteTask(task, logger) { + return __async(this, null, function* () { + const binary = this._plugins.exec("spawn.binary", "", pluginContext(task, task.commands)); + const args = this._plugins.exec( + "spawn.args", + [...task.commands], + pluginContext(task, task.commands) + ); + const raw = yield this.gitResponse( + task, + binary, + args, + this.outputHandler, + logger.step("SPAWN") + ); + const outputStreams = yield this.handleTaskData(task, args, raw, logger.step("HANDLE")); + logger(`passing response to task's parser as a %s`, task.format); + if (isBufferTask(task)) { + return callTaskParser(task.parser, outputStreams); + } + return callTaskParser(task.parser, outputStreams.asStrings()); + }); + } + attemptEmptyTask(task, logger) { + return __async(this, null, function* () { + logger(`empty task bypassing child process to call to task's parser`); + return task.parser(this); + }); + } + handleTaskData(task, args, result, logger) { + const { exitCode, rejection, stdOut, stdErr } = result; + return new Promise((done, fail) => { + logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode); + const { error } = this._plugins.exec( + "task.error", + { error: rejection }, + __spreadValues(__spreadValues({}, pluginContext(task, args)), result) + ); + if (error && task.onError) { + logger.info(`exitCode=%s handling with custom error handler`); + return task.onError( + result, + error, + (newStdOut) => { + logger.info(`custom error handler treated as success`); + logger(`custom error returned a %s`, objectToString(newStdOut)); + done( + new GitOutputStreams( + Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut, + Buffer.concat(stdErr) + ) + ); + }, + fail + ); + } + if (error) { + logger.info( + `handling as error: exitCode=%s stdErr=%s rejection=%o`, + exitCode, + stdErr.length, + rejection + ); + return fail(error); + } + logger.info(`retrieving task output complete`); + done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr))); + }); + } + gitResponse(task, command, args, outputHandler, logger) { + return __async(this, null, function* () { + const outputLogger = logger.sibling("output"); + const spawnOptions = this._plugins.exec( + "spawn.options", + { + cwd: this.cwd, + env: this.env, + windowsHide: true + }, + pluginContext(task, task.commands) + ); + return new Promise((done) => { + const stdOut = []; + const stdErr = []; + logger.info(`%s %o`, command, args); + logger("%O", spawnOptions); + let rejection = this._beforeSpawn(task, args); + if (rejection) { + return done({ + stdOut, + stdErr, + exitCode: 9901, + rejection + }); + } + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + const spawned = spawn(command, args, spawnOptions); + spawned.stdout.on( + "data", + onDataReceived(stdOut, "stdOut", logger, outputLogger.step("stdOut")) + ); + spawned.stderr.on( + "data", + onDataReceived(stdErr, "stdErr", logger, outputLogger.step("stdErr")) + ); + spawned.on("error", onErrorReceived(stdErr, logger)); + if (outputHandler) { + logger(`Passing child process stdOut/stdErr to custom outputHandler`); + outputHandler(command, spawned.stdout, spawned.stderr, [...args]); + } + this._plugins.exec("spawn.after", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + spawned, + close(exitCode, reason) { + done({ + stdOut, + stdErr, + exitCode, + rejection: rejection || reason + }); + }, + kill(reason) { + if (spawned.killed) { + return; + } + rejection = reason; + spawned.kill("SIGINT"); + } + })); + }); + }); + } + _beforeSpawn(task, args) { + let rejection; + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + return rejection; + } + }; + } +}); + +// src/lib/runners/git-executor.ts +var git_executor_exports = {}; +__export(git_executor_exports, { + GitExecutor: () => GitExecutor +}); +var GitExecutor; +var init_git_executor = __esm({ + "src/lib/runners/git-executor.ts"() { + "use strict"; + init_git_executor_chain(); + GitExecutor = class { + constructor(cwd, _scheduler, _plugins) { + this.cwd = cwd; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = new GitExecutorChain(this, this._scheduler, this._plugins); + } + chain() { + return new GitExecutorChain(this, this._scheduler, this._plugins); + } + push(task) { + return this._chain.push(task); + } + }; + } +}); + +// src/lib/task-callback.ts +function taskCallback(task, response, callback = NOOP) { + const onSuccess = (data) => { + callback(null, data); + }; + const onError2 = (err) => { + if ((err == null ? void 0 : err.task) === task) { + callback( + err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err, + void 0 + ); + } + }; + response.then(onSuccess, onError2); +} +function addDeprecationNoticeToError(err) { + let log = (name) => { + console.warn( + `simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3` + ); + log = NOOP; + }; + return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {})); + function descriptorReducer(all, name) { + if (name in err) { + return all; + } + all[name] = { + enumerable: false, + configurable: false, + get() { + log(name); + return err.git[name]; + } + }; + return all; + } +} +var init_task_callback = __esm({ + "src/lib/task-callback.ts"() { + "use strict"; + init_git_response_error(); + init_utils(); + } +}); + +// src/lib/tasks/change-working-directory.ts +function changeWorkingDirectoryTask(directory, root) { + return adhocExecTask((instance) => { + if (!folderExists(directory)) { + throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`); + } + return (root || instance).cwd = directory; + }); +} +var init_change_working_directory = __esm({ + "src/lib/tasks/change-working-directory.ts"() { + "use strict"; + init_utils(); + init_task(); + } +}); + +// src/lib/tasks/checkout.ts +function checkoutTask(args) { + const commands = ["checkout", ...args]; + if (commands[1] === "-b" && commands.includes("-B")) { + commands[1] = remove(commands, "-B"); + } + return straightThroughStringTask(commands); +} +function checkout_default() { + return { + checkout() { + return this._runTask( + checkoutTask(getTrailingOptions(arguments, 1)), + trailingFunctionArgument(arguments) + ); + }, + checkoutBranch(branchName, startPoint) { + return this._runTask( + checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]), + trailingFunctionArgument(arguments) + ); + }, + checkoutLocalBranch(branchName) { + return this._runTask( + checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]), + trailingFunctionArgument(arguments) + ); + } + }; +} +var init_checkout = __esm({ + "src/lib/tasks/checkout.ts"() { + "use strict"; + init_utils(); + init_task(); + } +}); + +// src/lib/parsers/parse-commit.ts +function parseCommitResult(stdOut) { + const result = { + author: null, + branch: "", + commit: "", + root: false, + summary: { + changes: 0, + insertions: 0, + deletions: 0 + } + }; + return parseStringResponse(result, parsers, stdOut); +} +var parsers; +var init_parse_commit = __esm({ + "src/lib/parsers/parse-commit.ts"() { + "use strict"; + init_utils(); + parsers = [ + new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch, root, commit]) => { + result.branch = branch; + result.commit = commit; + result.root = !!root; + }), + new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => { + const parts = author.split("<"); + const email = parts.pop(); + if (!email || !email.includes("@")) { + return; + } + result.author = { + email: email.substr(0, email.length - 1), + name: parts.join("<").trim() + }; + }), + new LineParser( + /(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g, + (result, [changes, insertions, deletions]) => { + result.summary.changes = parseInt(changes, 10) || 0; + result.summary.insertions = parseInt(insertions, 10) || 0; + result.summary.deletions = parseInt(deletions, 10) || 0; + } + ), + new LineParser( + /^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/, + (result, [changes, lines, direction]) => { + result.summary.changes = parseInt(changes, 10) || 0; + const count = parseInt(lines, 10) || 0; + if (direction === "-") { + result.summary.deletions = count; + } else if (direction === "+") { + result.summary.insertions = count; + } + } + ) + ]; + } +}); + +// src/lib/tasks/commit.ts +function commitTask(message, files, customArgs) { + const commands = [ + "-c", + "core.abbrev=40", + "commit", + ...prefixedArray(message, "-m"), + ...files, + ...customArgs + ]; + return { + commands, + format: "utf-8", + parser: parseCommitResult + }; +} +function commit_default() { + return { + commit(message, ...rest) { + const next = trailingFunctionArgument(arguments); + const task = rejectDeprecatedSignatures(message) || commitTask( + asArray(message), + asArray(filterType(rest[0], filterStringOrStringArray, [])), + [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)] + ); + return this._runTask(task, next); + } + }; + function rejectDeprecatedSignatures(message) { + return !filterStringOrStringArray(message) && configurationErrorTask( + `git.commit: requires the commit message to be supplied as a string/string[]` + ); + } +} +var init_commit = __esm({ + "src/lib/tasks/commit.ts"() { + "use strict"; + init_parse_commit(); + init_utils(); + init_task(); + } +}); + +// src/lib/tasks/first-commit.ts +function first_commit_default() { + return { + firstCommit() { + return this._runTask( + straightThroughStringTask(["rev-list", "--max-parents=0", "HEAD"], true), + trailingFunctionArgument(arguments) + ); + } + }; +} +var init_first_commit = __esm({ + "src/lib/tasks/first-commit.ts"() { + "use strict"; + init_utils(); + init_task(); + } +}); + +// src/lib/tasks/hash-object.ts +function hashObjectTask(filePath, write) { + const commands = ["hash-object", filePath]; + if (write) { + commands.push("-w"); + } + return straightThroughStringTask(commands, true); +} +var init_hash_object = __esm({ + "src/lib/tasks/hash-object.ts"() { + "use strict"; + init_task(); + } +}); + +// src/lib/responses/InitSummary.ts +function parseInit(bare, path, text) { + const response = String(text).trim(); + let result; + if (result = initResponseRegex.exec(response)) { + return new InitSummary(bare, path, false, result[1]); + } + if (result = reInitResponseRegex.exec(response)) { + return new InitSummary(bare, path, true, result[1]); + } + let gitDir = ""; + const tokens = response.split(" "); + while (tokens.length) { + const token = tokens.shift(); + if (token === "in") { + gitDir = tokens.join(" "); + break; + } + } + return new InitSummary(bare, path, /^re/i.test(response), gitDir); +} +var InitSummary, initResponseRegex, reInitResponseRegex; +var init_InitSummary = __esm({ + "src/lib/responses/InitSummary.ts"() { + "use strict"; + InitSummary = class { + constructor(bare, path, existing, gitDir) { + this.bare = bare; + this.path = path; + this.existing = existing; + this.gitDir = gitDir; + } + }; + initResponseRegex = /^Init.+ repository in (.+)$/; + reInitResponseRegex = /^Rein.+ in (.+)$/; + } +}); + +// src/lib/tasks/init.ts +function hasBareCommand(command) { + return command.includes(bareCommand); +} +function initTask(bare = false, path, customArgs) { + const commands = ["init", ...customArgs]; + if (bare && !hasBareCommand(commands)) { + commands.splice(1, 0, bareCommand); + } + return { + commands, + format: "utf-8", + parser(text) { + return parseInit(commands.includes("--bare"), path, text); + } + }; +} +var bareCommand; +var init_init = __esm({ + "src/lib/tasks/init.ts"() { + "use strict"; + init_InitSummary(); + bareCommand = "--bare"; + } +}); + +// src/lib/args/log-format.ts +function logFormatFromCommand(customArgs) { + for (let i = 0; i < customArgs.length; i++) { + const format = logFormatRegex.exec(customArgs[i]); + if (format) { + return `--${format[1]}`; + } + } + return "" /* NONE */; +} +function isLogFormat(customArg) { + return logFormatRegex.test(customArg); +} +var logFormatRegex; +var init_log_format = __esm({ + "src/lib/args/log-format.ts"() { + "use strict"; + logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/; + } +}); + +// src/lib/responses/DiffSummary.ts +var DiffSummary; +var init_DiffSummary = __esm({ + "src/lib/responses/DiffSummary.ts"() { + "use strict"; + DiffSummary = class { + constructor() { + this.changed = 0; + this.deletions = 0; + this.insertions = 0; + this.files = []; + } + }; + } +}); + +// src/lib/parsers/parse-diff-summary.ts +function getDiffParser(format = "" /* NONE */) { + const parser3 = diffSummaryParsers[format]; + return (stdOut) => parseStringResponse(new DiffSummary(), parser3, stdOut, false); +} +var statParser, numStatParser, nameOnlyParser, nameStatusParser, diffSummaryParsers; +var init_parse_diff_summary = __esm({ + "src/lib/parsers/parse-diff-summary.ts"() { + "use strict"; + init_log_format(); + init_DiffSummary(); + init_diff_name_status(); + init_utils(); + statParser = [ + new LineParser( + /^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/, + (result, [file, changes, alterations = ""]) => { + result.files.push({ + file: file.trim(), + changes: asNumber(changes), + insertions: alterations.replace(/[^+]/g, "").length, + deletions: alterations.replace(/[^-]/g, "").length, + binary: false + }); + } + ), + new LineParser( + /^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/, + (result, [file, before, after]) => { + result.files.push({ + file: file.trim(), + before: asNumber(before), + after: asNumber(after), + binary: true + }); + } + ), + new LineParser( + /(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/, + (result, [changed, summary]) => { + const inserted = /(\d+) i/.exec(summary); + const deleted = /(\d+) d/.exec(summary); + result.changed = asNumber(changed); + result.insertions = asNumber(inserted == null ? void 0 : inserted[1]); + result.deletions = asNumber(deleted == null ? void 0 : deleted[1]); + } + ) + ]; + numStatParser = [ + new LineParser( + /(\d+)\t(\d+)\t(.+)$/, + (result, [changesInsert, changesDelete, file]) => { + const insertions = asNumber(changesInsert); + const deletions = asNumber(changesDelete); + result.changed++; + result.insertions += insertions; + result.deletions += deletions; + result.files.push({ + file, + changes: insertions + deletions, + insertions, + deletions, + binary: false + }); + } + ), + new LineParser(/-\t-\t(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + after: 0, + before: 0, + binary: true + }); + }) + ]; + nameOnlyParser = [ + new LineParser(/(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + changes: 0, + insertions: 0, + deletions: 0, + binary: false + }); + }) + ]; + nameStatusParser = [ + new LineParser( + /([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/, + (result, [status, _similarity, from, _to, to]) => { + result.changed++; + result.files.push({ + file: to != null ? to : from, + changes: 0, + status: orVoid(isDiffNameStatus(status) && status), + insertions: 0, + deletions: 0, + binary: false + }); + } + ) + ]; + diffSummaryParsers = { + ["" /* NONE */]: statParser, + ["--stat" /* STAT */]: statParser, + ["--numstat" /* NUM_STAT */]: numStatParser, + ["--name-status" /* NAME_STATUS */]: nameStatusParser, + ["--name-only" /* NAME_ONLY */]: nameOnlyParser + }; + } +}); + +// src/lib/parsers/parse-list-log-summary.ts +function lineBuilder(tokens, fields) { + return fields.reduce( + (line, field, index) => { + line[field] = tokens[index] || ""; + return line; + }, + /* @__PURE__ */ Object.create({ diff: null }) + ); +} +function createListLogSummaryParser(splitter = SPLITTER, fields = defaultFieldNames, logFormat = "" /* NONE */) { + const parseDiffResult = getDiffParser(logFormat); + return function(stdOut) { + const all = toLinesWithContent( + stdOut, + true, + START_BOUNDARY + ).map(function(item) { + const lineDetail = item.trim().split(COMMIT_BOUNDARY); + const listLogLine = lineBuilder( + lineDetail[0].trim().split(splitter), + fields + ); + if (lineDetail.length > 1 && !!lineDetail[1].trim()) { + listLogLine.diff = parseDiffResult(lineDetail[1]); + } + return listLogLine; + }); + return { + all, + latest: all.length && all[0] || null, + total: all.length + }; + }; +} +var START_BOUNDARY, COMMIT_BOUNDARY, SPLITTER, defaultFieldNames; +var init_parse_list_log_summary = __esm({ + "src/lib/parsers/parse-list-log-summary.ts"() { + "use strict"; + init_utils(); + init_parse_diff_summary(); + init_log_format(); + START_BOUNDARY = "\xF2\xF2\xF2\xF2\xF2\xF2 "; + COMMIT_BOUNDARY = " \xF2\xF2"; + SPLITTER = " \xF2 "; + defaultFieldNames = ["hash", "date", "message", "refs", "author_name", "author_email"]; + } +}); + +// src/lib/tasks/diff.ts +var diff_exports = {}; +__export(diff_exports, { + diffSummaryTask: () => diffSummaryTask, + validateLogFormatConfig: () => validateLogFormatConfig +}); +function diffSummaryTask(customArgs) { + let logFormat = logFormatFromCommand(customArgs); + const commands = ["diff"]; + if (logFormat === "" /* NONE */) { + logFormat = "--stat" /* STAT */; + commands.push("--stat=4096"); + } + commands.push(...customArgs); + return validateLogFormatConfig(commands) || { + commands, + format: "utf-8", + parser: getDiffParser(logFormat) + }; +} +function validateLogFormatConfig(customArgs) { + const flags = customArgs.filter(isLogFormat); + if (flags.length > 1) { + return configurationErrorTask( + `Summary flags are mutually exclusive - pick one of ${flags.join(",")}` + ); + } + if (flags.length && customArgs.includes("-z")) { + return configurationErrorTask( + `Summary flag ${flags} parsing is not compatible with null termination option '-z'` + ); + } +} +var init_diff = __esm({ + "src/lib/tasks/diff.ts"() { + "use strict"; + init_log_format(); + init_parse_diff_summary(); + init_task(); + } +}); + +// src/lib/tasks/log.ts +function prettyFormat(format, splitter) { + const fields = []; + const formatStr = []; + Object.keys(format).forEach((field) => { + fields.push(field); + formatStr.push(String(format[field])); + }); + return [fields, formatStr.join(splitter)]; +} +function userOptions(input) { + return Object.keys(input).reduce((out, key) => { + if (!(key in excludeOptions)) { + out[key] = input[key]; + } + return out; + }, {}); +} +function parseLogOptions(opt = {}, customArgs = []) { + const splitter = filterType(opt.splitter, filterString, SPLITTER); + const format = !filterPrimitives(opt.format) && opt.format ? opt.format : { + hash: "%H", + date: opt.strictDate === false ? "%ai" : "%aI", + message: "%s", + refs: "%D", + body: opt.multiLine ? "%B" : "%b", + author_name: opt.mailMap !== false ? "%aN" : "%an", + author_email: opt.mailMap !== false ? "%aE" : "%ae" + }; + const [fields, formatStr] = prettyFormat(format, splitter); + const suffix = []; + const command = [ + `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`, + ...customArgs + ]; + const maxCount = opt.n || opt["max-count"] || opt.maxCount; + if (maxCount) { + command.push(`--max-count=${maxCount}`); + } + if (opt.from || opt.to) { + const rangeOperator = opt.symmetric !== false ? "..." : ".."; + suffix.push(`${opt.from || ""}${rangeOperator}${opt.to || ""}`); + } + if (filterString(opt.file)) { + command.push("--follow", pathspec(opt.file)); + } + appendTaskOptions(userOptions(opt), command); + return { + fields, + splitter, + commands: [...command, ...suffix] + }; +} +function logTask(splitter, fields, customArgs) { + const parser3 = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs)); + return { + commands: ["log", ...customArgs], + format: "utf-8", + parser: parser3 + }; +} +function log_default() { + return { + log(...rest) { + const next = trailingFunctionArgument(arguments); + const options = parseLogOptions( + trailingOptionsArgument(arguments), + filterType(arguments[0], filterArray) + ); + const task = rejectDeprecatedSignatures(...rest) || validateLogFormatConfig(options.commands) || createLogTask(options); + return this._runTask(task, next); + } + }; + function createLogTask(options) { + return logTask(options.splitter, options.fields, options.commands); + } + function rejectDeprecatedSignatures(from, to) { + return filterString(from) && filterString(to) && configurationErrorTask( + `git.log(string, string) should be replaced with git.log({ from: string, to: string })` + ); + } +} +var excludeOptions; +var init_log = __esm({ + "src/lib/tasks/log.ts"() { + "use strict"; + init_log_format(); + init_pathspec(); + init_parse_list_log_summary(); + init_utils(); + init_task(); + init_diff(); + excludeOptions = /* @__PURE__ */ ((excludeOptions2) => { + excludeOptions2[excludeOptions2["--pretty"] = 0] = "--pretty"; + excludeOptions2[excludeOptions2["max-count"] = 1] = "max-count"; + excludeOptions2[excludeOptions2["maxCount"] = 2] = "maxCount"; + excludeOptions2[excludeOptions2["n"] = 3] = "n"; + excludeOptions2[excludeOptions2["file"] = 4] = "file"; + excludeOptions2[excludeOptions2["format"] = 5] = "format"; + excludeOptions2[excludeOptions2["from"] = 6] = "from"; + excludeOptions2[excludeOptions2["to"] = 7] = "to"; + excludeOptions2[excludeOptions2["splitter"] = 8] = "splitter"; + excludeOptions2[excludeOptions2["symmetric"] = 9] = "symmetric"; + excludeOptions2[excludeOptions2["mailMap"] = 10] = "mailMap"; + excludeOptions2[excludeOptions2["multiLine"] = 11] = "multiLine"; + excludeOptions2[excludeOptions2["strictDate"] = 12] = "strictDate"; + return excludeOptions2; + })(excludeOptions || {}); + } +}); + +// src/lib/responses/MergeSummary.ts +var MergeSummaryConflict, MergeSummaryDetail; +var init_MergeSummary = __esm({ + "src/lib/responses/MergeSummary.ts"() { + "use strict"; + MergeSummaryConflict = class { + constructor(reason, file = null, meta) { + this.reason = reason; + this.file = file; + this.meta = meta; + } + toString() { + return `${this.file}:${this.reason}`; + } + }; + MergeSummaryDetail = class { + constructor() { + this.conflicts = []; + this.merges = []; + this.result = "success"; + } + get failed() { + return this.conflicts.length > 0; + } + get reason() { + return this.result; + } + toString() { + if (this.conflicts.length) { + return `CONFLICTS: ${this.conflicts.join(", ")}`; + } + return "OK"; + } + }; + } +}); + +// src/lib/responses/PullSummary.ts +var PullSummary, PullFailedSummary; +var init_PullSummary = __esm({ + "src/lib/responses/PullSummary.ts"() { + "use strict"; + PullSummary = class { + constructor() { + this.remoteMessages = { + all: [] + }; + this.created = []; + this.deleted = []; + this.files = []; + this.deletions = {}; + this.insertions = {}; + this.summary = { + changes: 0, + deletions: 0, + insertions: 0 + }; + } + }; + PullFailedSummary = class { + constructor() { + this.remote = ""; + this.hash = { + local: "", + remote: "" + }; + this.branch = { + local: "", + remote: "" + }; + this.message = ""; + } + toString() { + return this.message; + } + }; + } +}); + +// src/lib/parsers/parse-remote-objects.ts +function objectEnumerationResult(remoteMessages) { + return remoteMessages.objects = remoteMessages.objects || { + compressing: 0, + counting: 0, + enumerating: 0, + packReused: 0, + reused: { count: 0, delta: 0 }, + total: { count: 0, delta: 0 } + }; +} +function asObjectCount(source) { + const count = /^\s*(\d+)/.exec(source); + const delta = /delta (\d+)/i.exec(source); + return { + count: asNumber(count && count[1] || "0"), + delta: asNumber(delta && delta[1] || "0") + }; +} +var remoteMessagesObjectParsers; +var init_parse_remote_objects = __esm({ + "src/lib/parsers/parse-remote-objects.ts"() { + "use strict"; + init_utils(); + remoteMessagesObjectParsers = [ + new RemoteLineParser( + /^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i, + (result, [action, count]) => { + const key = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key]: asNumber(count) }); + } + ), + new RemoteLineParser( + /^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i, + (result, [action, count]) => { + const key = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key]: asNumber(count) }); + } + ), + new RemoteLineParser( + /total ([^,]+), reused ([^,]+), pack-reused (\d+)/i, + (result, [total, reused, packReused]) => { + const objects = objectEnumerationResult(result.remoteMessages); + objects.total = asObjectCount(total); + objects.reused = asObjectCount(reused); + objects.packReused = asNumber(packReused); + } + ) + ]; + } +}); + +// src/lib/parsers/parse-remote-messages.ts +function parseRemoteMessages(_stdOut, stdErr) { + return parseStringResponse({ remoteMessages: new RemoteMessageSummary() }, parsers2, stdErr); +} +var parsers2, RemoteMessageSummary; +var init_parse_remote_messages = __esm({ + "src/lib/parsers/parse-remote-messages.ts"() { + "use strict"; + init_utils(); + init_parse_remote_objects(); + parsers2 = [ + new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text]) => { + result.remoteMessages.all.push(text.trim()); + return false; + }), + ...remoteMessagesObjectParsers, + new RemoteLineParser( + [/create a (?:pull|merge) request/i, /\s(https?:\/\/\S+)$/], + (result, [pullRequestUrl]) => { + result.remoteMessages.pullRequestUrl = pullRequestUrl; + } + ), + new RemoteLineParser( + [/found (\d+) vulnerabilities.+\(([^)]+)\)/i, /\s(https?:\/\/\S+)$/], + (result, [count, summary, url]) => { + result.remoteMessages.vulnerabilities = { + count: asNumber(count), + summary, + url + }; + } + ) + ]; + RemoteMessageSummary = class { + constructor() { + this.all = []; + } + }; + } +}); + +// src/lib/parsers/parse-pull.ts +function parsePullErrorResult(stdOut, stdErr) { + const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]); + return pullError.message && pullError; +} +var FILE_UPDATE_REGEX, SUMMARY_REGEX, ACTION_REGEX, parsers3, errorParsers, parsePullDetail, parsePullResult; +var init_parse_pull = __esm({ + "src/lib/parsers/parse-pull.ts"() { + "use strict"; + init_PullSummary(); + init_utils(); + init_parse_remote_messages(); + FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/; + SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/; + ACTION_REGEX = /^(create|delete) mode \d+ (.+)/; + parsers3 = [ + new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => { + result.files.push(file); + if (insertions) { + result.insertions[file] = insertions.length; + } + if (deletions) { + result.deletions[file] = deletions.length; + } + }), + new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => { + if (insertions !== void 0 || deletions !== void 0) { + result.summary.changes = +changes || 0; + result.summary.insertions = +insertions || 0; + result.summary.deletions = +deletions || 0; + return true; + } + return false; + }), + new LineParser(ACTION_REGEX, (result, [action, file]) => { + append(result.files, file); + append(action === "create" ? result.created : result.deleted, file); + }) + ]; + errorParsers = [ + new LineParser(/^from\s(.+)$/i, (result, [remote]) => void (result.remote = remote)), + new LineParser(/^fatal:\s(.+)$/, (result, [message]) => void (result.message = message)), + new LineParser( + /([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/, + (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => { + result.branch.local = branchLocal; + result.hash.local = hashLocal; + result.branch.remote = branchRemote; + result.hash.remote = hashRemote; + } + ) + ]; + parsePullDetail = (stdOut, stdErr) => { + return parseStringResponse(new PullSummary(), parsers3, [stdOut, stdErr]); + }; + parsePullResult = (stdOut, stdErr) => { + return Object.assign( + new PullSummary(), + parsePullDetail(stdOut, stdErr), + parseRemoteMessages(stdOut, stdErr) + ); + }; + } +}); + +// src/lib/parsers/parse-merge.ts +var parsers4, parseMergeResult, parseMergeDetail; +var init_parse_merge = __esm({ + "src/lib/parsers/parse-merge.ts"() { + "use strict"; + init_MergeSummary(); + init_utils(); + init_parse_pull(); + parsers4 = [ + new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => { + summary.merges.push(autoMerge); + }), + new LineParser(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/, (summary, [reason, file]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file)); + }), + new LineParser( + /^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/, + (summary, [reason, file, deleteRef]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef })); + } + ), + new LineParser(/^CONFLICT\s+\((.+)\):/, (summary, [reason]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, null)); + }), + new LineParser(/^Automatic merge failed;\s+(.+)$/, (summary, [result]) => { + summary.result = result; + }) + ]; + parseMergeResult = (stdOut, stdErr) => { + return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr)); + }; + parseMergeDetail = (stdOut) => { + return parseStringResponse(new MergeSummaryDetail(), parsers4, stdOut); + }; + } +}); + +// src/lib/tasks/merge.ts +function mergeTask(customArgs) { + if (!customArgs.length) { + return configurationErrorTask("Git.merge requires at least one option"); + } + return { + commands: ["merge", ...customArgs], + format: "utf-8", + parser(stdOut, stdErr) { + const merge = parseMergeResult(stdOut, stdErr); + if (merge.failed) { + throw new GitResponseError(merge); + } + return merge; + } + }; +} +var init_merge = __esm({ + "src/lib/tasks/merge.ts"() { + "use strict"; + init_git_response_error(); + init_parse_merge(); + init_task(); + } +}); + +// src/lib/parsers/parse-push.ts +function pushResultPushedItem(local, remote, status) { + const deleted = status.includes("deleted"); + const tag = status.includes("tag") || /^refs\/tags/.test(local); + const alreadyUpdated = !status.includes("new"); + return { + deleted, + tag, + branch: !tag, + new: !alreadyUpdated, + alreadyUpdated, + local, + remote + }; +} +var parsers5, parsePushResult, parsePushDetail; +var init_parse_push = __esm({ + "src/lib/parsers/parse-push.ts"() { + "use strict"; + init_utils(); + init_parse_remote_messages(); + parsers5 = [ + new LineParser(/^Pushing to (.+)$/, (result, [repo]) => { + result.repo = repo; + }), + new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => { + result.ref = __spreadProps(__spreadValues({}, result.ref || {}), { + local + }); + }), + new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => { + result.pushed.push(pushResultPushedItem(local, remote, type)); + }), + new LineParser( + /^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/, + (result, [local, remote, remoteName]) => { + result.branch = __spreadProps(__spreadValues({}, result.branch || {}), { + local, + remote, + remoteName + }); + } + ), + new LineParser( + /^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/, + (result, [local, remote, from, to]) => { + result.update = { + head: { + local, + remote + }, + hash: { + from, + to + } + }; + } + ) + ]; + parsePushResult = (stdOut, stdErr) => { + const pushDetail = parsePushDetail(stdOut, stdErr); + const responseDetail = parseRemoteMessages(stdOut, stdErr); + return __spreadValues(__spreadValues({}, pushDetail), responseDetail); + }; + parsePushDetail = (stdOut, stdErr) => { + return parseStringResponse({ pushed: [] }, parsers5, [stdOut, stdErr]); + }; + } +}); + +// src/lib/tasks/push.ts +var push_exports = {}; +__export(push_exports, { + pushTagsTask: () => pushTagsTask, + pushTask: () => pushTask +}); +function pushTagsTask(ref = {}, customArgs) { + append(customArgs, "--tags"); + return pushTask(ref, customArgs); +} +function pushTask(ref = {}, customArgs) { + const commands = ["push", ...customArgs]; + if (ref.branch) { + commands.splice(1, 0, ref.branch); + } + if (ref.remote) { + commands.splice(1, 0, ref.remote); + } + remove(commands, "-v"); + append(commands, "--verbose"); + append(commands, "--porcelain"); + return { + commands, + format: "utf-8", + parser: parsePushResult + }; +} +var init_push = __esm({ + "src/lib/tasks/push.ts"() { + "use strict"; + init_parse_push(); + init_utils(); + } +}); + +// src/lib/tasks/show.ts +function show_default() { + return { + showBuffer() { + const commands = ["show", ...getTrailingOptions(arguments, 1)]; + if (!commands.includes("--binary")) { + commands.splice(1, 0, "--binary"); + } + return this._runTask( + straightThroughBufferTask(commands), + trailingFunctionArgument(arguments) + ); + }, + show() { + const commands = ["show", ...getTrailingOptions(arguments, 1)]; + return this._runTask( + straightThroughStringTask(commands), + trailingFunctionArgument(arguments) + ); + } + }; +} +var init_show = __esm({ + "src/lib/tasks/show.ts"() { + "use strict"; + init_utils(); + init_task(); + } +}); + +// src/lib/responses/FileStatusSummary.ts +var fromPathRegex, FileStatusSummary; +var init_FileStatusSummary = __esm({ + "src/lib/responses/FileStatusSummary.ts"() { + "use strict"; + fromPathRegex = /^(.+) -> (.+)$/; + FileStatusSummary = class { + constructor(path, index, working_dir) { + this.path = path; + this.index = index; + this.working_dir = working_dir; + if ("R" === index + working_dir) { + const detail = fromPathRegex.exec(path) || [null, path, path]; + this.from = detail[1] || ""; + this.path = detail[2] || ""; + } + } + }; + } +}); + +// src/lib/responses/StatusSummary.ts +function renamedFile(line) { + const [to, from] = line.split(NULL); + return { + from: from || to, + to + }; +} +function parser2(indexX, indexY, handler) { + return [`${indexX}${indexY}`, handler]; +} +function conflicts(indexX, ...indexY) { + return indexY.map((y) => parser2(indexX, y, (result, file) => append(result.conflicted, file))); +} +function splitLine(result, lineStr) { + const trimmed2 = lineStr.trim(); + switch (" ") { + case trimmed2.charAt(2): + return data(trimmed2.charAt(0), trimmed2.charAt(1), trimmed2.substr(3)); + case trimmed2.charAt(1): + return data(" " /* NONE */, trimmed2.charAt(0), trimmed2.substr(2)); + default: + return; + } + function data(index, workingDir, path) { + const raw = `${index}${workingDir}`; + const handler = parsers6.get(raw); + if (handler) { + handler(result, path); + } + if (raw !== "##" && raw !== "!!") { + result.files.push(new FileStatusSummary(path.replace(/\0.+$/, ""), index, workingDir)); + } + } +} +var StatusSummary, parsers6, parseStatusSummary; +var init_StatusSummary = __esm({ + "src/lib/responses/StatusSummary.ts"() { + "use strict"; + init_utils(); + init_FileStatusSummary(); + StatusSummary = class { + constructor() { + this.not_added = []; + this.conflicted = []; + this.created = []; + this.deleted = []; + this.ignored = void 0; + this.modified = []; + this.renamed = []; + this.files = []; + this.staged = []; + this.ahead = 0; + this.behind = 0; + this.current = null; + this.tracking = null; + this.detached = false; + this.isClean = () => { + return !this.files.length; + }; + } + }; + parsers6 = new Map([ + parser2( + " " /* NONE */, + "A" /* ADDED */, + (result, file) => append(result.created, file) + ), + parser2( + " " /* NONE */, + "D" /* DELETED */, + (result, file) => append(result.deleted, file) + ), + parser2( + " " /* NONE */, + "M" /* MODIFIED */, + (result, file) => append(result.modified, file) + ), + parser2( + "A" /* ADDED */, + " " /* NONE */, + (result, file) => append(result.created, file) && append(result.staged, file) + ), + parser2( + "A" /* ADDED */, + "M" /* MODIFIED */, + (result, file) => append(result.created, file) && append(result.staged, file) && append(result.modified, file) + ), + parser2( + "D" /* DELETED */, + " " /* NONE */, + (result, file) => append(result.deleted, file) && append(result.staged, file) + ), + parser2( + "M" /* MODIFIED */, + " " /* NONE */, + (result, file) => append(result.modified, file) && append(result.staged, file) + ), + parser2( + "M" /* MODIFIED */, + "M" /* MODIFIED */, + (result, file) => append(result.modified, file) && append(result.staged, file) + ), + parser2("R" /* RENAMED */, " " /* NONE */, (result, file) => { + append(result.renamed, renamedFile(file)); + }), + parser2("R" /* RENAMED */, "M" /* MODIFIED */, (result, file) => { + const renamed = renamedFile(file); + append(result.renamed, renamed); + append(result.modified, renamed.to); + }), + parser2("!" /* IGNORED */, "!" /* IGNORED */, (_result, _file) => { + append(_result.ignored = _result.ignored || [], _file); + }), + parser2( + "?" /* UNTRACKED */, + "?" /* UNTRACKED */, + (result, file) => append(result.not_added, file) + ), + ...conflicts("A" /* ADDED */, "A" /* ADDED */, "U" /* UNMERGED */), + ...conflicts( + "D" /* DELETED */, + "D" /* DELETED */, + "U" /* UNMERGED */ + ), + ...conflicts( + "U" /* UNMERGED */, + "A" /* ADDED */, + "D" /* DELETED */, + "U" /* UNMERGED */ + ), + [ + "##", + (result, line) => { + const aheadReg = /ahead (\d+)/; + const behindReg = /behind (\d+)/; + const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/; + const trackingReg = /\.{3}(\S*)/; + const onEmptyBranchReg = /\son\s([\S]+)$/; + let regexResult; + regexResult = aheadReg.exec(line); + result.ahead = regexResult && +regexResult[1] || 0; + regexResult = behindReg.exec(line); + result.behind = regexResult && +regexResult[1] || 0; + regexResult = currentReg.exec(line); + result.current = regexResult && regexResult[1]; + regexResult = trackingReg.exec(line); + result.tracking = regexResult && regexResult[1]; + regexResult = onEmptyBranchReg.exec(line); + result.current = regexResult && regexResult[1] || result.current; + result.detached = /\(no branch\)/.test(line); + } + ] + ]); + parseStatusSummary = function(text) { + const lines = text.split(NULL); + const status = new StatusSummary(); + for (let i = 0, l = lines.length; i < l; ) { + let line = lines[i++].trim(); + if (!line) { + continue; + } + if (line.charAt(0) === "R" /* RENAMED */) { + line += NULL + (lines[i++] || ""); + } + splitLine(status, line); + } + return status; + }; + } +}); + +// src/lib/tasks/status.ts +function statusTask(customArgs) { + const commands = [ + "status", + "--porcelain", + "-b", + "-u", + "--null", + ...customArgs.filter((arg) => !ignoredOptions.includes(arg)) + ]; + return { + format: "utf-8", + commands, + parser(text) { + return parseStatusSummary(text); + } + }; +} +var ignoredOptions; +var init_status = __esm({ + "src/lib/tasks/status.ts"() { + "use strict"; + init_StatusSummary(); + ignoredOptions = ["--null", "-z"]; + } +}); + +// src/lib/tasks/version.ts +function versionResponse(major = 0, minor = 0, patch = 0, agent = "", installed = true) { + return Object.defineProperty( + { + major, + minor, + patch, + agent, + installed + }, + "toString", + { + value() { + return `${this.major}.${this.minor}.${this.patch}`; + }, + configurable: false, + enumerable: false + } + ); +} +function notInstalledResponse() { + return versionResponse(0, 0, 0, "", false); +} +function version_default() { + return { + version() { + return this._runTask({ + commands: ["--version"], + format: "utf-8", + parser: versionParser, + onError(result, error, done, fail) { + if (result.exitCode === -2 /* NOT_FOUND */) { + return done(Buffer.from(NOT_INSTALLED)); + } + fail(error); + } + }); + } + }; +} +function versionParser(stdOut) { + if (stdOut === NOT_INSTALLED) { + return notInstalledResponse(); + } + return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers7, stdOut); +} +var NOT_INSTALLED, parsers7; +var init_version = __esm({ + "src/lib/tasks/version.ts"() { + "use strict"; + init_utils(); + NOT_INSTALLED = "installed=false"; + parsers7 = [ + new LineParser( + /version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/, + (result, [major, minor, patch, agent = ""]) => { + Object.assign( + result, + versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent) + ); + } + ), + new LineParser( + /version (\d+)\.(\d+)\.(\D+)(.+)?$/, + (result, [major, minor, patch, agent = ""]) => { + Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent)); + } + ) + ]; + } +}); + +// src/lib/simple-git-api.ts +var simple_git_api_exports = {}; +__export(simple_git_api_exports, { + SimpleGitApi: () => SimpleGitApi +}); +var SimpleGitApi; +var init_simple_git_api = __esm({ + "src/lib/simple-git-api.ts"() { + "use strict"; + init_task_callback(); + init_change_working_directory(); + init_checkout(); + init_commit(); + init_config(); + init_first_commit(); + init_grep(); + init_hash_object(); + init_init(); + init_log(); + init_merge(); + init_push(); + init_show(); + init_status(); + init_task(); + init_version(); + init_utils(); + SimpleGitApi = class { + constructor(_executor) { + this._executor = _executor; + } + _runTask(task, then) { + const chain = this._executor.chain(); + const promise = chain.push(task); + if (then) { + taskCallback(task, promise, then); + } + return Object.create(this, { + then: { value: promise.then.bind(promise) }, + catch: { value: promise.catch.bind(promise) }, + _executor: { value: chain } + }); + } + add(files) { + return this._runTask( + straightThroughStringTask(["add", ...asArray(files)]), + trailingFunctionArgument(arguments) + ); + } + cwd(directory) { + const next = trailingFunctionArgument(arguments); + if (typeof directory === "string") { + return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next); + } + if (typeof (directory == null ? void 0 : directory.path) === "string") { + return this._runTask( + changeWorkingDirectoryTask( + directory.path, + directory.root && this._executor || void 0 + ), + next + ); + } + return this._runTask( + configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"), + next + ); + } + hashObject(path, write) { + return this._runTask( + hashObjectTask(path, write === true), + trailingFunctionArgument(arguments) + ); + } + init(bare) { + return this._runTask( + initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)), + trailingFunctionArgument(arguments) + ); + } + merge() { + return this._runTask( + mergeTask(getTrailingOptions(arguments)), + trailingFunctionArgument(arguments) + ); + } + mergeFromTo(remote, branch) { + if (!(filterString(remote) && filterString(branch))) { + return this._runTask( + configurationErrorTask( + `Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings` + ) + ); + } + return this._runTask( + mergeTask([remote, branch, ...getTrailingOptions(arguments)]), + trailingFunctionArgument(arguments, false) + ); + } + outputHandler(handler) { + this._executor.outputHandler = handler; + return this; + } + push() { + const task = pushTask( + { + remote: filterType(arguments[0], filterString), + branch: filterType(arguments[1], filterString) + }, + getTrailingOptions(arguments) + ); + return this._runTask(task, trailingFunctionArgument(arguments)); + } + stash() { + return this._runTask( + straightThroughStringTask(["stash", ...getTrailingOptions(arguments)]), + trailingFunctionArgument(arguments) + ); + } + status() { + return this._runTask( + statusTask(getTrailingOptions(arguments)), + trailingFunctionArgument(arguments) + ); + } + }; + Object.assign( + SimpleGitApi.prototype, + checkout_default(), + commit_default(), + config_default(), + first_commit_default(), + grep_default(), + log_default(), + show_default(), + version_default() + ); + } +}); + +// src/lib/runners/scheduler.ts +var scheduler_exports = {}; +__export(scheduler_exports, { + Scheduler: () => Scheduler +}); +import { createDeferred } from "@kwsites/promise-deferred"; +var createScheduledTask, Scheduler; +var init_scheduler = __esm({ + "src/lib/runners/scheduler.ts"() { + "use strict"; + init_utils(); + init_git_logger(); + createScheduledTask = (() => { + let id = 0; + return () => { + id++; + const { promise, done } = createDeferred(); + return { + promise, + done, + id + }; + }; + })(); + Scheduler = class { + constructor(concurrency = 2) { + this.concurrency = concurrency; + this.logger = createLogger("", "scheduler"); + this.pending = []; + this.running = []; + this.logger(`Constructed, concurrency=%s`, concurrency); + } + schedule() { + if (!this.pending.length || this.running.length >= this.concurrency) { + this.logger( + `Schedule attempt ignored, pending=%s running=%s concurrency=%s`, + this.pending.length, + this.running.length, + this.concurrency + ); + return; + } + const task = append(this.running, this.pending.shift()); + this.logger(`Attempting id=%s`, task.id); + task.done(() => { + this.logger(`Completing id=`, task.id); + remove(this.running, task); + this.schedule(); + }); + } + next() { + const { promise, id } = append(this.pending, createScheduledTask()); + this.logger(`Scheduling id=%s`, id); + this.schedule(); + return promise; + } + }; + } +}); + +// src/lib/tasks/apply-patch.ts +var apply_patch_exports = {}; +__export(apply_patch_exports, { + applyPatchTask: () => applyPatchTask +}); +function applyPatchTask(patches, customArgs) { + return straightThroughStringTask(["apply", ...customArgs, ...patches]); +} +var init_apply_patch = __esm({ + "src/lib/tasks/apply-patch.ts"() { + "use strict"; + init_task(); + } +}); + +// src/lib/responses/BranchDeleteSummary.ts +function branchDeletionSuccess(branch, hash) { + return { + branch, + hash, + success: true + }; +} +function branchDeletionFailure(branch) { + return { + branch, + hash: null, + success: false + }; +} +var BranchDeletionBatch; +var init_BranchDeleteSummary = __esm({ + "src/lib/responses/BranchDeleteSummary.ts"() { + "use strict"; + BranchDeletionBatch = class { + constructor() { + this.all = []; + this.branches = {}; + this.errors = []; + } + get success() { + return !this.errors.length; + } + }; + } +}); + +// src/lib/parsers/parse-branch-delete.ts +function hasBranchDeletionError(data, processExitCode) { + return processExitCode === 1 /* ERROR */ && deleteErrorRegex.test(data); +} +var deleteSuccessRegex, deleteErrorRegex, parsers8, parseBranchDeletions; +var init_parse_branch_delete = __esm({ + "src/lib/parsers/parse-branch-delete.ts"() { + "use strict"; + init_BranchDeleteSummary(); + init_utils(); + deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/; + deleteErrorRegex = /^error[^']+'([^']+)'/m; + parsers8 = [ + new LineParser(deleteSuccessRegex, (result, [branch, hash]) => { + const deletion = branchDeletionSuccess(branch, hash); + result.all.push(deletion); + result.branches[branch] = deletion; + }), + new LineParser(deleteErrorRegex, (result, [branch]) => { + const deletion = branchDeletionFailure(branch); + result.errors.push(deletion); + result.all.push(deletion); + result.branches[branch] = deletion; + }) + ]; + parseBranchDeletions = (stdOut, stdErr) => { + return parseStringResponse(new BranchDeletionBatch(), parsers8, [stdOut, stdErr]); + }; + } +}); + +// src/lib/responses/BranchSummary.ts +var BranchSummaryResult; +var init_BranchSummary = __esm({ + "src/lib/responses/BranchSummary.ts"() { + "use strict"; + BranchSummaryResult = class { + constructor() { + this.all = []; + this.branches = {}; + this.current = ""; + this.detached = false; + } + push(status, detached, name, commit, label) { + if (status === "*" /* CURRENT */) { + this.detached = detached; + this.current = name; + } + this.all.push(name); + this.branches[name] = { + current: status === "*" /* CURRENT */, + linkedWorkTree: status === "+" /* LINKED */, + name, + commit, + label + }; + } + }; + } +}); + +// src/lib/parsers/parse-branch.ts +function branchStatus(input) { + return input ? input.charAt(0) : ""; +} +function parseBranchSummary(stdOut) { + return parseStringResponse(new BranchSummaryResult(), parsers9, stdOut); +} +var parsers9; +var init_parse_branch = __esm({ + "src/lib/parsers/parse-branch.ts"() { + "use strict"; + init_BranchSummary(); + init_utils(); + parsers9 = [ + new LineParser( + /^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/, + (result, [current, name, commit, label]) => { + result.push(branchStatus(current), true, name, commit, label); + } + ), + new LineParser( + new RegExp("^([*+]\\s)?(\\S+)\\s+([a-z0-9]+)\\s?(.*)$", "s"), + (result, [current, name, commit, label]) => { + result.push(branchStatus(current), false, name, commit, label); + } + ) + ]; + } +}); + +// src/lib/tasks/branch.ts +var branch_exports = {}; +__export(branch_exports, { + branchLocalTask: () => branchLocalTask, + branchTask: () => branchTask, + containsDeleteBranchCommand: () => containsDeleteBranchCommand, + deleteBranchTask: () => deleteBranchTask, + deleteBranchesTask: () => deleteBranchesTask +}); +function containsDeleteBranchCommand(commands) { + const deleteCommands = ["-d", "-D", "--delete"]; + return commands.some((command) => deleteCommands.includes(command)); +} +function branchTask(customArgs) { + const isDelete = containsDeleteBranchCommand(customArgs); + const commands = ["branch", ...customArgs]; + if (commands.length === 1) { + commands.push("-a"); + } + if (!commands.includes("-v")) { + commands.splice(1, 0, "-v"); + } + return { + format: "utf-8", + commands, + parser(stdOut, stdErr) { + if (isDelete) { + return parseBranchDeletions(stdOut, stdErr).all[0]; + } + return parseBranchSummary(stdOut); + } + }; +} +function branchLocalTask() { + const parser3 = parseBranchSummary; + return { + format: "utf-8", + commands: ["branch", "-v"], + parser: parser3 + }; +} +function deleteBranchesTask(branches, forceDelete = false) { + return { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", ...branches], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr); + }, + onError({ exitCode, stdOut }, error, done, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + done(stdOut); + } + }; +} +function deleteBranchTask(branch, forceDelete = false) { + const task = { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", branch], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr).branches[branch]; + }, + onError({ exitCode, stdErr, stdOut }, error, _, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + throw new GitResponseError( + task.parser(bufferToString(stdOut), bufferToString(stdErr)), + String(error) + ); + } + }; + return task; +} +var init_branch = __esm({ + "src/lib/tasks/branch.ts"() { + "use strict"; + init_git_response_error(); + init_parse_branch_delete(); + init_parse_branch(); + init_utils(); + } +}); + +// src/lib/responses/CheckIgnore.ts +var parseCheckIgnore; +var init_CheckIgnore = __esm({ + "src/lib/responses/CheckIgnore.ts"() { + "use strict"; + parseCheckIgnore = (text) => { + return text.split(/\n/g).map((line) => line.trim()).filter((file) => !!file); + }; + } +}); + +// src/lib/tasks/check-ignore.ts +var check_ignore_exports = {}; +__export(check_ignore_exports, { + checkIgnoreTask: () => checkIgnoreTask +}); +function checkIgnoreTask(paths) { + return { + commands: ["check-ignore", ...paths], + format: "utf-8", + parser: parseCheckIgnore + }; +} +var init_check_ignore = __esm({ + "src/lib/tasks/check-ignore.ts"() { + "use strict"; + init_CheckIgnore(); + } +}); + +// src/lib/tasks/clone.ts +var clone_exports = {}; +__export(clone_exports, { + cloneMirrorTask: () => cloneMirrorTask, + cloneTask: () => cloneTask +}); +function disallowedCommand(command) { + return /^--upload-pack(=|$)/.test(command); +} +function cloneTask(repo, directory, customArgs) { + const commands = ["clone", ...customArgs]; + filterString(repo) && commands.push(repo); + filterString(directory) && commands.push(directory); + const banned = commands.find(disallowedCommand); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return straightThroughStringTask(commands); +} +function cloneMirrorTask(repo, directory, customArgs) { + append(customArgs, "--mirror"); + return cloneTask(repo, directory, customArgs); +} +var init_clone = __esm({ + "src/lib/tasks/clone.ts"() { + "use strict"; + init_task(); + init_utils(); + } +}); + +// src/lib/parsers/parse-fetch.ts +function parseFetchResult(stdOut, stdErr) { + const result = { + raw: stdOut, + remote: null, + branches: [], + tags: [], + updated: [], + deleted: [] + }; + return parseStringResponse(result, parsers10, [stdOut, stdErr]); +} +var parsers10; +var init_parse_fetch = __esm({ + "src/lib/parsers/parse-fetch.ts"() { + "use strict"; + init_utils(); + parsers10 = [ + new LineParser(/From (.+)$/, (result, [remote]) => { + result.remote = remote; + }), + new LineParser(/\* \[new branch]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.branches.push({ + name, + tracking + }); + }), + new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.tags.push({ + name, + tracking + }); + }), + new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => { + result.deleted.push({ + tracking + }); + }), + new LineParser( + /\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/, + (result, [from, to, name, tracking]) => { + result.updated.push({ + name, + tracking, + to, + from + }); + } + ) + ]; + } +}); + +// src/lib/tasks/fetch.ts +var fetch_exports = {}; +__export(fetch_exports, { + fetchTask: () => fetchTask +}); +function disallowedCommand2(command) { + return /^--upload-pack(=|$)/.test(command); +} +function fetchTask(remote, branch, customArgs) { + const commands = ["fetch", ...customArgs]; + if (remote && branch) { + commands.push(remote, branch); + } + const banned = commands.find(disallowedCommand2); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return { + commands, + format: "utf-8", + parser: parseFetchResult + }; +} +var init_fetch = __esm({ + "src/lib/tasks/fetch.ts"() { + "use strict"; + init_parse_fetch(); + init_task(); + } +}); + +// src/lib/parsers/parse-move.ts +function parseMoveResult(stdOut) { + return parseStringResponse({ moves: [] }, parsers11, stdOut); +} +var parsers11; +var init_parse_move = __esm({ + "src/lib/parsers/parse-move.ts"() { + "use strict"; + init_utils(); + parsers11 = [ + new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => { + result.moves.push({ from, to }); + }) + ]; + } +}); + +// src/lib/tasks/move.ts +var move_exports = {}; +__export(move_exports, { + moveTask: () => moveTask +}); +function moveTask(from, to) { + return { + commands: ["mv", "-v", ...asArray(from), to], + format: "utf-8", + parser: parseMoveResult + }; +} +var init_move = __esm({ + "src/lib/tasks/move.ts"() { + "use strict"; + init_parse_move(); + init_utils(); + } +}); + +// src/lib/tasks/pull.ts +var pull_exports = {}; +__export(pull_exports, { + pullTask: () => pullTask +}); +function pullTask(remote, branch, customArgs) { + const commands = ["pull", ...customArgs]; + if (remote && branch) { + commands.splice(1, 0, remote, branch); + } + return { + commands, + format: "utf-8", + parser(stdOut, stdErr) { + return parsePullResult(stdOut, stdErr); + }, + onError(result, _error, _done, fail) { + const pullError = parsePullErrorResult( + bufferToString(result.stdOut), + bufferToString(result.stdErr) + ); + if (pullError) { + return fail(new GitResponseError(pullError)); + } + fail(_error); + } + }; +} +var init_pull = __esm({ + "src/lib/tasks/pull.ts"() { + "use strict"; + init_git_response_error(); + init_parse_pull(); + init_utils(); + } +}); + +// src/lib/responses/GetRemoteSummary.ts +function parseGetRemotes(text) { + const remotes = {}; + forEach(text, ([name]) => remotes[name] = { name }); + return Object.values(remotes); +} +function parseGetRemotesVerbose(text) { + const remotes = {}; + forEach(text, ([name, url, purpose]) => { + if (!remotes.hasOwnProperty(name)) { + remotes[name] = { + name, + refs: { fetch: "", push: "" } + }; + } + if (purpose && url) { + remotes[name].refs[purpose.replace(/[^a-z]/g, "")] = url; + } + }); + return Object.values(remotes); +} +function forEach(text, handler) { + forEachLineWithContent(text, (line) => handler(line.split(/\s+/))); +} +var init_GetRemoteSummary = __esm({ + "src/lib/responses/GetRemoteSummary.ts"() { + "use strict"; + init_utils(); + } +}); + +// src/lib/tasks/remote.ts +var remote_exports = {}; +__export(remote_exports, { + addRemoteTask: () => addRemoteTask, + getRemotesTask: () => getRemotesTask, + listRemotesTask: () => listRemotesTask, + remoteTask: () => remoteTask, + removeRemoteTask: () => removeRemoteTask +}); +function addRemoteTask(remoteName, remoteRepo, customArgs) { + return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]); +} +function getRemotesTask(verbose) { + const commands = ["remote"]; + if (verbose) { + commands.push("-v"); + } + return { + commands, + format: "utf-8", + parser: verbose ? parseGetRemotesVerbose : parseGetRemotes + }; +} +function listRemotesTask(customArgs) { + const commands = [...customArgs]; + if (commands[0] !== "ls-remote") { + commands.unshift("ls-remote"); + } + return straightThroughStringTask(commands); +} +function remoteTask(customArgs) { + const commands = [...customArgs]; + if (commands[0] !== "remote") { + commands.unshift("remote"); + } + return straightThroughStringTask(commands); +} +function removeRemoteTask(remoteName) { + return straightThroughStringTask(["remote", "remove", remoteName]); +} +var init_remote = __esm({ + "src/lib/tasks/remote.ts"() { + "use strict"; + init_GetRemoteSummary(); + init_task(); + } +}); + +// src/lib/tasks/stash-list.ts +var stash_list_exports = {}; +__export(stash_list_exports, { + stashListTask: () => stashListTask +}); +function stashListTask(opt = {}, customArgs) { + const options = parseLogOptions(opt); + const commands = ["stash", "list", ...options.commands, ...customArgs]; + const parser3 = createListLogSummaryParser( + options.splitter, + options.fields, + logFormatFromCommand(commands) + ); + return validateLogFormatConfig(commands) || { + commands, + format: "utf-8", + parser: parser3 + }; +} +var init_stash_list = __esm({ + "src/lib/tasks/stash-list.ts"() { + "use strict"; + init_log_format(); + init_parse_list_log_summary(); + init_diff(); + init_log(); + } +}); + +// src/lib/tasks/sub-module.ts +var sub_module_exports = {}; +__export(sub_module_exports, { + addSubModuleTask: () => addSubModuleTask, + initSubModuleTask: () => initSubModuleTask, + subModuleTask: () => subModuleTask, + updateSubModuleTask: () => updateSubModuleTask +}); +function addSubModuleTask(repo, path) { + return subModuleTask(["add", repo, path]); +} +function initSubModuleTask(customArgs) { + return subModuleTask(["init", ...customArgs]); +} +function subModuleTask(customArgs) { + const commands = [...customArgs]; + if (commands[0] !== "submodule") { + commands.unshift("submodule"); + } + return straightThroughStringTask(commands); +} +function updateSubModuleTask(customArgs) { + return subModuleTask(["update", ...customArgs]); +} +var init_sub_module = __esm({ + "src/lib/tasks/sub-module.ts"() { + "use strict"; + init_task(); + } +}); + +// src/lib/responses/TagList.ts +function singleSorted(a, b) { + const aIsNum = isNaN(a); + const bIsNum = isNaN(b); + if (aIsNum !== bIsNum) { + return aIsNum ? 1 : -1; + } + return aIsNum ? sorted(a, b) : 0; +} +function sorted(a, b) { + return a === b ? 0 : a > b ? 1 : -1; +} +function trimmed(input) { + return input.trim(); +} +function toNumber(input) { + if (typeof input === "string") { + return parseInt(input.replace(/^\D+/g, ""), 10) || 0; + } + return 0; +} +var TagList, parseTagList; +var init_TagList = __esm({ + "src/lib/responses/TagList.ts"() { + "use strict"; + TagList = class { + constructor(all, latest) { + this.all = all; + this.latest = latest; + } + }; + parseTagList = function(data, customSort = false) { + const tags = data.split("\n").map(trimmed).filter(Boolean); + if (!customSort) { + tags.sort(function(tagA, tagB) { + const partsA = tagA.split("."); + const partsB = tagB.split("."); + if (partsA.length === 1 || partsB.length === 1) { + return singleSorted(toNumber(partsA[0]), toNumber(partsB[0])); + } + for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) { + const diff = sorted(toNumber(partsA[i]), toNumber(partsB[i])); + if (diff) { + return diff; + } + } + return 0; + }); + } + const latest = customSort ? tags[0] : [...tags].reverse().find((tag) => tag.indexOf(".") >= 0); + return new TagList(tags, latest); + }; + } +}); + +// src/lib/tasks/tag.ts +var tag_exports = {}; +__export(tag_exports, { + addAnnotatedTagTask: () => addAnnotatedTagTask, + addTagTask: () => addTagTask, + tagListTask: () => tagListTask +}); +function tagListTask(customArgs = []) { + const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option)); + return { + format: "utf-8", + commands: ["tag", "-l", ...customArgs], + parser(text) { + return parseTagList(text, hasCustomSort); + } + }; +} +function addTagTask(name) { + return { + format: "utf-8", + commands: ["tag", name], + parser() { + return { name }; + } + }; +} +function addAnnotatedTagTask(name, tagMessage) { + return { + format: "utf-8", + commands: ["tag", "-a", "-m", tagMessage, name], + parser() { + return { name }; + } + }; +} +var init_tag = __esm({ + "src/lib/tasks/tag.ts"() { + "use strict"; + init_TagList(); + } +}); + +// src/git.js +var require_git = __commonJS({ + "src/git.js"(exports, module) { + "use strict"; + var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS(git_executor_exports)); + var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS(simple_git_api_exports)); + var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS(scheduler_exports)); + var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS(task_exports)); + var { + asArray: asArray2, + filterArray: filterArray2, + filterPrimitives: filterPrimitives2, + filterString: filterString2, + filterStringOrStringArray: filterStringOrStringArray2, + filterType: filterType2, + getTrailingOptions: getTrailingOptions2, + trailingFunctionArgument: trailingFunctionArgument2, + trailingOptionsArgument: trailingOptionsArgument2 + } = (init_utils(), __toCommonJS(utils_exports)); + var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS(apply_patch_exports)); + var { + branchTask: branchTask2, + branchLocalTask: branchLocalTask2, + deleteBranchesTask: deleteBranchesTask2, + deleteBranchTask: deleteBranchTask2 + } = (init_branch(), __toCommonJS(branch_exports)); + var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS(check_ignore_exports)); + var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS(check_is_repo_exports)); + var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS(clone_exports)); + var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS(clean_exports)); + var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS(diff_exports)); + var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS(fetch_exports)); + var { moveTask: moveTask2 } = (init_move(), __toCommonJS(move_exports)); + var { pullTask: pullTask2 } = (init_pull(), __toCommonJS(pull_exports)); + var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS(push_exports)); + var { + addRemoteTask: addRemoteTask2, + getRemotesTask: getRemotesTask2, + listRemotesTask: listRemotesTask2, + remoteTask: remoteTask2, + removeRemoteTask: removeRemoteTask2 + } = (init_remote(), __toCommonJS(remote_exports)); + var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS(reset_exports)); + var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS(stash_list_exports)); + var { + addSubModuleTask: addSubModuleTask2, + initSubModuleTask: initSubModuleTask2, + subModuleTask: subModuleTask2, + updateSubModuleTask: updateSubModuleTask2 + } = (init_sub_module(), __toCommonJS(sub_module_exports)); + var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS(tag_exports)); + var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS(task_exports)); + function Git2(options, plugins) { + this._plugins = plugins; + this._executor = new GitExecutor2( + options.baseDir, + new Scheduler2(options.maxConcurrentProcesses), + plugins + ); + this._trimmed = options.trimmed; + } + (Git2.prototype = Object.create(SimpleGitApi2.prototype)).constructor = Git2; + Git2.prototype.customBinary = function(command) { + this._plugins.reconfigure("binary", command); + return this; + }; + Git2.prototype.env = function(name, value) { + if (arguments.length === 1 && typeof name === "object") { + this._executor.env = name; + } else { + (this._executor.env = this._executor.env || {})[name] = value; + } + return this; + }; + Git2.prototype.stashList = function(options) { + return this._runTask( + stashListTask2( + trailingOptionsArgument2(arguments) || {}, + filterArray2(options) && options || [] + ), + trailingFunctionArgument2(arguments) + ); + }; + function createCloneTask(api, task, repoPath, localPath) { + if (typeof repoPath !== "string") { + return configurationErrorTask2(`git.${api}() requires a string 'repoPath'`); + } + return task(repoPath, filterType2(localPath, filterString2), getTrailingOptions2(arguments)); + } + Git2.prototype.clone = function() { + return this._runTask( + createCloneTask("clone", cloneTask2, ...arguments), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.mirror = function() { + return this._runTask( + createCloneTask("mirror", cloneMirrorTask2, ...arguments), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.mv = function(from, to) { + return this._runTask(moveTask2(from, to), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.checkoutLatestTag = function(then) { + var git = this; + return this.pull(function() { + git.tags(function(err, tags) { + git.checkout(tags.latest, then); + }); + }); + }; + Git2.prototype.pull = function(remote, branch, options, then) { + return this._runTask( + pullTask2( + filterType2(remote, filterString2), + filterType2(branch, filterString2), + getTrailingOptions2(arguments) + ), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.fetch = function(remote, branch) { + return this._runTask( + fetchTask2( + filterType2(remote, filterString2), + filterType2(branch, filterString2), + getTrailingOptions2(arguments) + ), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.silent = function(silence) { + console.warn( + "simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3" + ); + return this; + }; + Git2.prototype.tags = function(options, then) { + return this._runTask( + tagListTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.rebase = function() { + return this._runTask( + straightThroughStringTask2(["rebase", ...getTrailingOptions2(arguments)]), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.reset = function(mode) { + return this._runTask( + resetTask2(getResetMode2(mode), getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.revert = function(commit) { + const next = trailingFunctionArgument2(arguments); + if (typeof commit !== "string") { + return this._runTask(configurationErrorTask2("Commit must be a string"), next); + } + return this._runTask( + straightThroughStringTask2(["revert", ...getTrailingOptions2(arguments, 0, true), commit]), + next + ); + }; + Git2.prototype.addTag = function(name) { + const task = typeof name === "string" ? addTagTask2(name) : configurationErrorTask2("Git.addTag requires a tag name"); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) { + return this._runTask( + addAnnotatedTagTask2(tagName, tagMessage), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) { + return this._runTask( + deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.deleteLocalBranches = function(branchNames, forceDelete, then) { + return this._runTask( + deleteBranchesTask2(branchNames, typeof forceDelete === "boolean" ? forceDelete : false), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.branch = function(options, then) { + return this._runTask( + branchTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.branchLocal = function(then) { + return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.raw = function(commands) { + const createRestCommands = !Array.isArray(commands); + const command = [].slice.call(createRestCommands ? arguments : commands, 0); + for (let i = 0; i < command.length && createRestCommands; i++) { + if (!filterPrimitives2(command[i])) { + command.splice(i, command.length - i); + break; + } + } + command.push(...getTrailingOptions2(arguments, 0, true)); + var next = trailingFunctionArgument2(arguments); + if (!command.length) { + return this._runTask( + configurationErrorTask2("Raw: must supply one or more command to execute"), + next + ); + } + return this._runTask(straightThroughStringTask2(command, this._trimmed), next); + }; + Git2.prototype.submoduleAdd = function(repo, path, then) { + return this._runTask(addSubModuleTask2(repo, path), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.submoduleUpdate = function(args, then) { + return this._runTask( + updateSubModuleTask2(getTrailingOptions2(arguments, true)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.submoduleInit = function(args, then) { + return this._runTask( + initSubModuleTask2(getTrailingOptions2(arguments, true)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.subModule = function(options, then) { + return this._runTask( + subModuleTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.listRemote = function() { + return this._runTask( + listRemotesTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.addRemote = function(remoteName, remoteRepo, then) { + return this._runTask( + addRemoteTask2(remoteName, remoteRepo, getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.removeRemote = function(remoteName, then) { + return this._runTask(removeRemoteTask2(remoteName), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.getRemotes = function(verbose, then) { + return this._runTask(getRemotesTask2(verbose === true), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.remote = function(options, then) { + return this._runTask( + remoteTask2(getTrailingOptions2(arguments)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.tag = function(options, then) { + const command = getTrailingOptions2(arguments); + if (command[0] !== "tag") { + command.unshift("tag"); + } + return this._runTask(straightThroughStringTask2(command), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.updateServerInfo = function(then) { + return this._runTask( + straightThroughStringTask2(["update-server-info"]), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.pushTags = function(remote, then) { + const task = pushTagsTask2( + { remote: filterType2(remote, filterString2) }, + getTrailingOptions2(arguments) + ); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rm = function(files) { + return this._runTask( + straightThroughStringTask2(["rm", "-f", ...asArray2(files)]), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.rmKeepLocal = function(files) { + return this._runTask( + straightThroughStringTask2(["rm", "--cached", ...asArray2(files)]), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.catFile = function(options, then) { + return this._catFile("utf-8", arguments); + }; + Git2.prototype.binaryCatFile = function() { + return this._catFile("buffer", arguments); + }; + Git2.prototype._catFile = function(format, args) { + var handler = trailingFunctionArgument2(args); + var command = ["cat-file"]; + var options = args[0]; + if (typeof options === "string") { + return this._runTask( + configurationErrorTask2("Git.catFile: options must be supplied as an array of strings"), + handler + ); + } + if (Array.isArray(options)) { + command.push.apply(command, options); + } + const task = format === "buffer" ? straightThroughBufferTask2(command) : straightThroughStringTask2(command); + return this._runTask(task, handler); + }; + Git2.prototype.diff = function(options, then) { + const task = filterString2(options) ? configurationErrorTask2( + "git.diff: supplying options as a single string is no longer supported, switch to an array of strings" + ) : straightThroughStringTask2(["diff", ...getTrailingOptions2(arguments)]); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.diffSummary = function() { + return this._runTask( + diffSummaryTask2(getTrailingOptions2(arguments, 1)), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.applyPatch = function(patches) { + const task = !filterStringOrStringArray2(patches) ? configurationErrorTask2( + `git.applyPatch requires one or more string patches as the first argument` + ) : applyPatchTask2(asArray2(patches), getTrailingOptions2([].slice.call(arguments, 1))); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.revparse = function() { + const commands = ["rev-parse", ...getTrailingOptions2(arguments, true)]; + return this._runTask( + straightThroughStringTask2(commands, true), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.clean = function(mode, options, then) { + const usingCleanOptionsArray = isCleanOptionsArray2(mode); + const cleanMode = usingCleanOptionsArray && mode.join("") || filterType2(mode, filterString2) || ""; + const customArgs = getTrailingOptions2([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0)); + return this._runTask( + cleanWithOptionsTask2(cleanMode, customArgs), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.exec = function(then) { + const task = { + commands: [], + format: "utf-8", + parser() { + if (typeof then === "function") { + then(); + } + } + }; + return this._runTask(task); + }; + Git2.prototype.clearQueue = function() { + return this; + }; + Git2.prototype.checkIgnore = function(pathnames, then) { + return this._runTask( + checkIgnoreTask2(asArray2(filterType2(pathnames, filterStringOrStringArray2, []))), + trailingFunctionArgument2(arguments) + ); + }; + Git2.prototype.checkIsRepo = function(checkType, then) { + return this._runTask( + checkIsRepoTask2(filterType2(checkType, filterString2)), + trailingFunctionArgument2(arguments) + ); + }; + module.exports = Git2; + } +}); + +// src/lib/api.ts +init_pathspec(); + +// src/lib/errors/git-construct-error.ts +init_git_error(); +var GitConstructError = class extends GitError { + constructor(config, message) { + super(void 0, message); + this.config = config; + } +}; + +// src/lib/api.ts +init_git_error(); + +// src/lib/errors/git-plugin-error.ts +init_git_error(); +var GitPluginError = class extends GitError { + constructor(task, plugin, message) { + super(task, message); + this.task = task; + this.plugin = plugin; + Object.setPrototypeOf(this, new.target.prototype); + } +}; + +// src/lib/api.ts +init_git_response_error(); +init_task_configuration_error(); +init_check_is_repo(); +init_clean(); +init_config(); +init_diff_name_status(); +init_grep(); +init_reset(); + +// src/lib/plugins/abort-plugin.ts +function abortPlugin(signal) { + if (!signal) { + return; + } + const onSpawnAfter = { + type: "spawn.after", + action(_data, context) { + function kill() { + context.kill(new GitPluginError(void 0, "abort", "Abort signal received")); + } + signal.addEventListener("abort", kill); + context.spawned.on("close", () => signal.removeEventListener("abort", kill)); + } + }; + const onSpawnBefore = { + type: "spawn.before", + action(_data, context) { + if (signal.aborted) { + context.kill(new GitPluginError(void 0, "abort", "Abort already signaled")); + } + } + }; + return [onSpawnBefore, onSpawnAfter]; +} + +// src/lib/plugins/block-unsafe-operations-plugin.ts +function isConfigSwitch(arg) { + return typeof arg === "string" && arg.trim().toLowerCase() === "-c"; +} +function preventProtocolOverride(arg, next) { + if (!isConfigSwitch(arg)) { + return; + } + if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) { + return; + } + throw new GitPluginError( + void 0, + "unsafe", + "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol" + ); +} +function preventUploadPack(arg, method) { + if (/^\s*--(upload|receive)-pack/.test(arg)) { + throw new GitPluginError( + void 0, + "unsafe", + `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack` + ); + } + if (method === "clone" && /^\s*-u\b/.test(arg)) { + throw new GitPluginError( + void 0, + "unsafe", + `Use of clone with option -u is not permitted without enabling allowUnsafePack` + ); + } + if (method === "push" && /^\s*--exec\b/.test(arg)) { + throw new GitPluginError( + void 0, + "unsafe", + `Use of push with option --exec is not permitted without enabling allowUnsafePack` + ); + } +} +function blockUnsafeOperationsPlugin({ + allowUnsafeProtocolOverride = false, + allowUnsafePack = false +} = {}) { + return { + type: "spawn.args", + action(args, context) { + args.forEach((current, index) => { + const next = index < args.length ? args[index + 1] : ""; + allowUnsafeProtocolOverride || preventProtocolOverride(current, next); + allowUnsafePack || preventUploadPack(current, context.method); + }); + return args; + } + }; +} + +// src/lib/plugins/command-config-prefixing-plugin.ts +init_utils(); +function commandConfigPrefixingPlugin(configuration) { + const prefix = prefixedArray(configuration, "-c"); + return { + type: "spawn.args", + action(data) { + return [...prefix, ...data]; + } + }; +} + +// src/lib/plugins/completion-detection.plugin.ts +init_utils(); +import { deferred } from "@kwsites/promise-deferred"; +var never = deferred().promise; +function completionDetectionPlugin({ + onClose = true, + onExit = 50 +} = {}) { + function createEvents() { + let exitCode = -1; + const events = { + close: deferred(), + closeTimeout: deferred(), + exit: deferred(), + exitTimeout: deferred() + }; + const result = Promise.race([ + onClose === false ? never : events.closeTimeout.promise, + onExit === false ? never : events.exitTimeout.promise + ]); + configureTimeout(onClose, events.close, events.closeTimeout); + configureTimeout(onExit, events.exit, events.exitTimeout); + return { + close(code) { + exitCode = code; + events.close.done(); + }, + exit(code) { + exitCode = code; + events.exit.done(); + }, + get exitCode() { + return exitCode; + }, + result + }; + } + function configureTimeout(flag, event, timeout) { + if (flag === false) { + return; + } + (flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done); + } + return { + type: "spawn.after", + action(_0, _1) { + return __async(this, arguments, function* (_data, { spawned, close }) { + var _a3, _b; + const events = createEvents(); + let deferClose = true; + let quickClose = () => void (deferClose = false); + (_a3 = spawned.stdout) == null ? void 0 : _a3.on("data", quickClose); + (_b = spawned.stderr) == null ? void 0 : _b.on("data", quickClose); + spawned.on("error", quickClose); + spawned.on("close", (code) => events.close(code)); + spawned.on("exit", (code) => events.exit(code)); + try { + yield events.result; + if (deferClose) { + yield delay(50); + } + close(events.exitCode); + } catch (err) { + close(events.exitCode, err); + } + }); + } + }; +} + +// src/lib/plugins/custom-binary.plugin.ts +init_utils(); +var WRONG_NUMBER_ERR = `Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`; +var WRONG_CHARS_ERR = `Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`; +function isBadArgument(arg) { + return !arg || !/^([a-z]:)?([a-z0-9/.\\_-]+)$/i.test(arg); +} +function toBinaryConfig(input, allowUnsafe) { + if (input.length < 1 || input.length > 2) { + throw new GitPluginError(void 0, "binary", WRONG_NUMBER_ERR); + } + const isBad = input.some(isBadArgument); + if (isBad) { + if (allowUnsafe) { + console.warn(WRONG_CHARS_ERR); + } else { + throw new GitPluginError(void 0, "binary", WRONG_CHARS_ERR); + } + } + const [binary, prefix] = input; + return { + binary, + prefix + }; +} +function customBinaryPlugin(plugins, input = ["git"], allowUnsafe = false) { + let config = toBinaryConfig(asArray(input), allowUnsafe); + plugins.on("binary", (input2) => { + config = toBinaryConfig(asArray(input2), allowUnsafe); + }); + plugins.append("spawn.binary", () => { + return config.binary; + }); + plugins.append("spawn.args", (data) => { + return config.prefix ? [config.prefix, ...data] : data; + }); +} + +// src/lib/plugins/error-detection.plugin.ts +init_git_error(); +function isTaskError(result) { + return !!(result.exitCode && result.stdErr.length); +} +function getErrorMessage(result) { + return Buffer.concat([...result.stdOut, ...result.stdErr]); +} +function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage) { + return (error, result) => { + if (!overwrite && error || !isError(result)) { + return error; + } + return errorMessage(result); + }; +} +function errorDetectionPlugin(config) { + return { + type: "task.error", + action(data, context) { + const error = config(data.error, { + stdErr: context.stdErr, + stdOut: context.stdOut, + exitCode: context.exitCode + }); + if (Buffer.isBuffer(error)) { + return { error: new GitError(void 0, error.toString("utf-8")) }; + } + return { + error + }; + } + }; +} + +// src/lib/plugins/plugin-store.ts +init_utils(); +import { EventEmitter } from "node:events"; +var PluginStore = class { + constructor() { + this.plugins = /* @__PURE__ */ new Set(); + this.events = new EventEmitter(); + } + on(type, listener) { + this.events.on(type, listener); + } + reconfigure(type, data) { + this.events.emit(type, data); + } + append(type, action) { + const plugin = append(this.plugins, { type, action }); + return () => this.plugins.delete(plugin); + } + add(plugin) { + const plugins = []; + asArray(plugin).forEach((plugin2) => plugin2 && this.plugins.add(append(plugins, plugin2))); + return () => { + plugins.forEach((plugin2) => this.plugins.delete(plugin2)); + }; + } + exec(type, data, context) { + let output = data; + const contextual = Object.freeze(Object.create(context)); + for (const plugin of this.plugins) { + if (plugin.type === type) { + output = plugin.action(output, contextual); + } + } + return output; + } +}; + +// src/lib/plugins/progress-monitor-plugin.ts +init_utils(); +function progressMonitorPlugin(progress) { + const progressCommand = "--progress"; + const progressMethods = ["checkout", "clone", "fetch", "pull", "push"]; + const onProgress = { + type: "spawn.after", + action(_data, context) { + var _a2; + if (!context.commands.includes(progressCommand)) { + return; + } + (_a2 = context.spawned.stderr) == null ? void 0 : _a2.on("data", (chunk) => { + const message = /^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(chunk.toString("utf8")); + if (!message) { + return; + } + progress({ + method: context.method, + stage: progressEventStage(message[1]), + progress: asNumber(message[2]), + processed: asNumber(message[3]), + total: asNumber(message[4]) + }); + }); + } + }; + const onArgs = { + type: "spawn.args", + action(args, context) { + if (!progressMethods.includes(context.method)) { + return args; + } + return including(args, progressCommand); + } + }; + return [onArgs, onProgress]; +} +function progressEventStage(input) { + return String(input.toLowerCase().split(" ", 1)) || "unknown"; +} + +// src/lib/plugins/spawn-options-plugin.ts +init_utils(); +function spawnOptionsPlugin(spawnOptions) { + const options = pick(spawnOptions, ["uid", "gid"]); + return { + type: "spawn.options", + action(data) { + return __spreadValues(__spreadValues({}, options), data); + } + }; +} + +// src/lib/plugins/timout-plugin.ts +function timeoutPlugin({ + block, + stdErr = true, + stdOut = true +}) { + if (block > 0) { + return { + type: "spawn.after", + action(_data, context) { + var _a2, _b; + let timeout; + function wait() { + timeout && clearTimeout(timeout); + timeout = setTimeout(kill, block); + } + function stop() { + var _a3, _b2; + (_a3 = context.spawned.stdout) == null ? void 0 : _a3.off("data", wait); + (_b2 = context.spawned.stderr) == null ? void 0 : _b2.off("data", wait); + context.spawned.off("exit", stop); + context.spawned.off("close", stop); + timeout && clearTimeout(timeout); + } + function kill() { + stop(); + context.kill(new GitPluginError(void 0, "timeout", `block timeout reached`)); + } + stdOut && ((_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait)); + stdErr && ((_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait)); + context.spawned.on("exit", stop); + context.spawned.on("close", stop); + wait(); + } + }; + } +} + +// src/lib/plugins/suffix-paths.plugin.ts +init_pathspec(); +function suffixPathsPlugin() { + return { + type: "spawn.args", + action(data) { + const prefix = []; + let suffix; + function append2(args) { + (suffix = suffix || []).push(...args); + } + for (let i = 0; i < data.length; i++) { + const param = data[i]; + if (isPathSpec(param)) { + append2(toPaths(param)); + continue; + } + if (param === "--") { + append2( + data.slice(i + 1).flatMap((item) => isPathSpec(item) && toPaths(item) || item) + ); + break; + } + prefix.push(param); + } + return !suffix ? prefix : [...prefix, "--", ...suffix.map(String)]; + } + }; +} + +// src/lib/git-factory.ts +init_utils(); +var Git = require_git(); +function gitInstanceFactory(baseDir, options) { + var _a2; + const plugins = new PluginStore(); + const config = createInstanceConfig( + baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {}, + options + ); + if (!folderExists(config.baseDir)) { + throw new GitConstructError( + config, + `Cannot use simple-git on a directory that does not exist` + ); + } + if (Array.isArray(config.config)) { + plugins.add(commandConfigPrefixingPlugin(config.config)); + } + plugins.add(blockUnsafeOperationsPlugin(config.unsafe)); + plugins.add(suffixPathsPlugin()); + plugins.add(completionDetectionPlugin(config.completion)); + config.abort && plugins.add(abortPlugin(config.abort)); + config.progress && plugins.add(progressMonitorPlugin(config.progress)); + config.timeout && plugins.add(timeoutPlugin(config.timeout)); + config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions)); + plugins.add(errorDetectionPlugin(errorDetectionHandler(true))); + config.errors && plugins.add(errorDetectionPlugin(config.errors)); + customBinaryPlugin(plugins, config.binary, (_a2 = config.unsafe) == null ? void 0 : _a2.allowUnsafeCustomBinary); + return new Git(config, plugins); +} + +// src/lib/runners/promise-wrapped.ts +init_git_response_error(); +var functionNamesBuilderApi = ["customBinary", "env", "outputHandler", "silent"]; +var functionNamesPromiseApi = [ + "add", + "addAnnotatedTag", + "addConfig", + "addRemote", + "addTag", + "applyPatch", + "binaryCatFile", + "branch", + "branchLocal", + "catFile", + "checkIgnore", + "checkIsRepo", + "checkout", + "checkoutBranch", + "checkoutLatestTag", + "checkoutLocalBranch", + "clean", + "clone", + "commit", + "cwd", + "deleteLocalBranch", + "deleteLocalBranches", + "diff", + "diffSummary", + "exec", + "fetch", + "getRemotes", + "init", + "listConfig", + "listRemote", + "log", + "merge", + "mergeFromTo", + "mirror", + "mv", + "pull", + "push", + "pushTags", + "raw", + "rebase", + "remote", + "removeRemote", + "reset", + "revert", + "revparse", + "rm", + "rmKeepLocal", + "show", + "stash", + "stashList", + "status", + "subModule", + "submoduleAdd", + "submoduleInit", + "submoduleUpdate", + "tag", + "tags", + "updateServerInfo" +]; +function gitP(...args) { + let git; + let chain = Promise.resolve(); + try { + git = gitInstanceFactory(...args); + } catch (e) { + chain = Promise.reject(e); + } + function builderReturn() { + return promiseApi; + } + function chainReturn() { + return chain; + } + const promiseApi = [...functionNamesBuilderApi, ...functionNamesPromiseApi].reduce( + (api, name) => { + const isAsync = functionNamesPromiseApi.includes(name); + const valid = isAsync ? asyncWrapper(name, git) : syncWrapper(name, git, api); + const alternative = isAsync ? chainReturn : builderReturn; + Object.defineProperty(api, name, { + enumerable: false, + configurable: false, + value: git ? valid : alternative + }); + return api; + }, + {} + ); + return promiseApi; + function asyncWrapper(fn, git2) { + return function(...args2) { + if (typeof args2[args2.length] === "function") { + throw new TypeError( + "Promise interface requires that handlers are not supplied inline, trailing function not allowed in call to " + fn + ); + } + return chain.then(function() { + return new Promise(function(resolve, reject) { + const callback = (err, result) => { + if (err) { + return reject(toError(err)); + } + resolve(result); + }; + args2.push(callback); + git2[fn].apply(git2, args2); + }); + }); + }; + } + function syncWrapper(fn, git2, api) { + return (...args2) => { + git2[fn](...args2); + return api; + }; + } +} +function toError(error) { + if (error instanceof Error) { + return error; + } + if (typeof error === "string") { + return new Error(error); + } + return new GitResponseError(error); +} + +// src/esm.mjs +var simpleGit = gitInstanceFactory; +var esm_default = gitInstanceFactory; +export { + CheckRepoActions, + CleanOptions, + DiffNameStatus, + GitConfigScope, + GitConstructError, + GitError, + GitPluginError, + GitResponseError, + ResetMode, + TaskConfigurationError, + esm_default as default, + gitP, + grepQueryBuilder, + pathspec, + simpleGit +}; +//# sourceMappingURL=index.js.map diff --git a/node_modules/simple-git/dist/esm/index.js.map b/node_modules/simple-git/dist/esm/index.js.map new file mode 100644 index 0000000..abf696b --- /dev/null +++ b/node_modules/simple-git/dist/esm/index.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../../src/lib/args/pathspec.ts", "../../src/lib/errors/git-error.ts", "../../src/lib/errors/git-response-error.ts", "../../src/lib/errors/task-configuration-error.ts", "../../src/lib/utils/util.ts", "../../src/lib/utils/argument-filters.ts", "../../src/lib/utils/exit-codes.ts", "../../src/lib/utils/git-output-streams.ts", "../../src/lib/utils/line-parser.ts", "../../src/lib/utils/simple-git-options.ts", "../../src/lib/utils/task-options.ts", "../../src/lib/utils/task-parser.ts", "../../src/lib/utils/index.ts", "../../src/lib/tasks/check-is-repo.ts", "../../src/lib/responses/CleanSummary.ts", "../../src/lib/tasks/task.ts", "../../src/lib/tasks/clean.ts", "../../src/lib/responses/ConfigList.ts", "../../src/lib/tasks/config.ts", "../../src/lib/tasks/diff-name-status.ts", "../../src/lib/tasks/grep.ts", "../../src/lib/tasks/reset.ts", "../../src/lib/git-logger.ts", "../../src/lib/runners/tasks-pending-queue.ts", "../../src/lib/runners/git-executor-chain.ts", "../../src/lib/runners/git-executor.ts", "../../src/lib/task-callback.ts", "../../src/lib/tasks/change-working-directory.ts", "../../src/lib/tasks/checkout.ts", "../../src/lib/parsers/parse-commit.ts", "../../src/lib/tasks/commit.ts", "../../src/lib/tasks/first-commit.ts", "../../src/lib/tasks/hash-object.ts", "../../src/lib/responses/InitSummary.ts", "../../src/lib/tasks/init.ts", "../../src/lib/args/log-format.ts", "../../src/lib/responses/DiffSummary.ts", "../../src/lib/parsers/parse-diff-summary.ts", "../../src/lib/parsers/parse-list-log-summary.ts", "../../src/lib/tasks/diff.ts", "../../src/lib/tasks/log.ts", "../../src/lib/responses/MergeSummary.ts", "../../src/lib/responses/PullSummary.ts", "../../src/lib/parsers/parse-remote-objects.ts", "../../src/lib/parsers/parse-remote-messages.ts", "../../src/lib/parsers/parse-pull.ts", "../../src/lib/parsers/parse-merge.ts", "../../src/lib/tasks/merge.ts", "../../src/lib/parsers/parse-push.ts", "../../src/lib/tasks/push.ts", "../../src/lib/tasks/show.ts", "../../src/lib/responses/FileStatusSummary.ts", "../../src/lib/responses/StatusSummary.ts", "../../src/lib/tasks/status.ts", "../../src/lib/tasks/version.ts", "../../src/lib/simple-git-api.ts", "../../src/lib/runners/scheduler.ts", "../../src/lib/tasks/apply-patch.ts", "../../src/lib/responses/BranchDeleteSummary.ts", "../../src/lib/parsers/parse-branch-delete.ts", "../../src/lib/responses/BranchSummary.ts", "../../src/lib/parsers/parse-branch.ts", "../../src/lib/tasks/branch.ts", "../../src/lib/responses/CheckIgnore.ts", "../../src/lib/tasks/check-ignore.ts", "../../src/lib/tasks/clone.ts", "../../src/lib/parsers/parse-fetch.ts", "../../src/lib/tasks/fetch.ts", "../../src/lib/parsers/parse-move.ts", "../../src/lib/tasks/move.ts", "../../src/lib/tasks/pull.ts", "../../src/lib/responses/GetRemoteSummary.ts", "../../src/lib/tasks/remote.ts", "../../src/lib/tasks/stash-list.ts", "../../src/lib/tasks/sub-module.ts", "../../src/lib/responses/TagList.ts", "../../src/lib/tasks/tag.ts", "../../src/git.js", "../../src/lib/api.ts", "../../src/lib/errors/git-construct-error.ts", "../../src/lib/errors/git-plugin-error.ts", "../../src/lib/plugins/abort-plugin.ts", "../../src/lib/plugins/block-unsafe-operations-plugin.ts", "../../src/lib/plugins/command-config-prefixing-plugin.ts", "../../src/lib/plugins/completion-detection.plugin.ts", "../../src/lib/plugins/custom-binary.plugin.ts", "../../src/lib/plugins/error-detection.plugin.ts", "../../src/lib/plugins/plugin-store.ts", "../../src/lib/plugins/progress-monitor-plugin.ts", "../../src/lib/plugins/spawn-options-plugin.ts", "../../src/lib/plugins/timout-plugin.ts", "../../src/lib/plugins/suffix-paths.plugin.ts", "../../src/lib/git-factory.ts", "../../src/lib/runners/promise-wrapped.ts", "../../src/esm.mjs"], + "sourcesContent": ["const cache = new WeakMap();\n\nexport function pathspec(...paths: string[]) {\n const key = new String(paths);\n cache.set(key, paths);\n\n return key as string;\n}\n\nexport function isPathSpec(path: string | unknown): path is string {\n return path instanceof String && cache.has(path);\n}\n\nexport function toPaths(pathSpec: string): string[] {\n return cache.get(pathSpec) || [];\n}\n", "import type { SimpleGitTask } from '../types';\n\n/**\n * The `GitError` is thrown when the underlying `git` process throws a\n * fatal exception (eg an `ENOENT` exception when attempting to use a\n * non-writable directory as the root for your repo), and acts as the\n * base class for more specific errors thrown by the parsing of the\n * git response or errors in the configuration of the task about to\n * be run.\n *\n * When an exception is thrown, pending tasks in the same instance will\n * not be executed. The recommended way to run a series of tasks that\n * can independently fail without needing to prevent future tasks from\n * running is to catch them individually:\n *\n * ```typescript\n import { gitP, SimpleGit, GitError, PullResult } from 'simple-git';\n\n function catchTask (e: GitError) {\n return e.\n }\n\n const git = gitP(repoWorkingDir);\n const pulled: PullResult | GitError = await git.pull().catch(catchTask);\n const pushed: string | GitError = await git.pushTags().catch(catchTask);\n ```\n */\nexport class GitError extends Error {\n constructor(\n public task?: SimpleGitTask,\n message?: string\n ) {\n super(message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n", "import { GitError } from './git-error';\n\n/**\n * The `GitResponseError` is the wrapper for a parsed response that is treated as\n * a fatal error, for example attempting a `merge` can leave the repo in a corrupted\n * state when there are conflicts so the task will reject rather than resolve.\n *\n * For example, catching the merge conflict exception:\n *\n * ```typescript\n import { gitP, SimpleGit, GitResponseError, MergeSummary } from 'simple-git';\n\n const git = gitP(repoRoot);\n const mergeOptions: string[] = ['--no-ff', 'other-branch'];\n const mergeSummary: MergeSummary = await git.merge(mergeOptions)\n .catch((e: GitResponseError) => e.git);\n\n if (mergeSummary.failed) {\n // deal with the error\n }\n ```\n */\nexport class GitResponseError extends GitError {\n constructor(\n /**\n * `.git` access the parsed response that is treated as being an error\n */\n public readonly git: T,\n message?: string\n ) {\n super(undefined, message || String(git));\n }\n}\n", "import { GitError } from './git-error';\n\n/**\n * The `TaskConfigurationError` is thrown when a command was incorrectly\n * configured. An error of this kind means that no attempt was made to\n * run your command through the underlying `git` binary.\n *\n * Check the `.message` property for more detail on why your configuration\n * resulted in an error.\n */\nexport class TaskConfigurationError extends GitError {\n constructor(message?: string) {\n super(undefined, message);\n }\n}\n", "import { exists, FOLDER } from '@kwsites/file-exists';\nimport { Maybe } from '../types';\n\nexport const NULL = '\\0';\n\nexport const NOOP: (...args: any[]) => void = () => {};\n\n/**\n * Returns either the source argument when it is a `Function`, or the default\n * `NOOP` function constant\n */\nexport function asFunction any>(source: T | any): T {\n return typeof source === 'function' ? source : NOOP;\n}\n\n/**\n * Determines whether the supplied argument is both a function, and is not\n * the `NOOP` function.\n */\nexport function isUserFunction(source: T | any): source is T {\n return typeof source === 'function' && source !== NOOP;\n}\n\nexport function splitOn(input: string, char: string): [string, string] {\n const index = input.indexOf(char);\n if (index <= 0) {\n return [input, ''];\n }\n\n return [input.substr(0, index), input.substr(index + 1)];\n}\n\nexport function first(input: T, offset?: number): Maybe;\nexport function first(input: T, offset?: number): Maybe;\nexport function first(input: any[] | IArguments, offset = 0): Maybe {\n return isArrayLike(input) && input.length > offset ? input[offset] : undefined;\n}\n\nexport function last(input: T, offset?: number): Maybe;\nexport function last(input: T, offset?: number): Maybe;\nexport function last(input: T, offset?: number): Maybe;\nexport function last(input: unknown, offset = 0) {\n if (isArrayLike(input) && input.length > offset) {\n return input[input.length - 1 - offset];\n }\n}\n\ntype ArrayLike = T[] | IArguments | { [index: number]: T; length: number };\n\nfunction isArrayLike(input: any): input is ArrayLike {\n return !!(input && typeof input.length === 'number');\n}\n\nexport function toLinesWithContent(input = '', trimmed = true, separator = '\\n'): string[] {\n return input.split(separator).reduce((output, line) => {\n const lineContent = trimmed ? line.trim() : line;\n if (lineContent) {\n output.push(lineContent);\n }\n return output;\n }, [] as string[]);\n}\n\ntype LineWithContentCallback = (line: string) => T;\n\nexport function forEachLineWithContent(\n input: string,\n callback: LineWithContentCallback\n): T[] {\n return toLinesWithContent(input, true).map((line) => callback(line));\n}\n\nexport function folderExists(path: string): boolean {\n return exists(path, FOLDER);\n}\n\n/**\n * Adds `item` into the `target` `Array` or `Set` when it is not already present and returns the `item`.\n */\nexport function append(target: T[] | Set, item: T): typeof item {\n if (Array.isArray(target)) {\n if (!target.includes(item)) {\n target.push(item);\n }\n } else {\n target.add(item);\n }\n return item;\n}\n\n/**\n * Adds `item` into the `target` `Array` when it is not already present and returns the `target`.\n */\nexport function including(target: T[], item: T): typeof target {\n if (Array.isArray(target) && !target.includes(item)) {\n target.push(item);\n }\n\n return target;\n}\n\nexport function remove(target: Set | T[], item: T): T {\n if (Array.isArray(target)) {\n const index = target.indexOf(item);\n if (index >= 0) {\n target.splice(index, 1);\n }\n } else {\n target.delete(item);\n }\n return item;\n}\n\nexport const objectToString = Object.prototype.toString.call.bind(Object.prototype.toString) as (\n input: any\n) => string;\n\nexport function asArray(source: T | T[]): T[] {\n return Array.isArray(source) ? source : [source];\n}\n\nexport function asStringArray(source: T | T[]): string[] {\n return asArray(source).map(String);\n}\n\nexport function asNumber(source: string | null | undefined, onNaN = 0) {\n if (source == null) {\n return onNaN;\n }\n\n const num = parseInt(source, 10);\n return isNaN(num) ? onNaN : num;\n}\n\nexport function prefixedArray(input: T[], prefix: T): T[] {\n const output: T[] = [];\n for (let i = 0, max = input.length; i < max; i++) {\n output.push(prefix, input[i]);\n }\n return output;\n}\n\nexport function bufferToString(input: Buffer | Buffer[]): string {\n return (Array.isArray(input) ? Buffer.concat(input) : input).toString('utf-8');\n}\n\n/**\n * Get a new object from a source object with only the listed properties.\n */\nexport function pick(source: Record, properties: string[]) {\n return Object.assign(\n {},\n ...properties.map((property) => (property in source ? { [property]: source[property] } : {}))\n );\n}\n\nexport function delay(duration = 0): Promise {\n return new Promise((done) => setTimeout(done, duration));\n}\n\nexport function orVoid(input: T | false) {\n if (input === false) {\n return undefined;\n }\n return input;\n}\n", "import { Maybe, Options, Primitives } from '../types';\nimport { objectToString } from './util';\nimport { isPathSpec } from '../args/pathspec';\n\nexport interface ArgumentFilterPredicate {\n (input: any): input is T;\n}\n\nexport function filterType(\n input: K,\n filter: ArgumentFilterPredicate\n): K extends T ? T : undefined;\nexport function filterType(input: K, filter: ArgumentFilterPredicate, def: T): T;\nexport function filterType(input: K, filter: ArgumentFilterPredicate, def?: T): Maybe {\n if (filter(input)) {\n return input;\n }\n return arguments.length > 2 ? def : undefined;\n}\n\nexport const filterArray: ArgumentFilterPredicate> = (input): input is Array => {\n return Array.isArray(input);\n};\n\nexport function filterPrimitives(\n input: unknown,\n omit?: Array<'boolean' | 'string' | 'number'>\n): input is Primitives {\n const type = isPathSpec(input) ? 'string' : typeof input;\n\n return (\n /number|string|boolean/.test(type) &&\n (!omit || !omit.includes(type as 'boolean' | 'string' | 'number'))\n );\n}\n\nexport const filterString: ArgumentFilterPredicate = (input): input is string => {\n return typeof input === 'string';\n};\n\nexport const filterStringArray: ArgumentFilterPredicate = (input): input is string[] => {\n return Array.isArray(input) && input.every(filterString);\n};\n\nexport const filterStringOrStringArray: ArgumentFilterPredicate = (\n input\n): input is string | string[] => {\n return filterString(input) || (Array.isArray(input) && input.every(filterString));\n};\n\nexport function filterPlainObject(input: T | unknown): input is T;\nexport function filterPlainObject(input: T | unknown): input is T {\n return !!input && objectToString(input) === '[object Object]';\n}\n\nexport function filterFunction(input: unknown): input is Function {\n return typeof input === 'function';\n}\n\nexport const filterHasLength: ArgumentFilterPredicate<{ length: number }> = (\n input\n): input is { length: number } => {\n if (input == null || 'number|boolean|function'.includes(typeof input)) {\n return false;\n }\n return Array.isArray(input) || typeof input === 'string' || typeof input.length === 'number';\n};\n", "/**\n * Known process exit codes used by the task parsers to determine whether an error\n * was one they can automatically handle\n */\nexport enum ExitCodes {\n SUCCESS,\n ERROR,\n NOT_FOUND = -2,\n UNCLEAN = 128,\n}\n", "import { TaskResponseFormat } from '../types';\n\nexport class GitOutputStreams {\n constructor(\n public readonly stdOut: T,\n public readonly stdErr: T\n ) {}\n\n asStrings(): GitOutputStreams {\n return new GitOutputStreams(this.stdOut.toString('utf8'), this.stdErr.toString('utf8'));\n }\n}\n", "export class LineParser {\n protected matches: string[] = [];\n\n private _regExp: RegExp[];\n\n constructor(\n regExp: RegExp | RegExp[],\n useMatches?: (target: T, match: string[]) => boolean | void\n ) {\n this._regExp = Array.isArray(regExp) ? regExp : [regExp];\n if (useMatches) {\n this.useMatches = useMatches;\n }\n }\n\n parse = (line: (offset: number) => string | undefined, target: T): boolean => {\n this.resetMatches();\n\n if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) {\n return false;\n }\n\n return this.useMatches(target, this.prepareMatches()) !== false;\n };\n\n // @ts-ignore\n protected useMatches(target: T, match: string[]): boolean | void {\n throw new Error(`LineParser:useMatches not implemented`);\n }\n\n protected resetMatches() {\n this.matches.length = 0;\n }\n\n protected prepareMatches() {\n return this.matches;\n }\n\n protected addMatch(reg: RegExp, index: number, line?: string) {\n const matched = line && reg.exec(line);\n if (matched) {\n this.pushMatch(index, matched);\n }\n\n return !!matched;\n }\n\n protected pushMatch(_index: number, matched: string[]) {\n this.matches.push(...matched.slice(1));\n }\n}\n\nexport class RemoteLineParser extends LineParser {\n protected addMatch(reg: RegExp, index: number, line?: string): boolean {\n return /^remote:\\s/.test(String(line)) && super.addMatch(reg, index, line);\n }\n\n protected pushMatch(index: number, matched: string[]) {\n if (index > 0 || matched.length > 1) {\n super.pushMatch(index, matched);\n }\n }\n}\n", "import { SimpleGitOptions } from '../types';\n\nconst defaultOptions: Omit = {\n binary: 'git',\n maxConcurrentProcesses: 5,\n config: [],\n trimmed: false,\n};\n\nexport function createInstanceConfig(\n ...options: Array | undefined>\n): SimpleGitOptions {\n const baseDir = process.cwd();\n const config: SimpleGitOptions = Object.assign(\n { baseDir, ...defaultOptions },\n ...options.filter((o) => typeof o === 'object' && o)\n );\n\n config.baseDir = config.baseDir || baseDir;\n config.trimmed = config.trimmed === true;\n\n return config;\n}\n", "import {\n filterArray,\n filterFunction,\n filterPlainObject,\n filterPrimitives,\n filterType,\n} from './argument-filters';\nimport { asFunction, isUserFunction, last } from './util';\nimport { Maybe, Options, OptionsValues } from '../types';\nimport { isPathSpec } from '../args/pathspec';\n\nexport function appendTaskOptions(\n options: Maybe,\n commands: string[] = []\n): string[] {\n if (!filterPlainObject(options)) {\n return commands;\n }\n\n return Object.keys(options).reduce((commands: string[], key: string) => {\n const value: OptionsValues = options[key];\n\n if (isPathSpec(value)) {\n commands.push(value);\n } else if (filterPrimitives(value, ['boolean'])) {\n commands.push(key + '=' + value);\n } else {\n commands.push(key);\n }\n\n return commands;\n }, commands);\n}\n\nexport function getTrailingOptions(\n args: IArguments,\n initialPrimitive = 0,\n objectOnly = false\n): string[] {\n const command: string[] = [];\n\n for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) {\n if ('string|number'.includes(typeof args[i])) {\n command.push(String(args[i]));\n }\n }\n\n appendTaskOptions(trailingOptionsArgument(args), command);\n if (!objectOnly) {\n command.push(...trailingArrayArgument(args));\n }\n\n return command;\n}\n\nfunction trailingArrayArgument(args: IArguments) {\n const hasTrailingCallback = typeof last(args) === 'function';\n return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []);\n}\n\n/**\n * Given any number of arguments, returns the trailing options argument, ignoring a trailing function argument\n * if there is one. When not found, the return value is null.\n */\nexport function trailingOptionsArgument(args: IArguments): Maybe {\n const hasTrailingCallback = filterFunction(last(args));\n return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject);\n}\n\n/**\n * Returns either the source argument when it is a `Function`, or the default\n * `NOOP` function constant\n */\nexport function trailingFunctionArgument(\n args: unknown[] | IArguments | unknown,\n includeNoop = true\n): Maybe<(...args: any[]) => unknown> {\n const callback = asFunction(last(args));\n return includeNoop || isUserFunction(callback) ? callback : undefined;\n}\n", "import type { MaybeArray, TaskParser, TaskResponseFormat } from '../types';\nimport { GitOutputStreams } from './git-output-streams';\nimport { LineParser } from './line-parser';\nimport { asArray, toLinesWithContent } from './util';\n\nexport function callTaskParser(\n parser: TaskParser,\n streams: GitOutputStreams\n) {\n return parser(streams.stdOut, streams.stdErr);\n}\n\nexport function parseStringResponse(\n result: T,\n parsers: LineParser[],\n texts: MaybeArray,\n trim = true\n): T {\n asArray(texts).forEach((text) => {\n for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) {\n const line = (offset = 0) => {\n if (i + offset >= max) {\n return;\n }\n return lines[i + offset];\n };\n\n parsers.some(({ parse }) => parse(line, result));\n }\n });\n\n return result;\n}\n", "export * from './argument-filters';\nexport * from './exit-codes';\nexport * from './git-output-streams';\nexport * from './line-parser';\nexport * from './simple-git-options';\nexport * from './task-options';\nexport * from './task-parser';\nexport * from './util';\n", "import { ExitCodes } from '../utils';\nimport { Maybe, StringTask } from '../types';\n\nexport enum CheckRepoActions {\n BARE = 'bare',\n IN_TREE = 'tree',\n IS_REPO_ROOT = 'root',\n}\n\nconst onError: StringTask['onError'] = ({ exitCode }, error, done, fail) => {\n if (exitCode === ExitCodes.UNCLEAN && isNotRepoMessage(error)) {\n return done(Buffer.from('false'));\n }\n\n fail(error);\n};\n\nconst parser: StringTask['parser'] = (text) => {\n return text.trim() === 'true';\n};\n\nexport function checkIsRepoTask(action: Maybe): StringTask {\n switch (action) {\n case CheckRepoActions.BARE:\n return checkIsBareRepoTask();\n case CheckRepoActions.IS_REPO_ROOT:\n return checkIsRepoRootTask();\n }\n\n const commands = ['rev-parse', '--is-inside-work-tree'];\n\n return {\n commands,\n format: 'utf-8',\n onError,\n parser,\n };\n}\n\nexport function checkIsRepoRootTask(): StringTask {\n const commands = ['rev-parse', '--git-dir'];\n\n return {\n commands,\n format: 'utf-8',\n onError,\n parser(path) {\n return /^\\.(git)?$/.test(path.trim());\n },\n };\n}\n\nexport function checkIsBareRepoTask(): StringTask {\n const commands = ['rev-parse', '--is-bare-repository'];\n\n return {\n commands,\n format: 'utf-8',\n onError,\n parser,\n };\n}\n\nfunction isNotRepoMessage(error: Error): boolean {\n return /(Not a git repository|Kein Git-Repository)/i.test(String(error));\n}\n", "import { CleanSummary } from '../../../typings';\nimport { toLinesWithContent } from '../utils';\n\nexport class CleanResponse implements CleanSummary {\n public paths: string[] = [];\n public files: string[] = [];\n public folders: string[] = [];\n\n constructor(public readonly dryRun: boolean) {}\n}\n\nconst removalRegexp = /^[a-z]+\\s*/i;\nconst dryRunRemovalRegexp = /^[a-z]+\\s+[a-z]+\\s*/i;\nconst isFolderRegexp = /\\/$/;\n\nexport function cleanSummaryParser(dryRun: boolean, text: string): CleanSummary {\n const summary = new CleanResponse(dryRun);\n const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp;\n\n toLinesWithContent(text).forEach((line) => {\n const removed = line.replace(regexp, '');\n\n summary.paths.push(removed);\n (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed);\n });\n\n return summary;\n}\n", "import { TaskConfigurationError } from '../errors/task-configuration-error';\nimport type { BufferTask, EmptyTaskParser, SimpleGitTask, StringTask } from '../types';\n\nexport const EMPTY_COMMANDS: [] = [];\n\nexport type EmptyTask = {\n commands: typeof EMPTY_COMMANDS;\n format: 'empty';\n parser: EmptyTaskParser;\n onError?: undefined;\n};\n\nexport function adhocExecTask(parser: EmptyTaskParser): EmptyTask {\n return {\n commands: EMPTY_COMMANDS,\n format: 'empty',\n parser,\n };\n}\n\nexport function configurationErrorTask(error: Error | string): EmptyTask {\n return {\n commands: EMPTY_COMMANDS,\n format: 'empty',\n parser() {\n throw typeof error === 'string' ? new TaskConfigurationError(error) : error;\n },\n };\n}\n\nexport function straightThroughStringTask(commands: string[], trimmed = false): StringTask {\n return {\n commands,\n format: 'utf-8',\n parser(text) {\n return trimmed ? String(text).trim() : text;\n },\n };\n}\n\nexport function straightThroughBufferTask(commands: string[]): BufferTask {\n return {\n commands,\n format: 'buffer',\n parser(buffer) {\n return buffer;\n },\n };\n}\n\nexport function isBufferTask(task: SimpleGitTask): task is BufferTask {\n return task.format === 'buffer';\n}\n\nexport function isEmptyTask(task: SimpleGitTask): task is EmptyTask {\n return task.format === 'empty' || !task.commands.length;\n}\n", "import { CleanSummary } from '../../../typings';\nimport { cleanSummaryParser } from '../responses/CleanSummary';\nimport { Maybe, StringTask } from '../types';\nimport { asStringArray } from '../utils';\nimport { configurationErrorTask } from './task';\n\nexport const CONFIG_ERROR_INTERACTIVE_MODE = 'Git clean interactive mode is not supported';\nexport const CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter (\"n\" or \"f\") is required';\nexport const CONFIG_ERROR_UNKNOWN_OPTION = 'Git clean unknown option found in: ';\n\n/**\n * All supported option switches available for use in a `git.clean` operation\n */\nexport enum CleanOptions {\n DRY_RUN = 'n',\n FORCE = 'f',\n IGNORED_INCLUDED = 'x',\n IGNORED_ONLY = 'X',\n EXCLUDING = 'e',\n QUIET = 'q',\n RECURSIVE = 'd',\n}\n\n/**\n * The two modes `git.clean` can run in - one of these must be supplied in order\n * for the command to not throw a `TaskConfigurationError`\n */\nexport type CleanMode = CleanOptions.FORCE | CleanOptions.DRY_RUN;\n\nconst CleanOptionValues: Set = new Set([\n 'i',\n ...asStringArray(Object.values(CleanOptions as any)),\n]);\n\nexport function cleanWithOptionsTask(mode: CleanMode | string, customArgs: string[]) {\n const { cleanMode, options, valid } = getCleanOptions(mode);\n\n if (!cleanMode) {\n return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED);\n }\n\n if (!valid.options) {\n return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode));\n }\n\n options.push(...customArgs);\n\n if (options.some(isInteractiveMode)) {\n return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE);\n }\n\n return cleanTask(cleanMode, options);\n}\n\nexport function cleanTask(mode: CleanMode, customArgs: string[]): StringTask {\n const commands: string[] = ['clean', `-${mode}`, ...customArgs];\n\n return {\n commands,\n format: 'utf-8',\n parser(text: string): CleanSummary {\n return cleanSummaryParser(mode === CleanOptions.DRY_RUN, text);\n },\n };\n}\n\nexport function isCleanOptionsArray(input: string[]): input is CleanOptions[] {\n return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test));\n}\n\nfunction getCleanOptions(input: string) {\n let cleanMode: Maybe;\n let options: string[] = [];\n let valid = { cleanMode: false, options: true };\n\n input\n .replace(/[^a-z]i/g, '')\n .split('')\n .forEach((char) => {\n if (isCleanMode(char)) {\n cleanMode = char;\n valid.cleanMode = true;\n } else {\n valid.options = valid.options && isKnownOption((options[options.length] = `-${char}`));\n }\n });\n\n return {\n cleanMode,\n options,\n valid,\n };\n}\n\nfunction isCleanMode(cleanMode?: string): cleanMode is CleanMode {\n return cleanMode === CleanOptions.FORCE || cleanMode === CleanOptions.DRY_RUN;\n}\n\nfunction isKnownOption(option: string): boolean {\n return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1));\n}\n\nfunction isInteractiveMode(option: string): boolean {\n if (/^-[^\\-]/.test(option)) {\n return option.indexOf('i') > 0;\n }\n\n return option === '--interactive';\n}\n", "import { ConfigGetResult, ConfigListSummary, ConfigValues } from '../../../typings';\nimport { last, splitOn } from '../utils';\n\nexport class ConfigList implements ConfigListSummary {\n public files: string[] = [];\n public values: { [fileName: string]: ConfigValues } = Object.create(null);\n\n private _all: ConfigValues | undefined;\n\n public get all(): ConfigValues {\n if (!this._all) {\n this._all = this.files.reduce((all: ConfigValues, file: string) => {\n return Object.assign(all, this.values[file]);\n }, {});\n }\n\n return this._all;\n }\n\n public addFile(file: string): ConfigValues {\n if (!(file in this.values)) {\n const latest = last(this.files);\n this.values[file] = latest ? Object.create(this.values[latest]) : {};\n\n this.files.push(file);\n }\n\n return this.values[file];\n }\n\n public addValue(file: string, key: string, value: string) {\n const values = this.addFile(file);\n\n if (!values.hasOwnProperty(key)) {\n values[key] = value;\n } else if (Array.isArray(values[key])) {\n (values[key] as string[]).push(value);\n } else {\n values[key] = [values[key] as string, value];\n }\n\n this._all = undefined;\n }\n}\n\nexport function configListParser(text: string): ConfigList {\n const config = new ConfigList();\n\n for (const item of configParser(text)) {\n config.addValue(item.file, String(item.key), item.value);\n }\n\n return config;\n}\n\nexport function configGetParser(text: string, key: string): ConfigGetResult {\n let value: string | null = null;\n const values: string[] = [];\n const scopes: Map = new Map();\n\n for (const item of configParser(text, key)) {\n if (item.key !== key) {\n continue;\n }\n\n values.push((value = item.value));\n\n if (!scopes.has(item.file)) {\n scopes.set(item.file, []);\n }\n\n scopes.get(item.file)!.push(value);\n }\n\n return {\n key,\n paths: Array.from(scopes.keys()),\n scopes,\n value,\n values,\n };\n}\n\nfunction configFilePath(filePath: string): string {\n return filePath.replace(/^(file):/, '');\n}\n\nfunction* configParser(text: string, requestedKey: string | null = null) {\n const lines = text.split('\\0');\n\n for (let i = 0, max = lines.length - 1; i < max; ) {\n const file = configFilePath(lines[i++]);\n\n let value = lines[i++];\n let key = requestedKey;\n\n if (value.includes('\\n')) {\n const line = splitOn(value, '\\n');\n key = line[0];\n value = line[1];\n }\n\n yield { file, key, value };\n }\n}\n", "import type { ConfigGetResult, ConfigListSummary, SimpleGit } from '../../../typings';\nimport { configGetParser, configListParser } from '../responses/ConfigList';\nimport type { SimpleGitApi } from '../simple-git-api';\nimport type { StringTask } from '../types';\nimport { trailingFunctionArgument } from '../utils';\n\nexport enum GitConfigScope {\n system = 'system',\n global = 'global',\n local = 'local',\n worktree = 'worktree',\n}\n\nfunction asConfigScope(\n scope: GitConfigScope | unknown,\n fallback: T\n): GitConfigScope | T {\n if (typeof scope === 'string' && GitConfigScope.hasOwnProperty(scope)) {\n return scope as GitConfigScope;\n }\n return fallback;\n}\n\nfunction addConfigTask(\n key: string,\n value: string,\n append: boolean,\n scope: GitConfigScope\n): StringTask {\n const commands: string[] = ['config', `--${scope}`];\n\n if (append) {\n commands.push('--add');\n }\n\n commands.push(key, value);\n\n return {\n commands,\n format: 'utf-8',\n parser(text: string): string {\n return text;\n },\n };\n}\n\nfunction getConfigTask(key: string, scope?: GitConfigScope): StringTask {\n const commands: string[] = ['config', '--null', '--show-origin', '--get-all', key];\n\n if (scope) {\n commands.splice(1, 0, `--${scope}`);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser(text) {\n return configGetParser(text, key);\n },\n };\n}\n\nfunction listConfigTask(scope?: GitConfigScope): StringTask {\n const commands = ['config', '--list', '--show-origin', '--null'];\n\n if (scope) {\n commands.push(`--${scope}`);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser(text: string) {\n return configListParser(text);\n },\n };\n}\n\nexport default function (): Pick {\n return {\n addConfig(this: SimpleGitApi, key: string, value: string, ...rest: unknown[]) {\n return this._runTask(\n addConfigTask(\n key,\n value,\n rest[0] === true,\n asConfigScope(rest[1], GitConfigScope.local)\n ),\n trailingFunctionArgument(arguments)\n );\n },\n\n getConfig(this: SimpleGitApi, key: string, scope?: GitConfigScope) {\n return this._runTask(\n getConfigTask(key, asConfigScope(scope, undefined)),\n trailingFunctionArgument(arguments)\n );\n },\n\n listConfig(this: SimpleGitApi, ...rest: unknown[]) {\n return this._runTask(\n listConfigTask(asConfigScope(rest[0], undefined)),\n trailingFunctionArgument(arguments)\n );\n },\n };\n}\n", "export enum DiffNameStatus {\n ADDED = 'A',\n COPIED = 'C',\n DELETED = 'D',\n MODIFIED = 'M',\n RENAMED = 'R',\n CHANGED = 'T',\n UNMERGED = 'U',\n UNKNOWN = 'X',\n BROKEN = 'B',\n}\n\nconst diffNameStatus = new Set(Object.values(DiffNameStatus));\n\nexport function isDiffNameStatus(input: string): input is DiffNameStatus {\n return diffNameStatus.has(input as DiffNameStatus);\n}\n", "import { GrepResult, SimpleGit } from '../../../typings';\nimport { SimpleGitApi } from '../simple-git-api';\nimport {\n asNumber,\n forEachLineWithContent,\n getTrailingOptions,\n NULL,\n prefixedArray,\n trailingFunctionArgument,\n} from '../utils';\n\nimport { configurationErrorTask } from './task';\n\nconst disallowedOptions = ['-h'];\n\nconst Query = Symbol('grepQuery');\n\nexport interface GitGrepQuery extends Iterable {\n /** Adds one or more terms to be grouped as an \"and\" to any other terms */\n and(...and: string[]): this;\n\n /** Adds one or more search terms - git.grep will \"or\" this to other terms */\n param(...param: string[]): this;\n}\n\nclass GrepQuery implements GitGrepQuery {\n private [Query]: string[] = [];\n\n *[Symbol.iterator]() {\n for (const query of this[Query]) {\n yield query;\n }\n }\n\n and(...and: string[]) {\n and.length && this[Query].push('--and', '(', ...prefixedArray(and, '-e'), ')');\n return this;\n }\n\n param(...param: string[]) {\n this[Query].push(...prefixedArray(param, '-e'));\n return this;\n }\n}\n\n/**\n * Creates a new builder for a `git.grep` query with optional params\n */\nexport function grepQueryBuilder(...params: string[]): GitGrepQuery {\n return new GrepQuery().param(...params);\n}\n\nfunction parseGrep(grep: string): GrepResult {\n const paths: GrepResult['paths'] = new Set();\n const results: GrepResult['results'] = {};\n\n forEachLineWithContent(grep, (input) => {\n const [path, line, preview] = input.split(NULL);\n paths.add(path);\n (results[path] = results[path] || []).push({\n line: asNumber(line),\n path,\n preview,\n });\n });\n\n return {\n paths,\n results,\n };\n}\n\nexport default function (): Pick {\n return {\n grep(this: SimpleGitApi, searchTerm: string | GitGrepQuery) {\n const then = trailingFunctionArgument(arguments);\n const options = getTrailingOptions(arguments);\n\n for (const option of disallowedOptions) {\n if (options.includes(option)) {\n return this._runTask(\n configurationErrorTask(`git.grep: use of \"${option}\" is not supported.`),\n then\n );\n }\n }\n\n if (typeof searchTerm === 'string') {\n searchTerm = grepQueryBuilder().param(searchTerm);\n }\n\n const commands = ['grep', '--null', '-n', '--full-name', ...options, ...searchTerm];\n\n return this._runTask(\n {\n commands,\n format: 'utf-8',\n parser(stdOut) {\n return parseGrep(stdOut);\n },\n },\n then\n );\n },\n };\n}\n", "import { straightThroughStringTask } from './task';\nimport { Maybe, OptionFlags, Options } from '../types';\n\nexport enum ResetMode {\n MIXED = 'mixed',\n SOFT = 'soft',\n HARD = 'hard',\n MERGE = 'merge',\n KEEP = 'keep',\n}\n\nconst ResetModes = Array.from(Object.values(ResetMode));\n\nexport type ResetOptions = Options &\n OptionFlags<'-q' | '--quiet' | '--no-quiet' | '--pathspec-from-nul'> &\n OptionFlags<'--pathspec-from-file', string>;\n\nexport function resetTask(mode: Maybe, customArgs: string[]) {\n const commands: string[] = ['reset'];\n if (isValidResetMode(mode)) {\n commands.push(`--${mode}`);\n }\n commands.push(...customArgs);\n\n return straightThroughStringTask(commands);\n}\n\nexport function getResetMode(mode: ResetMode | any): Maybe {\n if (isValidResetMode(mode)) {\n return mode;\n }\n\n switch (typeof mode) {\n case 'string':\n case 'undefined':\n return ResetMode.SOFT;\n }\n\n return;\n}\n\nfunction isValidResetMode(mode: ResetMode | any): mode is ResetMode {\n return ResetModes.includes(mode);\n}\n", "import debug, { Debugger } from 'debug';\nimport {\n append,\n filterHasLength,\n filterString,\n filterType,\n NOOP,\n objectToString,\n remove,\n} from './utils';\nimport { Maybe } from './types';\n\ndebug.formatters.L = (value: any) => String(filterHasLength(value) ? value.length : '-');\ndebug.formatters.B = (value: Buffer) => {\n if (Buffer.isBuffer(value)) {\n return value.toString('utf8');\n }\n return objectToString(value);\n};\n\ntype OutputLoggingHandler = (message: string, ...args: any[]) => void;\n\nfunction createLog() {\n return debug('simple-git');\n}\n\nexport interface OutputLogger extends OutputLoggingHandler {\n readonly label: string;\n\n info: OutputLoggingHandler;\n step(nextStep?: string): OutputLogger;\n sibling(name: string): OutputLogger;\n}\n\nfunction prefixedLogger(\n to: Debugger,\n prefix: string,\n forward?: OutputLoggingHandler\n): OutputLoggingHandler {\n if (!prefix || !String(prefix).replace(/\\s*/, '')) {\n return !forward\n ? to\n : (message, ...args) => {\n to(message, ...args);\n forward(message, ...args);\n };\n }\n\n return (message, ...args) => {\n to(`%s ${message}`, prefix, ...args);\n if (forward) {\n forward(message, ...args);\n }\n };\n}\n\nfunction childLoggerName(\n name: Maybe,\n childDebugger: Maybe,\n { namespace: parentNamespace }: Debugger\n): string {\n if (typeof name === 'string') {\n return name;\n }\n const childNamespace = (childDebugger && childDebugger.namespace) || '';\n\n if (childNamespace.startsWith(parentNamespace)) {\n return childNamespace.substr(parentNamespace.length + 1);\n }\n\n return childNamespace || parentNamespace;\n}\n\nexport function createLogger(\n label: string,\n verbose?: string | Debugger,\n initialStep?: string,\n infoDebugger = createLog()\n): OutputLogger {\n const labelPrefix = (label && `[${label}]`) || '';\n\n const spawned: OutputLogger[] = [];\n const debugDebugger: Maybe =\n typeof verbose === 'string' ? infoDebugger.extend(verbose) : verbose;\n const key = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger);\n\n return step(initialStep);\n\n function sibling(name: string, initial?: string) {\n return append(\n spawned,\n createLogger(label, key.replace(/^[^:]+/, name), initial, infoDebugger)\n );\n }\n\n function step(phase?: string) {\n const stepPrefix = (phase && `[${phase}]`) || '';\n const debug = (debugDebugger && prefixedLogger(debugDebugger, stepPrefix)) || NOOP;\n const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug);\n\n return Object.assign(debugDebugger ? debug : info, {\n label,\n sibling,\n info,\n step,\n });\n }\n}\n\n/**\n * The `GitLogger` is used by the main `SimpleGit` runner to handle logging\n * any warnings or errors.\n */\nexport class GitLogger {\n public error: OutputLoggingHandler;\n\n public warn: OutputLoggingHandler;\n\n constructor(private _out: Debugger = createLog()) {\n this.error = prefixedLogger(_out, '[ERROR]');\n this.warn = prefixedLogger(_out, '[WARN]');\n }\n\n silent(silence = false) {\n if (silence !== this._out.enabled) {\n return;\n }\n\n const { namespace } = this._out;\n const env = (process.env.DEBUG || '').split(',').filter((s) => !!s);\n const hasOn = env.includes(namespace);\n const hasOff = env.includes(`-${namespace}`);\n\n // enabling the log\n if (!silence) {\n if (hasOff) {\n remove(env, `-${namespace}`);\n } else {\n env.push(namespace);\n }\n } else {\n if (hasOn) {\n remove(env, namespace);\n } else {\n env.push(`-${namespace}`);\n }\n }\n\n debug.enable(env.join(','));\n }\n}\n", "import { SimpleGitTask } from '../types';\nimport { GitError } from '../errors/git-error';\nimport { createLogger, OutputLogger } from '../git-logger';\n\ntype AnySimpleGitTask = SimpleGitTask;\n\ntype TaskInProgress = {\n name: string;\n logger: OutputLogger;\n task: AnySimpleGitTask;\n};\n\nexport class TasksPendingQueue {\n private _queue: Map = new Map();\n\n constructor(private logLabel = 'GitExecutor') {}\n\n private withProgress(task: AnySimpleGitTask) {\n return this._queue.get(task);\n }\n\n private createProgress(task: AnySimpleGitTask): TaskInProgress {\n const name = TasksPendingQueue.getName(task.commands[0]);\n const logger = createLogger(this.logLabel, name);\n\n return {\n task,\n logger,\n name,\n };\n }\n\n push(task: AnySimpleGitTask): TaskInProgress {\n const progress = this.createProgress(task);\n progress.logger('Adding task to the queue, commands = %o', task.commands);\n\n this._queue.set(task, progress);\n\n return progress;\n }\n\n fatal(err: GitError) {\n for (const [task, { logger }] of Array.from(this._queue.entries())) {\n if (task === err.task) {\n logger.info(`Failed %o`, err);\n logger(\n `Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`\n );\n } else {\n logger.info(\n `A fatal exception occurred in a previous task, the queue has been purged: %o`,\n err.message\n );\n }\n\n this.complete(task);\n }\n\n if (this._queue.size !== 0) {\n throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`);\n }\n }\n\n complete(task: AnySimpleGitTask) {\n const progress = this.withProgress(task);\n if (progress) {\n this._queue.delete(task);\n }\n }\n\n attempt(task: AnySimpleGitTask): TaskInProgress {\n const progress = this.withProgress(task);\n if (!progress) {\n throw new GitError(undefined, 'TasksPendingQueue: attempt called for an unknown task');\n }\n progress.logger('Starting task');\n\n return progress;\n }\n\n static getName(name = 'empty') {\n return `task:${name}:${++TasksPendingQueue.counter}`;\n }\n\n private static counter = 0;\n}\n", "import { spawn, SpawnOptions } from 'child_process';\nimport { GitError } from '../errors/git-error';\nimport { OutputLogger } from '../git-logger';\nimport { PluginStore } from '../plugins';\nimport { EmptyTask, isBufferTask, isEmptyTask } from '../tasks/task';\nimport {\n GitExecutorResult,\n Maybe,\n outputHandler,\n RunnableTask,\n SimpleGitExecutor,\n SimpleGitTask,\n} from '../types';\nimport { callTaskParser, first, GitOutputStreams, objectToString } from '../utils';\nimport { Scheduler } from './scheduler';\nimport { TasksPendingQueue } from './tasks-pending-queue';\n\nexport class GitExecutorChain implements SimpleGitExecutor {\n private _chain: Promise = Promise.resolve();\n private _queue = new TasksPendingQueue();\n private _cwd: string | undefined;\n\n public get cwd() {\n return this._cwd || this._executor.cwd;\n }\n\n public set cwd(cwd: string) {\n this._cwd = cwd;\n }\n\n public get env() {\n return this._executor.env;\n }\n\n public get outputHandler() {\n return this._executor.outputHandler;\n }\n\n constructor(\n private _executor: SimpleGitExecutor,\n private _scheduler: Scheduler,\n private _plugins: PluginStore\n ) {}\n\n public chain() {\n return this;\n }\n\n public push(task: SimpleGitTask): Promise {\n this._queue.push(task);\n\n return (this._chain = this._chain.then(() => this.attemptTask(task)));\n }\n\n private async attemptTask(task: SimpleGitTask): Promise {\n const onScheduleComplete = await this._scheduler.next();\n const onQueueComplete = () => this._queue.complete(task);\n\n try {\n const { logger } = this._queue.attempt(task);\n return (await (isEmptyTask(task)\n ? this.attemptEmptyTask(task, logger)\n : this.attemptRemoteTask(task, logger))) as R;\n } catch (e) {\n throw this.onFatalException(task, e as Error);\n } finally {\n onQueueComplete();\n onScheduleComplete();\n }\n }\n\n private onFatalException(task: SimpleGitTask, e: Error) {\n const gitError =\n e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e));\n\n this._chain = Promise.resolve();\n this._queue.fatal(gitError);\n\n return gitError;\n }\n\n private async attemptRemoteTask(task: RunnableTask, logger: OutputLogger) {\n const binary = this._plugins.exec('spawn.binary', '', pluginContext(task, task.commands));\n const args = this._plugins.exec(\n 'spawn.args',\n [...task.commands],\n pluginContext(task, task.commands)\n );\n\n const raw = await this.gitResponse(\n task,\n binary,\n args,\n this.outputHandler,\n logger.step('SPAWN')\n );\n const outputStreams = await this.handleTaskData(task, args, raw, logger.step('HANDLE'));\n\n logger(`passing response to task's parser as a %s`, task.format);\n\n if (isBufferTask(task)) {\n return callTaskParser(task.parser, outputStreams);\n }\n\n return callTaskParser(task.parser, outputStreams.asStrings());\n }\n\n private async attemptEmptyTask(task: EmptyTask, logger: OutputLogger) {\n logger(`empty task bypassing child process to call to task's parser`);\n return task.parser(this);\n }\n\n private handleTaskData(\n task: SimpleGitTask,\n args: string[],\n result: GitExecutorResult,\n logger: OutputLogger\n ): Promise {\n const { exitCode, rejection, stdOut, stdErr } = result;\n\n return new Promise((done, fail) => {\n logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode);\n\n const { error } = this._plugins.exec(\n 'task.error',\n { error: rejection },\n {\n ...pluginContext(task, args),\n ...result,\n }\n );\n\n if (error && task.onError) {\n logger.info(`exitCode=%s handling with custom error handler`);\n\n return task.onError(\n result,\n error,\n (newStdOut) => {\n logger.info(`custom error handler treated as success`);\n logger(`custom error returned a %s`, objectToString(newStdOut));\n\n done(\n new GitOutputStreams(\n Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut,\n Buffer.concat(stdErr)\n )\n );\n },\n fail\n );\n }\n\n if (error) {\n logger.info(\n `handling as error: exitCode=%s stdErr=%s rejection=%o`,\n exitCode,\n stdErr.length,\n rejection\n );\n return fail(error);\n }\n\n logger.info(`retrieving task output complete`);\n done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr)));\n });\n }\n\n private async gitResponse(\n task: SimpleGitTask,\n command: string,\n args: string[],\n outputHandler: Maybe,\n logger: OutputLogger\n ): Promise {\n const outputLogger = logger.sibling('output');\n const spawnOptions: SpawnOptions = this._plugins.exec(\n 'spawn.options',\n {\n cwd: this.cwd,\n env: this.env,\n windowsHide: true,\n },\n pluginContext(task, task.commands)\n );\n\n return new Promise((done) => {\n const stdOut: Buffer[] = [];\n const stdErr: Buffer[] = [];\n\n logger.info(`%s %o`, command, args);\n logger('%O', spawnOptions);\n\n let rejection = this._beforeSpawn(task, args);\n if (rejection) {\n return done({\n stdOut,\n stdErr,\n exitCode: 9901,\n rejection,\n });\n }\n\n this._plugins.exec('spawn.before', undefined, {\n ...pluginContext(task, args),\n kill(reason) {\n rejection = reason || rejection;\n },\n });\n\n const spawned = spawn(command, args, spawnOptions);\n\n spawned.stdout!.on(\n 'data',\n onDataReceived(stdOut, 'stdOut', logger, outputLogger.step('stdOut'))\n );\n spawned.stderr!.on(\n 'data',\n onDataReceived(stdErr, 'stdErr', logger, outputLogger.step('stdErr'))\n );\n\n spawned.on('error', onErrorReceived(stdErr, logger));\n\n if (outputHandler) {\n logger(`Passing child process stdOut/stdErr to custom outputHandler`);\n outputHandler(command, spawned.stdout!, spawned.stderr!, [...args]);\n }\n\n this._plugins.exec('spawn.after', undefined, {\n ...pluginContext(task, args),\n spawned,\n close(exitCode: number, reason?: Error) {\n done({\n stdOut,\n stdErr,\n exitCode,\n rejection: rejection || reason,\n });\n },\n kill(reason: Error) {\n if (spawned.killed) {\n return;\n }\n\n rejection = reason;\n spawned.kill('SIGINT');\n },\n });\n });\n }\n\n private _beforeSpawn(task: SimpleGitTask, args: string[]) {\n let rejection: Maybe;\n this._plugins.exec('spawn.before', undefined, {\n ...pluginContext(task, args),\n kill(reason) {\n rejection = reason || rejection;\n },\n });\n\n return rejection;\n }\n}\n\nfunction pluginContext(task: SimpleGitTask, commands: string[]) {\n return {\n method: first(task.commands) || '',\n commands,\n };\n}\n\nfunction onErrorReceived(target: Buffer[], logger: OutputLogger) {\n return (err: Error) => {\n logger(`[ERROR] child process exception %o`, err);\n target.push(Buffer.from(String(err.stack), 'ascii'));\n };\n}\n\nfunction onDataReceived(\n target: Buffer[],\n name: string,\n logger: OutputLogger,\n output: OutputLogger\n) {\n return (buffer: Buffer) => {\n logger(`%s received %L bytes`, name, buffer);\n output(`%B`, buffer);\n target.push(buffer);\n };\n}\n", "import type { PluginStore } from '../plugins';\nimport type { GitExecutorEnv, outputHandler, SimpleGitExecutor, SimpleGitTask } from '../types';\n\nimport { GitExecutorChain } from './git-executor-chain';\nimport { Scheduler } from './scheduler';\n\nexport class GitExecutor implements SimpleGitExecutor {\n private _chain = new GitExecutorChain(this, this._scheduler, this._plugins);\n\n public env: GitExecutorEnv;\n public outputHandler?: outputHandler;\n\n constructor(\n public cwd: string,\n private _scheduler: Scheduler,\n private _plugins: PluginStore\n ) {}\n\n chain(): SimpleGitExecutor {\n return new GitExecutorChain(this, this._scheduler, this._plugins);\n }\n\n push(task: SimpleGitTask): Promise {\n return this._chain.push(task);\n }\n}\n", "import { GitError } from './errors/git-error';\nimport { GitResponseError } from './errors/git-response-error';\nimport { SimpleGitTask, SimpleGitTaskCallback } from './types';\nimport { NOOP } from './utils';\n\nexport function taskCallback(\n task: SimpleGitTask,\n response: Promise,\n callback: SimpleGitTaskCallback = NOOP\n) {\n const onSuccess = (data: R) => {\n callback(null, data);\n };\n\n const onError = (err: GitError | GitResponseError) => {\n if (err?.task === task) {\n callback(\n err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err,\n undefined as any\n );\n }\n };\n\n response.then(onSuccess, onError);\n}\n\nfunction addDeprecationNoticeToError(err: GitResponseError) {\n let log = (name: string) => {\n console.warn(\n `simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3`\n );\n log = NOOP;\n };\n\n return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {}));\n\n function descriptorReducer(all: PropertyDescriptorMap, name: string): typeof all {\n if (name in err) {\n return all;\n }\n\n all[name] = {\n enumerable: false,\n configurable: false,\n get() {\n log(name);\n return err.git[name];\n },\n };\n\n return all;\n }\n}\n", "import { folderExists } from '../utils';\nimport { SimpleGitExecutor } from '../types';\nimport { adhocExecTask } from './task';\n\nexport function changeWorkingDirectoryTask(directory: string, root?: SimpleGitExecutor) {\n return adhocExecTask((instance: SimpleGitExecutor) => {\n if (!folderExists(directory)) {\n throw new Error(`Git.cwd: cannot change to non-directory \"${directory}\"`);\n }\n\n return ((root || instance).cwd = directory);\n });\n}\n", "import type { SimpleGit } from '../../../typings';\nimport type { SimpleGitApi } from '../simple-git-api';\nimport { getTrailingOptions, remove, trailingFunctionArgument } from '../utils';\nimport { straightThroughStringTask } from './task';\n\nfunction checkoutTask(args: string[]) {\n const commands = ['checkout', ...args];\n if (commands[1] === '-b' && commands.includes('-B')) {\n commands[1] = remove(commands, '-B');\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport default function (): Pick {\n return {\n checkout(this: SimpleGitApi) {\n return this._runTask(\n checkoutTask(getTrailingOptions(arguments, 1)),\n trailingFunctionArgument(arguments)\n );\n },\n\n checkoutBranch(this: SimpleGitApi, branchName, startPoint) {\n return this._runTask(\n checkoutTask(['-b', branchName, startPoint, ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments)\n );\n },\n\n checkoutLocalBranch(this: SimpleGitApi, branchName) {\n return this._runTask(\n checkoutTask(['-b', branchName, ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments)\n );\n },\n };\n}\n", "import { CommitResult } from '../../../typings';\nimport { LineParser, parseStringResponse } from '../utils';\n\nconst parsers: LineParser[] = [\n new LineParser(/^\\[([^\\s]+)( \\([^)]+\\))? ([^\\]]+)/, (result, [branch, root, commit]) => {\n result.branch = branch;\n result.commit = commit;\n result.root = !!root;\n }),\n new LineParser(/\\s*Author:\\s(.+)/i, (result, [author]) => {\n const parts = author.split('<');\n const email = parts.pop();\n\n if (!email || !email.includes('@')) {\n return;\n }\n\n result.author = {\n email: email.substr(0, email.length - 1),\n name: parts.join('<').trim(),\n };\n }),\n new LineParser(\n /(\\d+)[^,]*(?:,\\s*(\\d+)[^,]*)(?:,\\s*(\\d+))/g,\n (result, [changes, insertions, deletions]) => {\n result.summary.changes = parseInt(changes, 10) || 0;\n result.summary.insertions = parseInt(insertions, 10) || 0;\n result.summary.deletions = parseInt(deletions, 10) || 0;\n }\n ),\n new LineParser(\n /^(\\d+)[^,]*(?:,\\s*(\\d+)[^(]+\\(([+-]))?/,\n (result, [changes, lines, direction]) => {\n result.summary.changes = parseInt(changes, 10) || 0;\n const count = parseInt(lines, 10) || 0;\n if (direction === '-') {\n result.summary.deletions = count;\n } else if (direction === '+') {\n result.summary.insertions = count;\n }\n }\n ),\n];\n\nexport function parseCommitResult(stdOut: string): CommitResult {\n const result: CommitResult = {\n author: null,\n branch: '',\n commit: '',\n root: false,\n summary: {\n changes: 0,\n insertions: 0,\n deletions: 0,\n },\n };\n return parseStringResponse(result, parsers, stdOut);\n}\n", "import type { CommitResult, SimpleGit } from '../../../typings';\nimport type { SimpleGitApi } from '../simple-git-api';\nimport type { StringTask } from '../types';\nimport { parseCommitResult } from '../parsers/parse-commit';\nimport {\n asArray,\n filterArray,\n filterStringOrStringArray,\n filterType,\n getTrailingOptions,\n prefixedArray,\n trailingFunctionArgument,\n} from '../utils';\nimport { configurationErrorTask } from './task';\n\nexport function commitTask(\n message: string[],\n files: string[],\n customArgs: string[]\n): StringTask {\n const commands: string[] = [\n '-c',\n 'core.abbrev=40',\n 'commit',\n ...prefixedArray(message, '-m'),\n ...files,\n ...customArgs,\n ];\n\n return {\n commands,\n format: 'utf-8',\n parser: parseCommitResult,\n };\n}\n\nexport default function (): Pick {\n return {\n commit(this: SimpleGitApi, message: string | string[], ...rest: unknown[]) {\n const next = trailingFunctionArgument(arguments);\n const task =\n rejectDeprecatedSignatures(message) ||\n commitTask(\n asArray(message),\n asArray(filterType(rest[0], filterStringOrStringArray, [])),\n [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)]\n );\n\n return this._runTask(task, next);\n },\n };\n\n function rejectDeprecatedSignatures(message?: unknown) {\n return (\n !filterStringOrStringArray(message) &&\n configurationErrorTask(\n `git.commit: requires the commit message to be supplied as a string/string[]`\n )\n );\n }\n}\n", "import { Response, SimpleGit } from '../../../typings';\nimport { SimpleGitApi } from '../simple-git-api';\nimport { trailingFunctionArgument } from '../utils';\nimport { straightThroughStringTask } from './task';\n\nexport default function (): Pick {\n return {\n firstCommit(this: SimpleGitApi): Response {\n return this._runTask(\n straightThroughStringTask(['rev-list', '--max-parents=0', 'HEAD'], true),\n trailingFunctionArgument(arguments)\n );\n },\n };\n}\n", "import { straightThroughStringTask } from './task';\nimport { StringTask } from '../types';\n\n/**\n * Task used by `git.hashObject`\n */\nexport function hashObjectTask(filePath: string, write: boolean): StringTask {\n const commands = ['hash-object', filePath];\n if (write) {\n commands.push('-w');\n }\n\n return straightThroughStringTask(commands, true);\n}\n", "import { InitResult } from '../../../typings';\n\nexport class InitSummary implements InitResult {\n constructor(\n public readonly bare: boolean,\n public readonly path: string,\n public readonly existing: boolean,\n public readonly gitDir: string\n ) {}\n}\n\nconst initResponseRegex = /^Init.+ repository in (.+)$/;\nconst reInitResponseRegex = /^Rein.+ in (.+)$/;\n\nexport function parseInit(bare: boolean, path: string, text: string) {\n const response = String(text).trim();\n let result;\n\n if ((result = initResponseRegex.exec(response))) {\n return new InitSummary(bare, path, false, result[1]);\n }\n\n if ((result = reInitResponseRegex.exec(response))) {\n return new InitSummary(bare, path, true, result[1]);\n }\n\n let gitDir = '';\n const tokens = response.split(' ');\n while (tokens.length) {\n const token = tokens.shift();\n if (token === 'in') {\n gitDir = tokens.join(' ');\n break;\n }\n }\n\n return new InitSummary(bare, path, /^re/i.test(response), gitDir);\n}\n", "import { InitResult } from '../../../typings';\nimport { parseInit } from '../responses/InitSummary';\nimport { StringTask } from '../types';\n\nconst bareCommand = '--bare';\n\nfunction hasBareCommand(command: string[]) {\n return command.includes(bareCommand);\n}\n\nexport function initTask(bare = false, path: string, customArgs: string[]): StringTask {\n const commands = ['init', ...customArgs];\n if (bare && !hasBareCommand(commands)) {\n commands.splice(1, 0, bareCommand);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser(text: string): InitResult {\n return parseInit(commands.includes('--bare'), path, text);\n },\n };\n}\n", "export enum LogFormat {\n NONE = '',\n STAT = '--stat',\n NUM_STAT = '--numstat',\n NAME_ONLY = '--name-only',\n NAME_STATUS = '--name-status',\n}\n\nconst logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/;\n\nexport function logFormatFromCommand(customArgs: string[]) {\n for (let i = 0; i < customArgs.length; i++) {\n const format = logFormatRegex.exec(customArgs[i]);\n if (format) {\n return `--${format[1]}` as LogFormat;\n }\n }\n\n return LogFormat.NONE;\n}\n\nexport function isLogFormat(customArg: string | unknown) {\n return logFormatRegex.test(customArg as string);\n}\n", "import { DiffResult, DiffResultBinaryFile, DiffResultTextFile } from '../../../typings';\n\n/***\n * The DiffSummary is returned as a response to getting `git().status()`\n */\nexport class DiffSummary implements DiffResult {\n changed = 0;\n deletions = 0;\n insertions = 0;\n\n files: Array = [];\n}\n", "import { DiffResult } from '../../../typings';\nimport { LogFormat } from '../args/log-format';\nimport { DiffSummary } from '../responses/DiffSummary';\nimport { isDiffNameStatus } from '../tasks/diff-name-status';\nimport { asNumber, LineParser, orVoid, parseStringResponse } from '../utils';\n\nconst statParser = [\n new LineParser(\n /^(.+)\\s+\\|\\s+(\\d+)(\\s+[+\\-]+)?$/,\n (result, [file, changes, alterations = '']) => {\n result.files.push({\n file: file.trim(),\n changes: asNumber(changes),\n insertions: alterations.replace(/[^+]/g, '').length,\n deletions: alterations.replace(/[^-]/g, '').length,\n binary: false,\n });\n }\n ),\n new LineParser(\n /^(.+) \\|\\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,\n (result, [file, before, after]) => {\n result.files.push({\n file: file.trim(),\n before: asNumber(before),\n after: asNumber(after),\n binary: true,\n });\n }\n ),\n new LineParser(\n /(\\d+) files? changed\\s*((?:, \\d+ [^,]+){0,2})/,\n (result, [changed, summary]) => {\n const inserted = /(\\d+) i/.exec(summary);\n const deleted = /(\\d+) d/.exec(summary);\n\n result.changed = asNumber(changed);\n result.insertions = asNumber(inserted?.[1]);\n result.deletions = asNumber(deleted?.[1]);\n }\n ),\n];\n\nconst numStatParser = [\n new LineParser(\n /(\\d+)\\t(\\d+)\\t(.+)$/,\n (result, [changesInsert, changesDelete, file]) => {\n const insertions = asNumber(changesInsert);\n const deletions = asNumber(changesDelete);\n\n result.changed++;\n result.insertions += insertions;\n result.deletions += deletions;\n\n result.files.push({\n file,\n changes: insertions + deletions,\n insertions,\n deletions,\n binary: false,\n });\n }\n ),\n new LineParser(/-\\t-\\t(.+)$/, (result, [file]) => {\n result.changed++;\n\n result.files.push({\n file,\n after: 0,\n before: 0,\n binary: true,\n });\n }),\n];\n\nconst nameOnlyParser = [\n new LineParser(/(.+)$/, (result, [file]) => {\n result.changed++;\n result.files.push({\n file,\n changes: 0,\n insertions: 0,\n deletions: 0,\n binary: false,\n });\n }),\n];\n\nconst nameStatusParser = [\n new LineParser(\n /([ACDMRTUXB])([0-9]{0,3})\\t(.[^\\t]*)(\\t(.[^\\t]*))?$/,\n (result, [status, _similarity, from, _to, to]) => {\n result.changed++;\n result.files.push({\n file: to ?? from,\n changes: 0,\n status: orVoid(isDiffNameStatus(status) && status),\n insertions: 0,\n deletions: 0,\n binary: false,\n });\n }\n ),\n];\n\nconst diffSummaryParsers: Record[]> = {\n [LogFormat.NONE]: statParser,\n [LogFormat.STAT]: statParser,\n [LogFormat.NUM_STAT]: numStatParser,\n [LogFormat.NAME_STATUS]: nameStatusParser,\n [LogFormat.NAME_ONLY]: nameOnlyParser,\n};\n\nexport function getDiffParser(format = LogFormat.NONE) {\n const parser = diffSummaryParsers[format];\n\n return (stdOut: string) => parseStringResponse(new DiffSummary(), parser, stdOut, false);\n}\n", "import { ListLogLine, LogResult } from '../../../typings';\nimport { toLinesWithContent } from '../utils';\nimport { getDiffParser } from './parse-diff-summary';\nimport { LogFormat } from '../args/log-format';\n\nexport const START_BOUNDARY = '\u00F2\u00F2\u00F2\u00F2\u00F2\u00F2 ';\n\nexport const COMMIT_BOUNDARY = ' \u00F2\u00F2';\n\nexport const SPLITTER = ' \u00F2 ';\n\nconst defaultFieldNames = ['hash', 'date', 'message', 'refs', 'author_name', 'author_email'];\n\nfunction lineBuilder(tokens: string[], fields: string[]): any {\n return fields.reduce(\n (line, field, index) => {\n line[field] = tokens[index] || '';\n return line;\n },\n Object.create({ diff: null }) as any\n );\n}\n\nexport function createListLogSummaryParser(\n splitter = SPLITTER,\n fields = defaultFieldNames,\n logFormat = LogFormat.NONE\n) {\n const parseDiffResult = getDiffParser(logFormat);\n\n return function (stdOut: string): LogResult {\n const all: ReadonlyArray = toLinesWithContent(\n stdOut,\n true,\n START_BOUNDARY\n ).map(function (item) {\n const lineDetail = item.trim().split(COMMIT_BOUNDARY);\n const listLogLine: T & ListLogLine = lineBuilder(\n lineDetail[0].trim().split(splitter),\n fields\n );\n\n if (lineDetail.length > 1 && !!lineDetail[1].trim()) {\n listLogLine.diff = parseDiffResult(lineDetail[1]);\n }\n\n return listLogLine;\n });\n\n return {\n all,\n latest: (all.length && all[0]) || null,\n total: all.length,\n };\n };\n}\n", "import { StringTask } from '../types';\nimport { DiffResult } from '../../../typings';\nimport { isLogFormat, LogFormat, logFormatFromCommand } from '../args/log-format';\nimport { getDiffParser } from '../parsers/parse-diff-summary';\nimport { configurationErrorTask, EmptyTask } from './task';\n\nexport function diffSummaryTask(customArgs: string[]): StringTask | EmptyTask {\n let logFormat = logFormatFromCommand(customArgs);\n\n const commands = ['diff'];\n\n if (logFormat === LogFormat.NONE) {\n logFormat = LogFormat.STAT;\n commands.push('--stat=4096');\n }\n\n commands.push(...customArgs);\n\n return (\n validateLogFormatConfig(commands) || {\n commands,\n format: 'utf-8',\n parser: getDiffParser(logFormat),\n }\n );\n}\n\nexport function validateLogFormatConfig(customArgs: unknown[]): EmptyTask | void {\n const flags = customArgs.filter(isLogFormat);\n\n if (flags.length > 1) {\n return configurationErrorTask(\n `Summary flags are mutually exclusive - pick one of ${flags.join(',')}`\n );\n }\n\n if (flags.length && customArgs.includes('-z')) {\n return configurationErrorTask(\n `Summary flag ${flags} parsing is not compatible with null termination option '-z'`\n );\n }\n}\n", "import type { Options, StringTask } from '../types';\nimport type { LogResult, SimpleGit } from '../../../typings';\nimport { logFormatFromCommand } from '../args/log-format';\nimport { pathspec } from '../args/pathspec';\nimport {\n COMMIT_BOUNDARY,\n createListLogSummaryParser,\n SPLITTER,\n START_BOUNDARY,\n} from '../parsers/parse-list-log-summary';\nimport {\n appendTaskOptions,\n filterArray,\n filterPrimitives,\n filterString,\n filterType,\n trailingFunctionArgument,\n trailingOptionsArgument,\n} from '../utils';\nimport { SimpleGitApi } from '../simple-git-api';\nimport { configurationErrorTask } from './task';\nimport { validateLogFormatConfig } from './diff';\n\nenum excludeOptions {\n '--pretty',\n 'max-count',\n 'maxCount',\n 'n',\n 'file',\n 'format',\n 'from',\n 'to',\n 'splitter',\n 'symmetric',\n 'mailMap',\n 'multiLine',\n 'strictDate',\n}\n\nexport interface DefaultLogFields {\n hash: string;\n date: string;\n message: string;\n refs: string;\n body: string;\n author_name: string;\n author_email: string;\n}\n\nexport type LogOptions = {\n file?: string;\n format?: T;\n from?: string;\n mailMap?: boolean;\n maxCount?: number;\n multiLine?: boolean;\n splitter?: string;\n strictDate?: boolean;\n symmetric?: boolean;\n to?: string;\n};\n\ninterface ParsedLogOptions {\n fields: string[];\n splitter: string;\n commands: string[];\n}\n\nfunction prettyFormat(\n format: Record,\n splitter: string\n): [string[], string] {\n const fields: string[] = [];\n const formatStr: string[] = [];\n\n Object.keys(format).forEach((field) => {\n fields.push(field);\n formatStr.push(String(format[field]));\n });\n\n return [fields, formatStr.join(splitter)];\n}\n\nfunction userOptions(input: T): Options {\n return Object.keys(input).reduce((out, key) => {\n if (!(key in excludeOptions)) {\n out[key] = input[key];\n }\n return out;\n }, {} as Options);\n}\n\nexport function parseLogOptions(\n opt: Options | LogOptions = {},\n customArgs: string[] = []\n): ParsedLogOptions {\n const splitter = filterType(opt.splitter, filterString, SPLITTER);\n const format =\n !filterPrimitives(opt.format) && opt.format\n ? opt.format\n : {\n hash: '%H',\n date: opt.strictDate === false ? '%ai' : '%aI',\n message: '%s',\n refs: '%D',\n body: opt.multiLine ? '%B' : '%b',\n author_name: opt.mailMap !== false ? '%aN' : '%an',\n author_email: opt.mailMap !== false ? '%aE' : '%ae',\n };\n\n const [fields, formatStr] = prettyFormat(format, splitter);\n\n const suffix: string[] = [];\n const command: string[] = [\n `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`,\n ...customArgs,\n ];\n\n const maxCount: number | undefined = (opt as any).n || (opt as any)['max-count'] || opt.maxCount;\n if (maxCount) {\n command.push(`--max-count=${maxCount}`);\n }\n\n if (opt.from || opt.to) {\n const rangeOperator = opt.symmetric !== false ? '...' : '..';\n suffix.push(`${opt.from || ''}${rangeOperator}${opt.to || ''}`);\n }\n\n if (filterString(opt.file)) {\n command.push('--follow', pathspec(opt.file));\n }\n\n appendTaskOptions(userOptions(opt as Options), command);\n\n return {\n fields,\n splitter,\n commands: [...command, ...suffix],\n };\n}\n\nexport function logTask(\n splitter: string,\n fields: string[],\n customArgs: string[]\n): StringTask> {\n const parser = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs));\n\n return {\n commands: ['log', ...customArgs],\n format: 'utf-8',\n parser,\n };\n}\n\nexport default function (): Pick {\n return {\n log(this: SimpleGitApi, ...rest: unknown[]) {\n const next = trailingFunctionArgument(arguments);\n const options = parseLogOptions(\n trailingOptionsArgument(arguments),\n filterType(arguments[0], filterArray)\n );\n const task =\n rejectDeprecatedSignatures(...rest) ||\n validateLogFormatConfig(options.commands) ||\n createLogTask(options);\n\n return this._runTask(task, next);\n },\n };\n\n function createLogTask(options: ParsedLogOptions) {\n return logTask(options.splitter, options.fields, options.commands);\n }\n\n function rejectDeprecatedSignatures(from?: unknown, to?: unknown) {\n return (\n filterString(from) &&\n filterString(to) &&\n configurationErrorTask(\n `git.log(string, string) should be replaced with git.log({ from: string, to: string })`\n )\n );\n }\n}\n", "import {\n MergeConflict,\n MergeConflictDeletion,\n MergeDetail,\n MergeResultStatus,\n} from '../../../typings';\n\nexport class MergeSummaryConflict implements MergeConflict {\n constructor(\n public readonly reason: string,\n public readonly file: string | null = null,\n public readonly meta?: MergeConflictDeletion\n ) {}\n\n toString() {\n return `${this.file}:${this.reason}`;\n }\n}\n\nexport class MergeSummaryDetail implements MergeDetail {\n public conflicts: MergeConflict[] = [];\n public merges: string[] = [];\n public result: MergeResultStatus = 'success';\n\n get failed() {\n return this.conflicts.length > 0;\n }\n\n get reason() {\n return this.result;\n }\n\n toString() {\n if (this.conflicts.length) {\n return `CONFLICTS: ${this.conflicts.join(', ')}`;\n }\n\n return 'OK';\n }\n}\n", "import {\n PullDetailFileChanges,\n PullDetailSummary,\n PullFailedResult,\n PullResult,\n} from '../../../typings';\n\nexport class PullSummary implements PullResult {\n public remoteMessages = {\n all: [],\n };\n public created = [];\n public deleted: string[] = [];\n public files: string[] = [];\n public deletions: PullDetailFileChanges = {};\n public insertions: PullDetailFileChanges = {};\n public summary: PullDetailSummary = {\n changes: 0,\n deletions: 0,\n insertions: 0,\n };\n}\n\nexport class PullFailedSummary implements PullFailedResult {\n remote = '';\n hash = {\n local: '',\n remote: '',\n };\n branch = {\n local: '',\n remote: '',\n };\n message = '';\n\n toString() {\n return this.message;\n }\n}\n", "import {\n RemoteMessageResult,\n RemoteMessages,\n RemoteMessagesObjectEnumeration,\n} from '../../../typings';\nimport { asNumber, RemoteLineParser } from '../utils';\n\nfunction objectEnumerationResult(\n remoteMessages: T\n): RemoteMessagesObjectEnumeration {\n return (remoteMessages.objects = remoteMessages.objects || {\n compressing: 0,\n counting: 0,\n enumerating: 0,\n packReused: 0,\n reused: { count: 0, delta: 0 },\n total: { count: 0, delta: 0 },\n });\n}\n\nfunction asObjectCount(source: string) {\n const count = /^\\s*(\\d+)/.exec(source);\n const delta = /delta (\\d+)/i.exec(source);\n\n return {\n count: asNumber((count && count[1]) || '0'),\n delta: asNumber((delta && delta[1]) || '0'),\n };\n}\n\nexport const remoteMessagesObjectParsers: RemoteLineParser>[] =\n [\n new RemoteLineParser(\n /^remote:\\s*(enumerating|counting|compressing) objects: (\\d+),/i,\n (result, [action, count]) => {\n const key = action.toLowerCase();\n const enumeration = objectEnumerationResult(result.remoteMessages);\n\n Object.assign(enumeration, { [key]: asNumber(count) });\n }\n ),\n new RemoteLineParser(\n /^remote:\\s*(enumerating|counting|compressing) objects: \\d+% \\(\\d+\\/(\\d+)\\),/i,\n (result, [action, count]) => {\n const key = action.toLowerCase();\n const enumeration = objectEnumerationResult(result.remoteMessages);\n\n Object.assign(enumeration, { [key]: asNumber(count) });\n }\n ),\n new RemoteLineParser(\n /total ([^,]+), reused ([^,]+), pack-reused (\\d+)/i,\n (result, [total, reused, packReused]) => {\n const objects = objectEnumerationResult(result.remoteMessages);\n objects.total = asObjectCount(total);\n objects.reused = asObjectCount(reused);\n objects.packReused = asNumber(packReused);\n }\n ),\n ];\n", "import { PushResultRemoteMessages, RemoteMessageResult, RemoteMessages } from '../../../typings';\nimport { asNumber, parseStringResponse, RemoteLineParser } from '../utils';\nimport { remoteMessagesObjectParsers } from './parse-remote-objects';\n\nconst parsers: RemoteLineParser>[] =\n [\n new RemoteLineParser(/^remote:\\s*(.+)$/, (result, [text]) => {\n result.remoteMessages.all.push(text.trim());\n return false;\n }),\n ...remoteMessagesObjectParsers,\n new RemoteLineParser(\n [/create a (?:pull|merge) request/i, /\\s(https?:\\/\\/\\S+)$/],\n (result, [pullRequestUrl]) => {\n (result.remoteMessages as PushResultRemoteMessages).pullRequestUrl = pullRequestUrl;\n }\n ),\n new RemoteLineParser(\n [/found (\\d+) vulnerabilities.+\\(([^)]+)\\)/i, /\\s(https?:\\/\\/\\S+)$/],\n (result, [count, summary, url]) => {\n (result.remoteMessages as PushResultRemoteMessages).vulnerabilities = {\n count: asNumber(count),\n summary,\n url,\n };\n }\n ),\n ];\n\nexport function parseRemoteMessages(\n _stdOut: string,\n stdErr: string\n): RemoteMessageResult {\n return parseStringResponse({ remoteMessages: new RemoteMessageSummary() as T }, parsers, stdErr);\n}\n\nexport class RemoteMessageSummary implements RemoteMessages {\n public readonly all: string[] = [];\n}\n", "import { PullDetail, PullFailedResult, PullResult, RemoteMessages } from '../../../typings';\nimport { PullFailedSummary, PullSummary } from '../responses/PullSummary';\nimport { TaskParser } from '../types';\nimport { append, LineParser, parseStringResponse } from '../utils';\nimport { parseRemoteMessages } from './parse-remote-messages';\n\nconst FILE_UPDATE_REGEX = /^\\s*(.+?)\\s+\\|\\s+\\d+\\s*(\\+*)(-*)/;\nconst SUMMARY_REGEX = /(\\d+)\\D+((\\d+)\\D+\\(\\+\\))?(\\D+(\\d+)\\D+\\(-\\))?/;\nconst ACTION_REGEX = /^(create|delete) mode \\d+ (.+)/;\n\nconst parsers: LineParser[] = [\n new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => {\n result.files.push(file);\n\n if (insertions) {\n result.insertions[file] = insertions.length;\n }\n\n if (deletions) {\n result.deletions[file] = deletions.length;\n }\n }),\n new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => {\n if (insertions !== undefined || deletions !== undefined) {\n result.summary.changes = +changes || 0;\n result.summary.insertions = +insertions || 0;\n result.summary.deletions = +deletions || 0;\n return true;\n }\n return false;\n }),\n new LineParser(ACTION_REGEX, (result, [action, file]) => {\n append(result.files, file);\n append(action === 'create' ? result.created : result.deleted, file);\n }),\n];\n\nconst errorParsers: LineParser[] = [\n new LineParser(/^from\\s(.+)$/i, (result, [remote]) => void (result.remote = remote)),\n new LineParser(/^fatal:\\s(.+)$/, (result, [message]) => void (result.message = message)),\n new LineParser(\n /([a-z0-9]+)\\.\\.([a-z0-9]+)\\s+(\\S+)\\s+->\\s+(\\S+)$/,\n (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => {\n result.branch.local = branchLocal;\n result.hash.local = hashLocal;\n result.branch.remote = branchRemote;\n result.hash.remote = hashRemote;\n }\n ),\n];\n\nexport const parsePullDetail: TaskParser = (stdOut, stdErr) => {\n return parseStringResponse(new PullSummary(), parsers, [stdOut, stdErr]);\n};\n\nexport const parsePullResult: TaskParser = (stdOut, stdErr) => {\n return Object.assign(\n new PullSummary(),\n parsePullDetail(stdOut, stdErr),\n parseRemoteMessages(stdOut, stdErr)\n );\n};\n\nexport function parsePullErrorResult(stdOut: string, stdErr: string) {\n const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]);\n\n return pullError.message && pullError;\n}\n", "import { MergeDetail, MergeResult } from '../../../typings';\nimport { MergeSummaryConflict, MergeSummaryDetail } from '../responses/MergeSummary';\nimport { TaskParser } from '../types';\nimport { LineParser, parseStringResponse } from '../utils';\nimport { parsePullResult } from './parse-pull';\n\nconst parsers: LineParser[] = [\n new LineParser(/^Auto-merging\\s+(.+)$/, (summary, [autoMerge]) => {\n summary.merges.push(autoMerge);\n }),\n new LineParser(/^CONFLICT\\s+\\((.+)\\): Merge conflict in (.+)$/, (summary, [reason, file]) => {\n summary.conflicts.push(new MergeSummaryConflict(reason, file));\n }),\n new LineParser(\n /^CONFLICT\\s+\\((.+\\/delete)\\): (.+) deleted in (.+) and/,\n (summary, [reason, file, deleteRef]) => {\n summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef }));\n }\n ),\n new LineParser(/^CONFLICT\\s+\\((.+)\\):/, (summary, [reason]) => {\n summary.conflicts.push(new MergeSummaryConflict(reason, null));\n }),\n new LineParser(/^Automatic merge failed;\\s+(.+)$/, (summary, [result]) => {\n summary.result = result;\n }),\n];\n\n/**\n * Parse the complete response from `git.merge`\n */\nexport const parseMergeResult: TaskParser = (stdOut, stdErr) => {\n return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr));\n};\n\n/**\n * Parse the merge specific detail (ie: not the content also available in the pull detail) from `git.mnerge`\n * @param stdOut\n */\nexport const parseMergeDetail: TaskParser = (stdOut) => {\n return parseStringResponse(new MergeSummaryDetail(), parsers, stdOut);\n};\n", "import { MergeResult } from '../../../typings';\nimport { GitResponseError } from '../errors/git-response-error';\nimport { parseMergeResult } from '../parsers/parse-merge';\nimport { StringTask } from '../types';\nimport { configurationErrorTask, EmptyTask } from './task';\n\nexport function mergeTask(customArgs: string[]): EmptyTask | StringTask {\n if (!customArgs.length) {\n return configurationErrorTask('Git.merge requires at least one option');\n }\n\n return {\n commands: ['merge', ...customArgs],\n format: 'utf-8',\n parser(stdOut, stdErr): MergeResult {\n const merge = parseMergeResult(stdOut, stdErr);\n if (merge.failed) {\n throw new GitResponseError(merge);\n }\n\n return merge;\n },\n };\n}\n", "import {\n PushDetail,\n PushResult,\n PushResultPushedItem,\n PushResultRemoteMessages,\n} from '../../../typings';\nimport { TaskParser } from '../types';\nimport { LineParser, parseStringResponse } from '../utils';\nimport { parseRemoteMessages } from './parse-remote-messages';\n\nfunction pushResultPushedItem(local: string, remote: string, status: string): PushResultPushedItem {\n const deleted = status.includes('deleted');\n const tag = status.includes('tag') || /^refs\\/tags/.test(local);\n const alreadyUpdated = !status.includes('new');\n\n return {\n deleted,\n tag,\n branch: !tag,\n new: !alreadyUpdated,\n alreadyUpdated,\n local,\n remote,\n };\n}\n\nconst parsers: LineParser[] = [\n new LineParser(/^Pushing to (.+)$/, (result, [repo]) => {\n result.repo = repo;\n }),\n new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => {\n result.ref = {\n ...(result.ref || {}),\n local,\n };\n }),\n new LineParser(/^[=*-]\\s+([^:]+):(\\S+)\\s+\\[(.+)]$/, (result, [local, remote, type]) => {\n result.pushed.push(pushResultPushedItem(local, remote, type));\n }),\n new LineParser(\n /^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,\n (result, [local, remote, remoteName]) => {\n result.branch = {\n ...(result.branch || {}),\n local,\n remote,\n remoteName,\n };\n }\n ),\n new LineParser(\n /^([^:]+):(\\S+)\\s+([a-z0-9]+)\\.\\.([a-z0-9]+)$/,\n (result, [local, remote, from, to]) => {\n result.update = {\n head: {\n local,\n remote,\n },\n hash: {\n from,\n to,\n },\n };\n }\n ),\n];\n\nexport const parsePushResult: TaskParser = (stdOut, stdErr) => {\n const pushDetail = parsePushDetail(stdOut, stdErr);\n const responseDetail = parseRemoteMessages(stdOut, stdErr);\n\n return {\n ...pushDetail,\n ...responseDetail,\n };\n};\n\nexport const parsePushDetail: TaskParser = (stdOut, stdErr) => {\n return parseStringResponse({ pushed: [] }, parsers, [stdOut, stdErr]);\n};\n", "import { PushResult } from '../../../typings';\nimport { parsePushResult as parser } from '../parsers/parse-push';\nimport { StringTask } from '../types';\nimport { append, remove } from '../utils';\n\ntype PushRef = { remote?: string; branch?: string };\n\nexport function pushTagsTask(ref: PushRef = {}, customArgs: string[]): StringTask {\n append(customArgs, '--tags');\n return pushTask(ref, customArgs);\n}\n\nexport function pushTask(ref: PushRef = {}, customArgs: string[]): StringTask {\n const commands = ['push', ...customArgs];\n if (ref.branch) {\n commands.splice(1, 0, ref.branch);\n }\n if (ref.remote) {\n commands.splice(1, 0, ref.remote);\n }\n\n remove(commands, '-v');\n append(commands, '--verbose');\n append(commands, '--porcelain');\n\n return {\n commands,\n format: 'utf-8',\n parser,\n };\n}\n", "import { SimpleGit } from '../../../typings';\nimport { SimpleGitApi } from '../simple-git-api';\nimport { getTrailingOptions, trailingFunctionArgument } from '../utils';\nimport { straightThroughBufferTask, straightThroughStringTask } from './task';\n\nexport default function (): Pick {\n return {\n showBuffer(this: SimpleGitApi) {\n const commands = ['show', ...getTrailingOptions(arguments, 1)];\n if (!commands.includes('--binary')) {\n commands.splice(1, 0, '--binary');\n }\n\n return this._runTask(\n straightThroughBufferTask(commands),\n trailingFunctionArgument(arguments)\n );\n },\n\n show(this: SimpleGitApi) {\n const commands = ['show', ...getTrailingOptions(arguments, 1)];\n return this._runTask(\n straightThroughStringTask(commands),\n trailingFunctionArgument(arguments)\n );\n },\n };\n}\n", "import { FileStatusResult } from '../../../typings';\n\nexport const fromPathRegex = /^(.+) -> (.+)$/;\n\nexport class FileStatusSummary implements FileStatusResult {\n public readonly from: string | undefined;\n\n constructor(\n public path: string,\n public index: string,\n public working_dir: string\n ) {\n if ('R' === index + working_dir) {\n const detail = fromPathRegex.exec(path) || [null, path, path];\n this.from = detail[1] || '';\n this.path = detail[2] || '';\n }\n }\n}\n", "import { StatusResult } from '../../../typings';\nimport { append, NULL } from '../utils';\nimport { FileStatusSummary } from './FileStatusSummary';\n\ntype StatusLineParser = (result: StatusResult, file: string) => void;\n\nexport class StatusSummary implements StatusResult {\n public not_added = [];\n public conflicted = [];\n public created = [];\n public deleted = [];\n public ignored = undefined;\n public modified = [];\n public renamed = [];\n public files = [];\n public staged = [];\n public ahead = 0;\n public behind = 0;\n public current = null;\n public tracking = null;\n public detached = false;\n\n public isClean = () => {\n return !this.files.length;\n };\n}\n\nenum PorcelainFileStatus {\n ADDED = 'A',\n DELETED = 'D',\n MODIFIED = 'M',\n RENAMED = 'R',\n COPIED = 'C',\n UNMERGED = 'U',\n UNTRACKED = '?',\n IGNORED = '!',\n NONE = ' ',\n}\n\nfunction renamedFile(line: string) {\n const [to, from] = line.split(NULL);\n\n return {\n from: from || to,\n to,\n };\n}\n\nfunction parser(\n indexX: PorcelainFileStatus,\n indexY: PorcelainFileStatus,\n handler: StatusLineParser\n): [string, StatusLineParser] {\n return [`${indexX}${indexY}`, handler];\n}\n\nfunction conflicts(indexX: PorcelainFileStatus, ...indexY: PorcelainFileStatus[]) {\n return indexY.map((y) => parser(indexX, y, (result, file) => append(result.conflicted, file)));\n}\n\nconst parsers: Map = new Map([\n parser(PorcelainFileStatus.NONE, PorcelainFileStatus.ADDED, (result, file) =>\n append(result.created, file)\n ),\n parser(PorcelainFileStatus.NONE, PorcelainFileStatus.DELETED, (result, file) =>\n append(result.deleted, file)\n ),\n parser(PorcelainFileStatus.NONE, PorcelainFileStatus.MODIFIED, (result, file) =>\n append(result.modified, file)\n ),\n\n parser(\n PorcelainFileStatus.ADDED,\n PorcelainFileStatus.NONE,\n (result, file) => append(result.created, file) && append(result.staged, file)\n ),\n parser(\n PorcelainFileStatus.ADDED,\n PorcelainFileStatus.MODIFIED,\n (result, file) =>\n append(result.created, file) &&\n append(result.staged, file) &&\n append(result.modified, file)\n ),\n\n parser(\n PorcelainFileStatus.DELETED,\n PorcelainFileStatus.NONE,\n (result, file) => append(result.deleted, file) && append(result.staged, file)\n ),\n\n parser(\n PorcelainFileStatus.MODIFIED,\n PorcelainFileStatus.NONE,\n (result, file) => append(result.modified, file) && append(result.staged, file)\n ),\n parser(\n PorcelainFileStatus.MODIFIED,\n PorcelainFileStatus.MODIFIED,\n (result, file) => append(result.modified, file) && append(result.staged, file)\n ),\n\n parser(PorcelainFileStatus.RENAMED, PorcelainFileStatus.NONE, (result, file) => {\n append(result.renamed, renamedFile(file));\n }),\n parser(PorcelainFileStatus.RENAMED, PorcelainFileStatus.MODIFIED, (result, file) => {\n const renamed = renamedFile(file);\n append(result.renamed, renamed);\n append(result.modified, renamed.to);\n }),\n parser(PorcelainFileStatus.IGNORED, PorcelainFileStatus.IGNORED, (_result, _file) => {\n append((_result.ignored = _result.ignored || []), _file);\n }),\n\n parser(PorcelainFileStatus.UNTRACKED, PorcelainFileStatus.UNTRACKED, (result, file) =>\n append(result.not_added, file)\n ),\n\n ...conflicts(PorcelainFileStatus.ADDED, PorcelainFileStatus.ADDED, PorcelainFileStatus.UNMERGED),\n ...conflicts(\n PorcelainFileStatus.DELETED,\n PorcelainFileStatus.DELETED,\n PorcelainFileStatus.UNMERGED\n ),\n ...conflicts(\n PorcelainFileStatus.UNMERGED,\n PorcelainFileStatus.ADDED,\n PorcelainFileStatus.DELETED,\n PorcelainFileStatus.UNMERGED\n ),\n\n [\n '##',\n (result, line) => {\n const aheadReg = /ahead (\\d+)/;\n const behindReg = /behind (\\d+)/;\n const currentReg = /^(.+?(?=(?:\\.{3}|\\s|$)))/;\n const trackingReg = /\\.{3}(\\S*)/;\n const onEmptyBranchReg = /\\son\\s([\\S]+)$/;\n let regexResult;\n\n regexResult = aheadReg.exec(line);\n result.ahead = (regexResult && +regexResult[1]) || 0;\n\n regexResult = behindReg.exec(line);\n result.behind = (regexResult && +regexResult[1]) || 0;\n\n regexResult = currentReg.exec(line);\n result.current = regexResult && regexResult[1];\n\n regexResult = trackingReg.exec(line);\n result.tracking = regexResult && regexResult[1];\n\n regexResult = onEmptyBranchReg.exec(line);\n result.current = (regexResult && regexResult[1]) || result.current;\n\n result.detached = /\\(no branch\\)/.test(line);\n },\n ],\n]);\n\nexport const parseStatusSummary = function (text: string): StatusResult {\n const lines = text.split(NULL);\n const status = new StatusSummary();\n\n for (let i = 0, l = lines.length; i < l; ) {\n let line = lines[i++].trim();\n\n if (!line) {\n continue;\n }\n\n if (line.charAt(0) === PorcelainFileStatus.RENAMED) {\n line += NULL + (lines[i++] || '');\n }\n\n splitLine(status, line);\n }\n\n return status;\n};\n\nfunction splitLine(result: StatusResult, lineStr: string) {\n const trimmed = lineStr.trim();\n switch (' ') {\n case trimmed.charAt(2):\n return data(trimmed.charAt(0), trimmed.charAt(1), trimmed.substr(3));\n case trimmed.charAt(1):\n return data(PorcelainFileStatus.NONE, trimmed.charAt(0), trimmed.substr(2));\n default:\n return;\n }\n\n function data(index: string, workingDir: string, path: string) {\n const raw = `${index}${workingDir}`;\n const handler = parsers.get(raw);\n\n if (handler) {\n handler(result, path);\n }\n\n if (raw !== '##' && raw !== '!!') {\n result.files.push(new FileStatusSummary(path.replace(/\\0.+$/, ''), index, workingDir));\n }\n }\n}\n", "import { StatusResult } from '../../../typings';\nimport { parseStatusSummary } from '../responses/StatusSummary';\nimport { StringTask } from '../types';\n\nconst ignoredOptions = ['--null', '-z'];\n\nexport function statusTask(customArgs: string[]): StringTask {\n const commands = [\n 'status',\n '--porcelain',\n '-b',\n '-u',\n '--null',\n ...customArgs.filter((arg) => !ignoredOptions.includes(arg)),\n ];\n\n return {\n format: 'utf-8',\n commands,\n parser(text: string) {\n return parseStatusSummary(text);\n },\n };\n}\n", "import type { SimpleGitApi } from '../simple-git-api';\nimport type { SimpleGit } from '../../../typings';\nimport { asNumber, ExitCodes, LineParser, parseStringResponse } from '../utils';\n\nexport interface VersionResult {\n major: number;\n minor: number;\n patch: number | string;\n agent: string;\n installed: boolean;\n}\n\nconst NOT_INSTALLED = 'installed=false';\n\nfunction versionResponse(\n major = 0,\n minor = 0,\n patch: string | number = 0,\n agent = '',\n installed = true\n): VersionResult {\n return Object.defineProperty(\n {\n major,\n minor,\n patch,\n agent,\n installed,\n },\n 'toString',\n {\n value() {\n return `${this.major}.${this.minor}.${this.patch}`;\n },\n configurable: false,\n enumerable: false,\n }\n );\n}\n\nfunction notInstalledResponse() {\n return versionResponse(0, 0, 0, '', false);\n}\n\nexport default function (): Pick {\n return {\n version(this: SimpleGitApi) {\n return this._runTask({\n commands: ['--version'],\n format: 'utf-8',\n parser: versionParser,\n onError(result, error, done, fail) {\n if (result.exitCode === ExitCodes.NOT_FOUND) {\n return done(Buffer.from(NOT_INSTALLED));\n }\n\n fail(error);\n },\n });\n },\n };\n}\n\nconst parsers: LineParser[] = [\n new LineParser(\n /version (\\d+)\\.(\\d+)\\.(\\d+)(?:\\s*\\((.+)\\))?/,\n (result, [major, minor, patch, agent = '']) => {\n Object.assign(\n result,\n versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent)\n );\n }\n ),\n new LineParser(\n /version (\\d+)\\.(\\d+)\\.(\\D+)(.+)?$/,\n (result, [major, minor, patch, agent = '']) => {\n Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent));\n }\n ),\n];\n\nfunction versionParser(stdOut: string) {\n if (stdOut === NOT_INSTALLED) {\n return notInstalledResponse();\n }\n\n return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers, stdOut);\n}\n", "import { SimpleGitBase } from '../../typings';\nimport { taskCallback } from './task-callback';\nimport { changeWorkingDirectoryTask } from './tasks/change-working-directory';\nimport checkout from './tasks/checkout';\nimport commit from './tasks/commit';\nimport config from './tasks/config';\nimport firstCommit from './tasks/first-commit';\nimport grep from './tasks/grep';\nimport { hashObjectTask } from './tasks/hash-object';\nimport { initTask } from './tasks/init';\nimport log from './tasks/log';\nimport { mergeTask } from './tasks/merge';\nimport { pushTask } from './tasks/push';\nimport show from './tasks/show';\nimport { statusTask } from './tasks/status';\nimport { configurationErrorTask, straightThroughStringTask } from './tasks/task';\nimport version from './tasks/version';\nimport { outputHandler, SimpleGitExecutor, SimpleGitTask, SimpleGitTaskCallback } from './types';\nimport {\n asArray,\n filterString,\n filterType,\n getTrailingOptions,\n trailingFunctionArgument,\n} from './utils';\n\nexport class SimpleGitApi implements SimpleGitBase {\n constructor(private _executor: SimpleGitExecutor) {}\n\n protected _runTask(task: SimpleGitTask, then?: SimpleGitTaskCallback) {\n const chain = this._executor.chain();\n const promise = chain.push(task);\n\n if (then) {\n taskCallback(task, promise, then);\n }\n\n return Object.create(this, {\n then: { value: promise.then.bind(promise) },\n catch: { value: promise.catch.bind(promise) },\n _executor: { value: chain },\n });\n }\n\n add(files: string | string[]) {\n return this._runTask(\n straightThroughStringTask(['add', ...asArray(files)]),\n trailingFunctionArgument(arguments)\n );\n }\n\n cwd(directory: string | { path: string; root?: boolean }) {\n const next = trailingFunctionArgument(arguments);\n\n if (typeof directory === 'string') {\n return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next);\n }\n\n if (typeof directory?.path === 'string') {\n return this._runTask(\n changeWorkingDirectoryTask(\n directory.path,\n (directory.root && this._executor) || undefined\n ),\n next\n );\n }\n\n return this._runTask(\n configurationErrorTask('Git.cwd: workingDirectory must be supplied as a string'),\n next\n );\n }\n\n hashObject(path: string, write: boolean | unknown) {\n return this._runTask(\n hashObjectTask(path, write === true),\n trailingFunctionArgument(arguments)\n );\n }\n\n init(bare?: boolean | unknown) {\n return this._runTask(\n initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n }\n\n merge() {\n return this._runTask(\n mergeTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n }\n\n mergeFromTo(remote: string, branch: string) {\n if (!(filterString(remote) && filterString(branch))) {\n return this._runTask(\n configurationErrorTask(\n `Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`\n )\n );\n }\n\n return this._runTask(\n mergeTask([remote, branch, ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments, false)\n );\n }\n\n outputHandler(handler: outputHandler) {\n this._executor.outputHandler = handler;\n return this;\n }\n\n push() {\n const task = pushTask(\n {\n remote: filterType(arguments[0], filterString),\n branch: filterType(arguments[1], filterString),\n },\n getTrailingOptions(arguments)\n );\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n }\n\n stash() {\n return this._runTask(\n straightThroughStringTask(['stash', ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments)\n );\n }\n\n status() {\n return this._runTask(\n statusTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n }\n}\n\nObject.assign(\n SimpleGitApi.prototype,\n checkout(),\n commit(),\n config(),\n firstCommit(),\n grep(),\n log(),\n show(),\n version()\n);\n", "import { append, remove } from '../utils';\nimport { createDeferred, DeferredPromise } from '@kwsites/promise-deferred';\nimport { createLogger } from '../git-logger';\n\ntype ScheduleCompleteCallback = () => void;\ntype ScheduledTask = Pick, 'promise' | 'done'> & {\n id: number;\n};\n\nconst createScheduledTask: () => ScheduledTask = (() => {\n let id = 0;\n return () => {\n id++;\n const { promise, done } = createDeferred();\n\n return {\n promise,\n done,\n id,\n };\n };\n})();\n\nexport class Scheduler {\n private logger = createLogger('', 'scheduler');\n private pending: ScheduledTask[] = [];\n private running: ScheduledTask[] = [];\n\n constructor(private concurrency = 2) {\n this.logger(`Constructed, concurrency=%s`, concurrency);\n }\n\n private schedule() {\n if (!this.pending.length || this.running.length >= this.concurrency) {\n this.logger(\n `Schedule attempt ignored, pending=%s running=%s concurrency=%s`,\n this.pending.length,\n this.running.length,\n this.concurrency\n );\n return;\n }\n\n const task = append(this.running, this.pending.shift()!);\n this.logger(`Attempting id=%s`, task.id);\n task.done(() => {\n this.logger(`Completing id=`, task.id);\n remove(this.running, task);\n this.schedule();\n });\n }\n\n next(): Promise {\n const { promise, id } = append(this.pending, createScheduledTask());\n this.logger(`Scheduling id=%s`, id);\n\n this.schedule();\n\n return promise;\n }\n}\n", "import { straightThroughStringTask } from './task';\nimport { OptionFlags, Options, StringTask } from '../types';\n\nexport type ApplyOptions = Options &\n OptionFlags<\n | '--stat'\n | '--numstat'\n | '--summary'\n | '--check'\n | '--index'\n | '--intent-to-add'\n | '--3way'\n | '--apply'\n | '--no-add'\n | '-R'\n | '--reverse'\n | '--allow-binary-replacement'\n | '--binary'\n | '--reject'\n | '-z'\n | '--inaccurate-eof'\n | '--recount'\n | '--cached'\n | '--ignore-space-change'\n | '--ignore-whitespace'\n | '--verbose'\n | '--unsafe-paths'\n > &\n OptionFlags<'--whitespace', 'nowarn' | 'warn' | 'fix' | 'error' | 'error-all'> &\n OptionFlags<'--build-fake-ancestor' | '--exclude' | '--include' | '--directory', string> &\n OptionFlags<'-p' | '-C', number>;\n\nexport function applyPatchTask(patches: string[], customArgs: string[]): StringTask {\n return straightThroughStringTask(['apply', ...customArgs, ...patches]);\n}\n", "import {\n BranchMultiDeleteResult,\n BranchSingleDeleteFailure,\n BranchSingleDeleteResult,\n BranchSingleDeleteSuccess,\n} from '../../../typings';\n\nexport class BranchDeletionBatch implements BranchMultiDeleteResult {\n all: BranchSingleDeleteResult[] = [];\n branches: { [branchName: string]: BranchSingleDeleteResult } = {};\n errors: BranchSingleDeleteResult[] = [];\n\n get success(): boolean {\n return !this.errors.length;\n }\n}\n\nexport function branchDeletionSuccess(branch: string, hash: string): BranchSingleDeleteSuccess {\n return {\n branch,\n hash,\n success: true,\n };\n}\n\nexport function branchDeletionFailure(branch: string): BranchSingleDeleteFailure {\n return {\n branch,\n hash: null,\n success: false,\n };\n}\n\nexport function isSingleBranchDeleteFailure(\n test: BranchSingleDeleteResult\n): test is BranchSingleDeleteSuccess {\n return test.success;\n}\n", "import { BranchMultiDeleteResult } from '../../../typings';\nimport {\n BranchDeletionBatch,\n branchDeletionFailure,\n branchDeletionSuccess,\n} from '../responses/BranchDeleteSummary';\nimport { TaskParser } from '../types';\nimport { ExitCodes, LineParser, parseStringResponse } from '../utils';\n\nconst deleteSuccessRegex = /(\\S+)\\s+\\(\\S+\\s([^)]+)\\)/;\nconst deleteErrorRegex = /^error[^']+'([^']+)'/m;\n\nconst parsers: LineParser[] = [\n new LineParser(deleteSuccessRegex, (result, [branch, hash]) => {\n const deletion = branchDeletionSuccess(branch, hash);\n\n result.all.push(deletion);\n result.branches[branch] = deletion;\n }),\n new LineParser(deleteErrorRegex, (result, [branch]) => {\n const deletion = branchDeletionFailure(branch);\n\n result.errors.push(deletion);\n result.all.push(deletion);\n result.branches[branch] = deletion;\n }),\n];\n\nexport const parseBranchDeletions: TaskParser = (\n stdOut,\n stdErr\n) => {\n return parseStringResponse(new BranchDeletionBatch(), parsers, [stdOut, stdErr]);\n};\n\nexport function hasBranchDeletionError(data: string, processExitCode: ExitCodes): boolean {\n return processExitCode === ExitCodes.ERROR && deleteErrorRegex.test(data);\n}\n", "import type { BranchSummary, BranchSummaryBranch } from '../../../typings';\n\nexport enum BranchStatusIdentifier {\n CURRENT = '*',\n LINKED = '+',\n}\n\nexport class BranchSummaryResult implements BranchSummary {\n public all: string[] = [];\n public branches: { [p: string]: BranchSummaryBranch } = {};\n public current: string = '';\n public detached: boolean = false;\n\n push(\n status: BranchStatusIdentifier | unknown,\n detached: boolean,\n name: string,\n commit: string,\n label: string\n ) {\n if (status === BranchStatusIdentifier.CURRENT) {\n this.detached = detached;\n this.current = name;\n }\n\n this.all.push(name);\n this.branches[name] = {\n current: status === BranchStatusIdentifier.CURRENT,\n linkedWorkTree: status === BranchStatusIdentifier.LINKED,\n name,\n commit,\n label,\n };\n }\n}\n", "import type { BranchSummary } from '../../../typings';\nimport { BranchSummaryResult } from '../responses/BranchSummary';\nimport { LineParser, parseStringResponse } from '../utils';\n\nconst parsers: LineParser[] = [\n new LineParser(\n /^([*+]\\s)?\\((?:HEAD )?detached (?:from|at) (\\S+)\\)\\s+([a-z0-9]+)\\s(.*)$/,\n (result, [current, name, commit, label]) => {\n result.push(branchStatus(current), true, name, commit, label);\n }\n ),\n new LineParser(\n /^([*+]\\s)?(\\S+)\\s+([a-z0-9]+)\\s?(.*)$/s,\n (result, [current, name, commit, label]) => {\n result.push(branchStatus(current), false, name, commit, label);\n }\n ),\n];\n\nfunction branchStatus(input?: string) {\n return input ? input.charAt(0) : '';\n}\n\nexport function parseBranchSummary(stdOut: string): BranchSummary {\n return parseStringResponse(new BranchSummaryResult(), parsers, stdOut);\n}\n", "import { BranchMultiDeleteResult, BranchSingleDeleteResult, BranchSummary } from '../../../typings';\nimport { StringTask } from '../types';\nimport { GitResponseError } from '../errors/git-response-error';\nimport { hasBranchDeletionError, parseBranchDeletions } from '../parsers/parse-branch-delete';\nimport { parseBranchSummary } from '../parsers/parse-branch';\nimport { bufferToString } from '../utils';\n\nexport function containsDeleteBranchCommand(commands: string[]) {\n const deleteCommands = ['-d', '-D', '--delete'];\n return commands.some((command) => deleteCommands.includes(command));\n}\n\nexport function branchTask(\n customArgs: string[]\n): StringTask {\n const isDelete = containsDeleteBranchCommand(customArgs);\n const commands = ['branch', ...customArgs];\n\n if (commands.length === 1) {\n commands.push('-a');\n }\n\n if (!commands.includes('-v')) {\n commands.splice(1, 0, '-v');\n }\n\n return {\n format: 'utf-8',\n commands,\n parser(stdOut, stdErr) {\n if (isDelete) {\n return parseBranchDeletions(stdOut, stdErr).all[0];\n }\n\n return parseBranchSummary(stdOut);\n },\n };\n}\n\nexport function branchLocalTask(): StringTask {\n const parser = parseBranchSummary;\n\n return {\n format: 'utf-8',\n commands: ['branch', '-v'],\n parser,\n };\n}\n\nexport function deleteBranchesTask(\n branches: string[],\n forceDelete = false\n): StringTask {\n return {\n format: 'utf-8',\n commands: ['branch', '-v', forceDelete ? '-D' : '-d', ...branches],\n parser(stdOut, stdErr) {\n return parseBranchDeletions(stdOut, stdErr);\n },\n onError({ exitCode, stdOut }, error, done, fail) {\n if (!hasBranchDeletionError(String(error), exitCode)) {\n return fail(error);\n }\n\n done(stdOut);\n },\n };\n}\n\nexport function deleteBranchTask(\n branch: string,\n forceDelete = false\n): StringTask {\n const task: StringTask = {\n format: 'utf-8',\n commands: ['branch', '-v', forceDelete ? '-D' : '-d', branch],\n parser(stdOut, stdErr) {\n return parseBranchDeletions(stdOut, stdErr).branches[branch]!;\n },\n onError({ exitCode, stdErr, stdOut }, error, _, fail) {\n if (!hasBranchDeletionError(String(error), exitCode)) {\n return fail(error);\n }\n\n throw new GitResponseError(\n task.parser(bufferToString(stdOut), bufferToString(stdErr)),\n String(error)\n );\n },\n };\n\n return task;\n}\n", "/**\n * Parser for the `check-ignore` command - returns each file as a string array\n */\nexport const parseCheckIgnore = (text: string): string[] => {\n return text\n .split(/\\n/g)\n .map((line) => line.trim())\n .filter((file) => !!file);\n};\n", "import { StringTask } from '../types';\nimport { parseCheckIgnore } from '../responses/CheckIgnore';\n\nexport function checkIgnoreTask(paths: string[]): StringTask {\n return {\n commands: ['check-ignore', ...paths],\n format: 'utf-8',\n parser: parseCheckIgnore,\n };\n}\n", "import { configurationErrorTask, EmptyTask, straightThroughStringTask } from './task';\nimport { OptionFlags, Options, StringTask } from '../types';\nimport { append, filterString } from '../utils';\n\nexport type CloneOptions = Options &\n OptionFlags<\n | '--bare'\n | '--dissociate'\n | '--mirror'\n | '--no-checkout'\n | '--no-remote-submodules'\n | '--no-shallow-submodules'\n | '--no-single-branch'\n | '--no-tags'\n | '--remote-submodules'\n | '--single-branch'\n | '--shallow-submodules'\n | '--verbose'\n > &\n OptionFlags<'--depth' | '-j' | '--jobs', number> &\n OptionFlags<\n | '--branch'\n | '--origin'\n | '--recurse-submodules'\n | '--separate-git-dir'\n | '--shallow-exclude'\n | '--shallow-since'\n | '--template',\n string\n >;\n\nfunction disallowedCommand(command: string) {\n return /^--upload-pack(=|$)/.test(command);\n}\n\nexport function cloneTask(\n repo: string | undefined,\n directory: string | undefined,\n customArgs: string[]\n): StringTask | EmptyTask {\n const commands = ['clone', ...customArgs];\n\n filterString(repo) && commands.push(repo);\n filterString(directory) && commands.push(directory);\n\n const banned = commands.find(disallowedCommand);\n if (banned) {\n return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport function cloneMirrorTask(\n repo: string | undefined,\n directory: string | undefined,\n customArgs: string[]\n) {\n append(customArgs, '--mirror');\n\n return cloneTask(repo, directory, customArgs);\n}\n", "import { FetchResult } from '../../../typings';\nimport { LineParser, parseStringResponse } from '../utils';\n\nconst parsers: LineParser[] = [\n new LineParser(/From (.+)$/, (result, [remote]) => {\n result.remote = remote;\n }),\n new LineParser(/\\* \\[new branch]\\s+(\\S+)\\s*-> (.+)$/, (result, [name, tracking]) => {\n result.branches.push({\n name,\n tracking,\n });\n }),\n new LineParser(/\\* \\[new tag]\\s+(\\S+)\\s*-> (.+)$/, (result, [name, tracking]) => {\n result.tags.push({\n name,\n tracking,\n });\n }),\n new LineParser(/- \\[deleted]\\s+\\S+\\s*-> (.+)$/, (result, [tracking]) => {\n result.deleted.push({\n tracking,\n });\n }),\n new LineParser(\n /\\s*([^.]+)\\.\\.(\\S+)\\s+(\\S+)\\s*-> (.+)$/,\n (result, [from, to, name, tracking]) => {\n result.updated.push({\n name,\n tracking,\n to,\n from,\n });\n }\n ),\n];\n\nexport function parseFetchResult(stdOut: string, stdErr: string): FetchResult {\n const result: FetchResult = {\n raw: stdOut,\n remote: null,\n branches: [],\n tags: [],\n updated: [],\n deleted: [],\n };\n return parseStringResponse(result, parsers, [stdOut, stdErr]);\n}\n", "import { FetchResult } from '../../../typings';\nimport { parseFetchResult } from '../parsers/parse-fetch';\nimport { StringTask } from '../types';\n\nimport { configurationErrorTask, EmptyTask } from './task';\n\nfunction disallowedCommand(command: string) {\n return /^--upload-pack(=|$)/.test(command);\n}\n\nexport function fetchTask(\n remote: string,\n branch: string,\n customArgs: string[]\n): StringTask | EmptyTask {\n const commands = ['fetch', ...customArgs];\n if (remote && branch) {\n commands.push(remote, branch);\n }\n\n const banned = commands.find(disallowedCommand);\n if (banned) {\n return configurationErrorTask(`git.fetch: potential exploit argument blocked.`);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser: parseFetchResult,\n };\n}\n", "import { MoveResult } from '../../../typings';\nimport { LineParser, parseStringResponse } from '../utils';\n\nconst parsers: LineParser[] = [\n new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => {\n result.moves.push({ from, to });\n }),\n];\n\nexport function parseMoveResult(stdOut: string): MoveResult {\n return parseStringResponse({ moves: [] }, parsers, stdOut);\n}\n", "import { MoveResult } from '../../../typings';\nimport { parseMoveResult } from '../parsers/parse-move';\nimport { StringTask } from '../types';\nimport { asArray } from '../utils';\n\nexport function moveTask(from: string | string[], to: string): StringTask {\n return {\n commands: ['mv', '-v', ...asArray(from), to],\n format: 'utf-8',\n parser: parseMoveResult,\n };\n}\n", "import { PullResult } from '../../../typings';\nimport { GitResponseError } from '../errors/git-response-error';\nimport { parsePullErrorResult, parsePullResult } from '../parsers/parse-pull';\nimport { Maybe, StringTask } from '../types';\nimport { bufferToString } from '../utils';\n\nexport function pullTask(\n remote: Maybe,\n branch: Maybe,\n customArgs: string[]\n): StringTask {\n const commands: string[] = ['pull', ...customArgs];\n if (remote && branch) {\n commands.splice(1, 0, remote, branch);\n }\n\n return {\n commands,\n format: 'utf-8',\n parser(stdOut, stdErr): PullResult {\n return parsePullResult(stdOut, stdErr);\n },\n onError(result, _error, _done, fail) {\n const pullError = parsePullErrorResult(\n bufferToString(result.stdOut),\n bufferToString(result.stdErr)\n );\n if (pullError) {\n return fail(new GitResponseError(pullError));\n }\n\n fail(_error);\n },\n };\n}\n", "import { forEachLineWithContent } from '../utils';\n\nexport interface RemoteWithoutRefs {\n name: string;\n}\n\nexport interface RemoteWithRefs extends RemoteWithoutRefs {\n refs: {\n fetch: string;\n push: string;\n };\n}\n\nexport function parseGetRemotes(text: string): RemoteWithoutRefs[] {\n const remotes: { [name: string]: RemoteWithoutRefs } = {};\n\n forEach(text, ([name]) => (remotes[name] = { name }));\n\n return Object.values(remotes);\n}\n\nexport function parseGetRemotesVerbose(text: string): RemoteWithRefs[] {\n const remotes: { [name: string]: RemoteWithRefs } = {};\n\n forEach(text, ([name, url, purpose]) => {\n if (!remotes.hasOwnProperty(name)) {\n remotes[name] = {\n name: name,\n refs: { fetch: '', push: '' },\n };\n }\n\n if (purpose && url) {\n remotes[name].refs[purpose.replace(/[^a-z]/g, '') as keyof RemoteWithRefs['refs']] = url;\n }\n });\n\n return Object.values(remotes);\n}\n\nfunction forEach(text: string, handler: (line: string[]) => void) {\n forEachLineWithContent(text, (line) => handler(line.split(/\\s+/)));\n}\n", "import { parseGetRemotes, parseGetRemotesVerbose } from '../responses/GetRemoteSummary';\nimport { StringTask } from '../types';\nimport { straightThroughStringTask } from './task';\n\nexport function addRemoteTask(\n remoteName: string,\n remoteRepo: string,\n customArgs: string[]\n): StringTask {\n return straightThroughStringTask(['remote', 'add', ...customArgs, remoteName, remoteRepo]);\n}\n\nexport function getRemotesTask(verbose: boolean): StringTask {\n const commands = ['remote'];\n if (verbose) {\n commands.push('-v');\n }\n\n return {\n commands,\n format: 'utf-8',\n parser: verbose ? parseGetRemotesVerbose : parseGetRemotes,\n };\n}\n\nexport function listRemotesTask(customArgs: string[]): StringTask {\n const commands = [...customArgs];\n if (commands[0] !== 'ls-remote') {\n commands.unshift('ls-remote');\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport function remoteTask(customArgs: string[]): StringTask {\n const commands = [...customArgs];\n if (commands[0] !== 'remote') {\n commands.unshift('remote');\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport function removeRemoteTask(remoteName: string) {\n return straightThroughStringTask(['remote', 'remove', remoteName]);\n}\n", "import { LogOptions, LogResult } from '../../../typings';\nimport { logFormatFromCommand } from '../args/log-format';\nimport { createListLogSummaryParser } from '../parsers/parse-list-log-summary';\nimport type { StringTask } from '../types';\nimport { validateLogFormatConfig } from './diff';\nimport { parseLogOptions } from './log';\nimport type { EmptyTask } from './task';\n\nexport function stashListTask(\n opt: LogOptions = {},\n customArgs: string[]\n): EmptyTask | StringTask {\n const options = parseLogOptions(opt);\n const commands = ['stash', 'list', ...options.commands, ...customArgs];\n const parser = createListLogSummaryParser(\n options.splitter,\n options.fields,\n logFormatFromCommand(commands)\n );\n\n return (\n validateLogFormatConfig(commands) || {\n commands,\n format: 'utf-8',\n parser,\n }\n );\n}\n", "import { StringTask } from '../types';\nimport { straightThroughStringTask } from './task';\n\nexport function addSubModuleTask(repo: string, path: string): StringTask {\n return subModuleTask(['add', repo, path]);\n}\n\nexport function initSubModuleTask(customArgs: string[]): StringTask {\n return subModuleTask(['init', ...customArgs]);\n}\n\nexport function subModuleTask(customArgs: string[]): StringTask {\n const commands = [...customArgs];\n if (commands[0] !== 'submodule') {\n commands.unshift('submodule');\n }\n\n return straightThroughStringTask(commands);\n}\n\nexport function updateSubModuleTask(customArgs: string[]): StringTask {\n return subModuleTask(['update', ...customArgs]);\n}\n", "import { TagResult } from '../../../typings';\n\nexport class TagList implements TagResult {\n constructor(\n public readonly all: string[],\n public readonly latest: string | undefined\n ) {}\n}\n\nexport const parseTagList = function (data: string, customSort = false) {\n const tags = data.split('\\n').map(trimmed).filter(Boolean);\n\n if (!customSort) {\n tags.sort(function (tagA, tagB) {\n const partsA = tagA.split('.');\n const partsB = tagB.split('.');\n\n if (partsA.length === 1 || partsB.length === 1) {\n return singleSorted(toNumber(partsA[0]), toNumber(partsB[0]));\n }\n\n for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) {\n const diff = sorted(toNumber(partsA[i]), toNumber(partsB[i]));\n\n if (diff) {\n return diff;\n }\n }\n\n return 0;\n });\n }\n\n const latest = customSort ? tags[0] : [...tags].reverse().find((tag) => tag.indexOf('.') >= 0);\n\n return new TagList(tags, latest);\n};\n\nfunction singleSorted(a: number, b: number): number {\n const aIsNum = isNaN(a);\n const bIsNum = isNaN(b);\n\n if (aIsNum !== bIsNum) {\n return aIsNum ? 1 : -1;\n }\n\n return aIsNum ? sorted(a, b) : 0;\n}\n\nfunction sorted(a: number, b: number) {\n return a === b ? 0 : a > b ? 1 : -1;\n}\n\nfunction trimmed(input: string) {\n return input.trim();\n}\n\nfunction toNumber(input: string | undefined) {\n if (typeof input === 'string') {\n return parseInt(input.replace(/^\\D+/g, ''), 10) || 0;\n }\n\n return 0;\n}\n", "import { TagResult } from '../../../typings';\nimport { parseTagList } from '../responses/TagList';\nimport { StringTask } from '../types';\n\n/**\n * Task used by `git.tags`\n */\nexport function tagListTask(customArgs: string[] = []): StringTask {\n const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option));\n\n return {\n format: 'utf-8',\n commands: ['tag', '-l', ...customArgs],\n parser(text: string) {\n return parseTagList(text, hasCustomSort);\n },\n };\n}\n\n/**\n * Task used by `git.addTag`\n */\nexport function addTagTask(name: string): StringTask<{ name: string }> {\n return {\n format: 'utf-8',\n commands: ['tag', name],\n parser() {\n return { name };\n },\n };\n}\n\n/**\n * Task used by `git.addTag`\n */\nexport function addAnnotatedTagTask(\n name: string,\n tagMessage: string\n): StringTask<{ name: string }> {\n return {\n format: 'utf-8',\n commands: ['tag', '-a', '-m', tagMessage, name],\n parser() {\n return { name };\n },\n };\n}\n", "const { GitExecutor } = require('./lib/runners/git-executor');\nconst { SimpleGitApi } = require('./lib/simple-git-api');\n\nconst { Scheduler } = require('./lib/runners/scheduler');\nconst { configurationErrorTask } = require('./lib/tasks/task');\nconst {\n asArray,\n filterArray,\n filterPrimitives,\n filterString,\n filterStringOrStringArray,\n filterType,\n getTrailingOptions,\n trailingFunctionArgument,\n trailingOptionsArgument,\n} = require('./lib/utils');\nconst { applyPatchTask } = require('./lib/tasks/apply-patch');\nconst {\n branchTask,\n branchLocalTask,\n deleteBranchesTask,\n deleteBranchTask,\n} = require('./lib/tasks/branch');\nconst { checkIgnoreTask } = require('./lib/tasks/check-ignore');\nconst { checkIsRepoTask } = require('./lib/tasks/check-is-repo');\nconst { cloneTask, cloneMirrorTask } = require('./lib/tasks/clone');\nconst { cleanWithOptionsTask, isCleanOptionsArray } = require('./lib/tasks/clean');\nconst { diffSummaryTask } = require('./lib/tasks/diff');\nconst { fetchTask } = require('./lib/tasks/fetch');\nconst { moveTask } = require('./lib/tasks/move');\nconst { pullTask } = require('./lib/tasks/pull');\nconst { pushTagsTask } = require('./lib/tasks/push');\nconst {\n addRemoteTask,\n getRemotesTask,\n listRemotesTask,\n remoteTask,\n removeRemoteTask,\n} = require('./lib/tasks/remote');\nconst { getResetMode, resetTask } = require('./lib/tasks/reset');\nconst { stashListTask } = require('./lib/tasks/stash-list');\nconst {\n addSubModuleTask,\n initSubModuleTask,\n subModuleTask,\n updateSubModuleTask,\n} = require('./lib/tasks/sub-module');\nconst { addAnnotatedTagTask, addTagTask, tagListTask } = require('./lib/tasks/tag');\nconst { straightThroughBufferTask, straightThroughStringTask } = require('./lib/tasks/task');\n\nfunction Git(options, plugins) {\n this._plugins = plugins;\n this._executor = new GitExecutor(\n options.baseDir,\n new Scheduler(options.maxConcurrentProcesses),\n plugins\n );\n\n this._trimmed = options.trimmed;\n}\n\n(Git.prototype = Object.create(SimpleGitApi.prototype)).constructor = Git;\n\n/**\n * Sets the path to a custom git binary, should either be `git` when there is an installation of git available on\n * the system path, or a fully qualified path to the executable.\n */\nGit.prototype.customBinary = function (command) {\n this._plugins.reconfigure('binary', command);\n return this;\n};\n\n/**\n * Sets an environment variable for the spawned child process, either supply both a name and value as strings or\n * a single object to entirely replace the current environment variables.\n *\n * @param {string|Object} name\n * @param {string} [value]\n * @returns {Git}\n */\nGit.prototype.env = function (name, value) {\n if (arguments.length === 1 && typeof name === 'object') {\n this._executor.env = name;\n } else {\n (this._executor.env = this._executor.env || {})[name] = value;\n }\n\n return this;\n};\n\n/**\n * List the stash(s) of the local repo\n */\nGit.prototype.stashList = function (options) {\n return this._runTask(\n stashListTask(\n trailingOptionsArgument(arguments) || {},\n (filterArray(options) && options) || []\n ),\n trailingFunctionArgument(arguments)\n );\n};\n\nfunction createCloneTask(api, task, repoPath, localPath) {\n if (typeof repoPath !== 'string') {\n return configurationErrorTask(`git.${api}() requires a string 'repoPath'`);\n }\n\n return task(repoPath, filterType(localPath, filterString), getTrailingOptions(arguments));\n}\n\n/**\n * Clone a git repo\n */\nGit.prototype.clone = function () {\n return this._runTask(\n createCloneTask('clone', cloneTask, ...arguments),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Mirror a git repo\n */\nGit.prototype.mirror = function () {\n return this._runTask(\n createCloneTask('mirror', cloneMirrorTask, ...arguments),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Moves one or more files to a new destination.\n *\n * @see https://git-scm.com/docs/git-mv\n *\n * @param {string|string[]} from\n * @param {string} to\n */\nGit.prototype.mv = function (from, to) {\n return this._runTask(moveTask(from, to), trailingFunctionArgument(arguments));\n};\n\n/**\n * Internally uses pull and tags to get the list of tags then checks out the latest tag.\n *\n * @param {Function} [then]\n */\nGit.prototype.checkoutLatestTag = function (then) {\n var git = this;\n return this.pull(function () {\n git.tags(function (err, tags) {\n git.checkout(tags.latest, then);\n });\n });\n};\n\n/**\n * Pull the updated contents of the current repo\n */\nGit.prototype.pull = function (remote, branch, options, then) {\n return this._runTask(\n pullTask(\n filterType(remote, filterString),\n filterType(branch, filterString),\n getTrailingOptions(arguments)\n ),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Fetch the updated contents of the current repo.\n *\n * @example\n * .fetch('upstream', 'master') // fetches from master on remote named upstream\n * .fetch(function () {}) // runs fetch against default remote and branch and calls function\n *\n * @param {string} [remote]\n * @param {string} [branch]\n */\nGit.prototype.fetch = function (remote, branch) {\n return this._runTask(\n fetchTask(\n filterType(remote, filterString),\n filterType(branch, filterString),\n getTrailingOptions(arguments)\n ),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Disables/enables the use of the console for printing warnings and errors, by default messages are not shown in\n * a production environment.\n *\n * @param {boolean} silence\n * @returns {Git}\n */\nGit.prototype.silent = function (silence) {\n console.warn(\n 'simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3'\n );\n return this;\n};\n\n/**\n * List all tags. When using git 2.7.0 or above, include an options object with `\"--sort\": \"property-name\"` to\n * sort the tags by that property instead of using the default semantic versioning sort.\n *\n * Note, supplying this option when it is not supported by your Git version will cause the operation to fail.\n *\n * @param {Object} [options]\n * @param {Function} [then]\n */\nGit.prototype.tags = function (options, then) {\n return this._runTask(\n tagListTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Rebases the current working copy. Options can be supplied either as an array of string parameters\n * to be sent to the `git rebase` command, or a standard options object.\n */\nGit.prototype.rebase = function () {\n return this._runTask(\n straightThroughStringTask(['rebase', ...getTrailingOptions(arguments)]),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Reset a repo\n */\nGit.prototype.reset = function (mode) {\n return this._runTask(\n resetTask(getResetMode(mode), getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Revert one or more commits in the local working copy\n */\nGit.prototype.revert = function (commit) {\n const next = trailingFunctionArgument(arguments);\n\n if (typeof commit !== 'string') {\n return this._runTask(configurationErrorTask('Commit must be a string'), next);\n }\n\n return this._runTask(\n straightThroughStringTask(['revert', ...getTrailingOptions(arguments, 0, true), commit]),\n next\n );\n};\n\n/**\n * Add a lightweight tag to the head of the current branch\n */\nGit.prototype.addTag = function (name) {\n const task =\n typeof name === 'string'\n ? addTagTask(name)\n : configurationErrorTask('Git.addTag requires a tag name');\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n};\n\n/**\n * Add an annotated tag to the head of the current branch\n */\nGit.prototype.addAnnotatedTag = function (tagName, tagMessage) {\n return this._runTask(\n addAnnotatedTagTask(tagName, tagMessage),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Delete a local branch\n */\nGit.prototype.deleteLocalBranch = function (branchName, forceDelete, then) {\n return this._runTask(\n deleteBranchTask(branchName, typeof forceDelete === 'boolean' ? forceDelete : false),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Delete one or more local branches\n */\nGit.prototype.deleteLocalBranches = function (branchNames, forceDelete, then) {\n return this._runTask(\n deleteBranchesTask(branchNames, typeof forceDelete === 'boolean' ? forceDelete : false),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * List all branches\n *\n * @param {Object | string[]} [options]\n * @param {Function} [then]\n */\nGit.prototype.branch = function (options, then) {\n return this._runTask(\n branchTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Return list of local branches\n *\n * @param {Function} [then]\n */\nGit.prototype.branchLocal = function (then) {\n return this._runTask(branchLocalTask(), trailingFunctionArgument(arguments));\n};\n\n/**\n * Executes any command against the git binary.\n */\nGit.prototype.raw = function (commands) {\n const createRestCommands = !Array.isArray(commands);\n const command = [].slice.call(createRestCommands ? arguments : commands, 0);\n\n for (let i = 0; i < command.length && createRestCommands; i++) {\n if (!filterPrimitives(command[i])) {\n command.splice(i, command.length - i);\n break;\n }\n }\n\n command.push(...getTrailingOptions(arguments, 0, true));\n\n var next = trailingFunctionArgument(arguments);\n\n if (!command.length) {\n return this._runTask(\n configurationErrorTask('Raw: must supply one or more command to execute'),\n next\n );\n }\n\n return this._runTask(straightThroughStringTask(command, this._trimmed), next);\n};\n\nGit.prototype.submoduleAdd = function (repo, path, then) {\n return this._runTask(addSubModuleTask(repo, path), trailingFunctionArgument(arguments));\n};\n\nGit.prototype.submoduleUpdate = function (args, then) {\n return this._runTask(\n updateSubModuleTask(getTrailingOptions(arguments, true)),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.submoduleInit = function (args, then) {\n return this._runTask(\n initSubModuleTask(getTrailingOptions(arguments, true)),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.subModule = function (options, then) {\n return this._runTask(\n subModuleTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.listRemote = function () {\n return this._runTask(\n listRemotesTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Adds a remote to the list of remotes.\n */\nGit.prototype.addRemote = function (remoteName, remoteRepo, then) {\n return this._runTask(\n addRemoteTask(remoteName, remoteRepo, getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Removes an entry by name from the list of remotes.\n */\nGit.prototype.removeRemote = function (remoteName, then) {\n return this._runTask(removeRemoteTask(remoteName), trailingFunctionArgument(arguments));\n};\n\n/**\n * Gets the currently available remotes, setting the optional verbose argument to true includes additional\n * detail on the remotes themselves.\n */\nGit.prototype.getRemotes = function (verbose, then) {\n return this._runTask(getRemotesTask(verbose === true), trailingFunctionArgument(arguments));\n};\n\n/**\n * Call any `git remote` function with arguments passed as an array of strings.\n *\n * @param {string[]} options\n * @param {Function} [then]\n */\nGit.prototype.remote = function (options, then) {\n return this._runTask(\n remoteTask(getTrailingOptions(arguments)),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Call any `git tag` function with arguments passed as an array of strings.\n *\n * @param {string[]} options\n * @param {Function} [then]\n */\nGit.prototype.tag = function (options, then) {\n const command = getTrailingOptions(arguments);\n\n if (command[0] !== 'tag') {\n command.unshift('tag');\n }\n\n return this._runTask(straightThroughStringTask(command), trailingFunctionArgument(arguments));\n};\n\n/**\n * Updates repository server info\n *\n * @param {Function} [then]\n */\nGit.prototype.updateServerInfo = function (then) {\n return this._runTask(\n straightThroughStringTask(['update-server-info']),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Pushes the current tag changes to a remote which can be either a URL or named remote. When not specified uses the\n * default configured remote spec.\n *\n * @param {string} [remote]\n * @param {Function} [then]\n */\nGit.prototype.pushTags = function (remote, then) {\n const task = pushTagsTask(\n { remote: filterType(remote, filterString) },\n getTrailingOptions(arguments)\n );\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n};\n\n/**\n * Removes the named files from source control.\n */\nGit.prototype.rm = function (files) {\n return this._runTask(\n straightThroughStringTask(['rm', '-f', ...asArray(files)]),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Removes the named files from source control but keeps them on disk rather than deleting them entirely. To\n * completely remove the files, use `rm`.\n *\n * @param {string|string[]} files\n */\nGit.prototype.rmKeepLocal = function (files) {\n return this._runTask(\n straightThroughStringTask(['rm', '--cached', ...asArray(files)]),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n * Returns a list of objects in a tree based on commit hash. Passing in an object hash returns the object's content,\n * size, and type.\n *\n * Passing \"-p\" will instruct cat-file to determine the object type, and display its formatted contents.\n *\n * @param {string[]} [options]\n * @param {Function} [then]\n */\nGit.prototype.catFile = function (options, then) {\n return this._catFile('utf-8', arguments);\n};\n\nGit.prototype.binaryCatFile = function () {\n return this._catFile('buffer', arguments);\n};\n\nGit.prototype._catFile = function (format, args) {\n var handler = trailingFunctionArgument(args);\n var command = ['cat-file'];\n var options = args[0];\n\n if (typeof options === 'string') {\n return this._runTask(\n configurationErrorTask('Git.catFile: options must be supplied as an array of strings'),\n handler\n );\n }\n\n if (Array.isArray(options)) {\n command.push.apply(command, options);\n }\n\n const task =\n format === 'buffer' ? straightThroughBufferTask(command) : straightThroughStringTask(command);\n\n return this._runTask(task, handler);\n};\n\nGit.prototype.diff = function (options, then) {\n const task = filterString(options)\n ? configurationErrorTask(\n 'git.diff: supplying options as a single string is no longer supported, switch to an array of strings'\n )\n : straightThroughStringTask(['diff', ...getTrailingOptions(arguments)]);\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n};\n\nGit.prototype.diffSummary = function () {\n return this._runTask(\n diffSummaryTask(getTrailingOptions(arguments, 1)),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.applyPatch = function (patches) {\n const task = !filterStringOrStringArray(patches)\n ? configurationErrorTask(\n `git.applyPatch requires one or more string patches as the first argument`\n )\n : applyPatchTask(asArray(patches), getTrailingOptions([].slice.call(arguments, 1)));\n\n return this._runTask(task, trailingFunctionArgument(arguments));\n};\n\nGit.prototype.revparse = function () {\n const commands = ['rev-parse', ...getTrailingOptions(arguments, true)];\n return this._runTask(\n straightThroughStringTask(commands, true),\n trailingFunctionArgument(arguments)\n );\n};\n\n/**\n */\nGit.prototype.clean = function (mode, options, then) {\n const usingCleanOptionsArray = isCleanOptionsArray(mode);\n const cleanMode =\n (usingCleanOptionsArray && mode.join('')) || filterType(mode, filterString) || '';\n const customArgs = getTrailingOptions([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0));\n\n return this._runTask(\n cleanWithOptionsTask(cleanMode, customArgs),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.exec = function (then) {\n const task = {\n commands: [],\n format: 'utf-8',\n parser() {\n if (typeof then === 'function') {\n then();\n }\n },\n };\n\n return this._runTask(task);\n};\n\n/**\n * Clears the queue of pending commands and returns the wrapper instance for chaining.\n *\n * @returns {Git}\n */\nGit.prototype.clearQueue = function () {\n // TODO:\n // this._executor.clear();\n return this;\n};\n\n/**\n * Check if a pathname or pathnames are excluded by .gitignore\n *\n * @param {string|string[]} pathnames\n * @param {Function} [then]\n */\nGit.prototype.checkIgnore = function (pathnames, then) {\n return this._runTask(\n checkIgnoreTask(asArray(filterType(pathnames, filterStringOrStringArray, []))),\n trailingFunctionArgument(arguments)\n );\n};\n\nGit.prototype.checkIsRepo = function (checkType, then) {\n return this._runTask(\n checkIsRepoTask(filterType(checkType, filterString)),\n trailingFunctionArgument(arguments)\n );\n};\n\nmodule.exports = Git;\n", "import { pathspec } from './args/pathspec';\nimport { GitConstructError } from './errors/git-construct-error';\nimport { GitError } from './errors/git-error';\nimport { GitPluginError } from './errors/git-plugin-error';\nimport { GitResponseError } from './errors/git-response-error';\nimport { TaskConfigurationError } from './errors/task-configuration-error';\nimport { CheckRepoActions } from './tasks/check-is-repo';\nimport { CleanOptions } from './tasks/clean';\nimport { GitConfigScope } from './tasks/config';\nimport { DiffNameStatus } from './tasks/diff-name-status';\nimport { grepQueryBuilder } from './tasks/grep';\nimport { ResetMode } from './tasks/reset';\n\nexport {\n CheckRepoActions,\n CleanOptions,\n DiffNameStatus,\n GitConfigScope,\n GitConstructError,\n GitError,\n GitPluginError,\n GitResponseError,\n ResetMode,\n TaskConfigurationError,\n grepQueryBuilder,\n pathspec,\n};\n", "import { GitError } from './git-error';\nimport { SimpleGitOptions } from '../types';\n\n/**\n * The `GitConstructError` is thrown when an error occurs in the constructor\n * of the `simple-git` instance itself. Most commonly as a result of using\n * a `baseDir` option that points to a folder that either does not exist,\n * or cannot be read by the user the node script is running as.\n *\n * Check the `.message` property for more detail including the properties\n * passed to the constructor.\n */\nexport class GitConstructError extends GitError {\n constructor(\n public readonly config: SimpleGitOptions,\n message: string\n ) {\n super(undefined, message);\n }\n}\n", "import { SimpleGitOptions, SimpleGitTask } from '../types';\nimport { GitError } from './git-error';\n\nexport class GitPluginError extends GitError {\n constructor(\n public task?: SimpleGitTask,\n public readonly plugin?: keyof SimpleGitOptions,\n message?: string\n ) {\n super(task, message);\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n", "import { SimpleGitOptions } from '../types';\nimport { SimpleGitPlugin } from './simple-git-plugin';\nimport { GitPluginError } from '../errors/git-plugin-error';\n\nexport function abortPlugin(signal: SimpleGitOptions['abort']) {\n if (!signal) {\n return;\n }\n\n const onSpawnAfter: SimpleGitPlugin<'spawn.after'> = {\n type: 'spawn.after',\n action(_data, context) {\n function kill() {\n context.kill(new GitPluginError(undefined, 'abort', 'Abort signal received'));\n }\n\n signal.addEventListener('abort', kill);\n\n context.spawned.on('close', () => signal.removeEventListener('abort', kill));\n },\n };\n\n const onSpawnBefore: SimpleGitPlugin<'spawn.before'> = {\n type: 'spawn.before',\n action(_data, context) {\n if (signal.aborted) {\n context.kill(new GitPluginError(undefined, 'abort', 'Abort already signaled'));\n }\n },\n };\n\n return [onSpawnBefore, onSpawnAfter];\n}\n", "import type { SimpleGitPlugin } from './simple-git-plugin';\n\nimport { GitPluginError } from '../errors/git-plugin-error';\nimport type { SimpleGitPluginConfig } from '../types';\n\nfunction isConfigSwitch(arg: string | unknown) {\n return typeof arg === 'string' && arg.trim().toLowerCase() === '-c';\n}\n\nfunction preventProtocolOverride(arg: string, next: string) {\n if (!isConfigSwitch(arg)) {\n return;\n }\n\n if (!/^\\s*protocol(.[a-z]+)?.allow/.test(next)) {\n return;\n }\n\n throw new GitPluginError(\n undefined,\n 'unsafe',\n 'Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol'\n );\n}\n\nfunction preventUploadPack(arg: string, method: string) {\n if (/^\\s*--(upload|receive)-pack/.test(arg)) {\n throw new GitPluginError(\n undefined,\n 'unsafe',\n `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`\n );\n }\n\n if (method === 'clone' && /^\\s*-u\\b/.test(arg)) {\n throw new GitPluginError(\n undefined,\n 'unsafe',\n `Use of clone with option -u is not permitted without enabling allowUnsafePack`\n );\n }\n\n if (method === 'push' && /^\\s*--exec\\b/.test(arg)) {\n throw new GitPluginError(\n undefined,\n 'unsafe',\n `Use of push with option --exec is not permitted without enabling allowUnsafePack`\n );\n }\n}\n\nexport function blockUnsafeOperationsPlugin({\n allowUnsafeProtocolOverride = false,\n allowUnsafePack = false,\n}: SimpleGitPluginConfig['unsafe'] = {}): SimpleGitPlugin<'spawn.args'> {\n return {\n type: 'spawn.args',\n action(args, context) {\n args.forEach((current, index) => {\n const next = index < args.length ? args[index + 1] : '';\n\n allowUnsafeProtocolOverride || preventProtocolOverride(current, next);\n allowUnsafePack || preventUploadPack(current, context.method);\n });\n\n return args;\n },\n };\n}\n", "import { prefixedArray } from '../utils';\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\nexport function commandConfigPrefixingPlugin(\n configuration: string[]\n): SimpleGitPlugin<'spawn.args'> {\n const prefix = prefixedArray(configuration, '-c');\n\n return {\n type: 'spawn.args',\n action(data) {\n return [...prefix, ...data];\n },\n };\n}\n", "import { deferred, DeferredPromise } from '@kwsites/promise-deferred';\nimport { SimpleGitPluginConfig } from '../types';\nimport { delay } from '../utils';\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\nconst never = deferred().promise;\n\nexport function completionDetectionPlugin({\n onClose = true,\n onExit = 50,\n}: SimpleGitPluginConfig['completion'] = {}): SimpleGitPlugin<'spawn.after'> {\n function createEvents() {\n let exitCode = -1;\n const events = {\n close: deferred(),\n closeTimeout: deferred(),\n exit: deferred(),\n exitTimeout: deferred(),\n };\n\n const result = Promise.race([\n onClose === false ? never : events.closeTimeout.promise,\n onExit === false ? never : events.exitTimeout.promise,\n ]);\n\n configureTimeout(onClose, events.close, events.closeTimeout);\n configureTimeout(onExit, events.exit, events.exitTimeout);\n\n return {\n close(code: number) {\n exitCode = code;\n events.close.done();\n },\n exit(code: number) {\n exitCode = code;\n events.exit.done();\n },\n get exitCode() {\n return exitCode;\n },\n result,\n };\n }\n\n function configureTimeout(\n flag: boolean | number,\n event: DeferredPromise,\n timeout: DeferredPromise\n ) {\n if (flag === false) {\n return;\n }\n\n (flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done);\n }\n\n return {\n type: 'spawn.after',\n async action(_data, { spawned, close }) {\n const events = createEvents();\n\n let deferClose = true;\n let quickClose = () => void (deferClose = false);\n\n spawned.stdout?.on('data', quickClose);\n spawned.stderr?.on('data', quickClose);\n spawned.on('error', quickClose);\n\n spawned.on('close', (code: number) => events.close(code));\n spawned.on('exit', (code: number) => events.exit(code));\n\n try {\n await events.result;\n if (deferClose) {\n await delay(50);\n }\n close(events.exitCode);\n } catch (err) {\n close(events.exitCode, err as Error);\n }\n },\n };\n}\n", "import type { SimpleGitOptions } from '../types';\n\nimport { GitPluginError } from '../errors/git-plugin-error';\nimport { asArray } from '../utils';\nimport { PluginStore } from './plugin-store';\n\nconst WRONG_NUMBER_ERR = `Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings`;\nconst WRONG_CHARS_ERR = `Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option`;\n\nfunction isBadArgument(arg: string) {\n return !arg || !/^([a-z]:)?([a-z0-9/.\\\\_-]+)$/i.test(arg);\n}\n\nfunction toBinaryConfig(\n input: string[],\n allowUnsafe: boolean\n): { binary: string; prefix?: string } {\n if (input.length < 1 || input.length > 2) {\n throw new GitPluginError(undefined, 'binary', WRONG_NUMBER_ERR);\n }\n\n const isBad = input.some(isBadArgument);\n if (isBad) {\n if (allowUnsafe) {\n console.warn(WRONG_CHARS_ERR);\n } else {\n throw new GitPluginError(undefined, 'binary', WRONG_CHARS_ERR);\n }\n }\n\n const [binary, prefix] = input;\n return {\n binary,\n prefix,\n };\n}\n\nexport function customBinaryPlugin(\n plugins: PluginStore,\n input: SimpleGitOptions['binary'] = ['git'],\n allowUnsafe = false\n) {\n let config = toBinaryConfig(asArray(input), allowUnsafe);\n\n plugins.on('binary', (input) => {\n config = toBinaryConfig(asArray(input), allowUnsafe);\n });\n\n plugins.append('spawn.binary', () => {\n return config.binary;\n });\n\n plugins.append('spawn.args', (data) => {\n return config.prefix ? [config.prefix, ...data] : data;\n });\n}\n", "import { GitError } from '../errors/git-error';\nimport { GitExecutorResult, SimpleGitPluginConfig } from '../types';\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\ntype TaskResult = Omit;\n\nfunction isTaskError(result: TaskResult) {\n return !!(result.exitCode && result.stdErr.length);\n}\n\nfunction getErrorMessage(result: TaskResult) {\n return Buffer.concat([...result.stdOut, ...result.stdErr]);\n}\n\nexport function errorDetectionHandler(\n overwrite = false,\n isError = isTaskError,\n errorMessage: (result: TaskResult) => Buffer | Error = getErrorMessage\n) {\n return (error: Buffer | Error | undefined, result: TaskResult) => {\n if ((!overwrite && error) || !isError(result)) {\n return error;\n }\n\n return errorMessage(result);\n };\n}\n\nexport function errorDetectionPlugin(\n config: SimpleGitPluginConfig['errors']\n): SimpleGitPlugin<'task.error'> {\n return {\n type: 'task.error',\n action(data, context) {\n const error = config(data.error, {\n stdErr: context.stdErr,\n stdOut: context.stdOut,\n exitCode: context.exitCode,\n });\n\n if (Buffer.isBuffer(error)) {\n return { error: new GitError(undefined, error.toString('utf-8')) };\n }\n\n return {\n error,\n };\n },\n };\n}\n", "import { EventEmitter } from 'node:events';\n\nimport type {\n SimpleGitPlugin,\n SimpleGitPluginType,\n SimpleGitPluginTypes,\n} from './simple-git-plugin';\nimport { append, asArray } from '../utils';\nimport type { SimpleGitPluginConfig } from '../types';\n\nexport class PluginStore {\n private plugins: Set> = new Set();\n private events = new EventEmitter();\n\n on(\n type: K,\n listener: (data: SimpleGitPluginConfig[K]) => void\n ) {\n this.events.on(type, listener);\n }\n\n reconfigure(type: K, data: SimpleGitPluginConfig[K]) {\n this.events.emit(type, data);\n }\n\n public append(type: T, action: SimpleGitPlugin['action']) {\n const plugin = append(this.plugins, { type, action });\n\n return () => this.plugins.delete(plugin);\n }\n\n public add(\n plugin: void | SimpleGitPlugin | SimpleGitPlugin[]\n ) {\n const plugins: SimpleGitPlugin[] = [];\n\n asArray(plugin).forEach((plugin) => plugin && this.plugins.add(append(plugins, plugin)));\n\n return () => {\n plugins.forEach((plugin) => this.plugins.delete(plugin));\n };\n }\n\n public exec(\n type: T,\n data: SimpleGitPluginTypes[T]['data'],\n context: SimpleGitPluginTypes[T]['context']\n ): typeof data {\n let output = data;\n const contextual = Object.freeze(Object.create(context));\n\n for (const plugin of this.plugins) {\n if (plugin.type === type) {\n output = plugin.action(output, contextual);\n }\n }\n\n return output;\n }\n}\n", "import { SimpleGitOptions } from '../types';\nimport { asNumber, including } from '../utils';\n\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\nexport function progressMonitorPlugin(progress: Exclude) {\n const progressCommand = '--progress';\n const progressMethods = ['checkout', 'clone', 'fetch', 'pull', 'push'];\n\n const onProgress: SimpleGitPlugin<'spawn.after'> = {\n type: 'spawn.after',\n action(_data, context) {\n if (!context.commands.includes(progressCommand)) {\n return;\n }\n\n context.spawned.stderr?.on('data', (chunk: Buffer) => {\n const message = /^([\\s\\S]+?):\\s*(\\d+)% \\((\\d+)\\/(\\d+)\\)/.exec(chunk.toString('utf8'));\n if (!message) {\n return;\n }\n\n progress({\n method: context.method,\n stage: progressEventStage(message[1]),\n progress: asNumber(message[2]),\n processed: asNumber(message[3]),\n total: asNumber(message[4]),\n });\n });\n },\n };\n\n const onArgs: SimpleGitPlugin<'spawn.args'> = {\n type: 'spawn.args',\n action(args, context) {\n if (!progressMethods.includes(context.method)) {\n return args;\n }\n\n return including(args, progressCommand);\n },\n };\n\n return [onArgs, onProgress];\n}\n\nfunction progressEventStage(input: string) {\n return String(input.toLowerCase().split(' ', 1)) || 'unknown';\n}\n", "import { SpawnOptions } from 'child_process';\nimport { pick } from '../utils';\nimport { SimpleGitPlugin } from './simple-git-plugin';\n\nexport function spawnOptionsPlugin(\n spawnOptions: Partial\n): SimpleGitPlugin<'spawn.options'> {\n const options = pick(spawnOptions, ['uid', 'gid']);\n\n return {\n type: 'spawn.options',\n action(data) {\n return { ...options, ...data };\n },\n };\n}\n", "import type { SimpleGitPlugin } from './simple-git-plugin';\n\nimport type { SimpleGitOptions } from '../types';\nimport { GitPluginError } from '../errors/git-plugin-error';\n\nexport function timeoutPlugin({\n block,\n stdErr = true,\n stdOut = true,\n}: Exclude): SimpleGitPlugin<'spawn.after'> | void {\n if (block > 0) {\n return {\n type: 'spawn.after',\n action(_data, context) {\n let timeout: NodeJS.Timeout;\n\n function wait() {\n timeout && clearTimeout(timeout);\n timeout = setTimeout(kill, block);\n }\n\n function stop() {\n context.spawned.stdout?.off('data', wait);\n context.spawned.stderr?.off('data', wait);\n context.spawned.off('exit', stop);\n context.spawned.off('close', stop);\n timeout && clearTimeout(timeout);\n }\n\n function kill() {\n stop();\n context.kill(new GitPluginError(undefined, 'timeout', `block timeout reached`));\n }\n\n stdOut && context.spawned.stdout?.on('data', wait);\n stdErr && context.spawned.stderr?.on('data', wait);\n context.spawned.on('exit', stop);\n context.spawned.on('close', stop);\n\n wait();\n },\n };\n }\n}\n", "import { SimpleGitPlugin } from './simple-git-plugin';\nimport { isPathSpec, toPaths } from '../args/pathspec';\n\nexport function suffixPathsPlugin(): SimpleGitPlugin<'spawn.args'> {\n return {\n type: 'spawn.args',\n action(data) {\n const prefix: string[] = [];\n let suffix: undefined | string[];\n function append(args: string[]) {\n (suffix = suffix || []).push(...args);\n }\n\n for (let i = 0; i < data.length; i++) {\n const param = data[i];\n\n if (isPathSpec(param)) {\n append(toPaths(param));\n continue;\n }\n\n if (param === '--') {\n append(\n data.slice(i + 1).flatMap((item) => (isPathSpec(item) && toPaths(item)) || item)\n );\n break;\n }\n\n prefix.push(param);\n }\n\n return !suffix ? prefix : [...prefix, '--', ...suffix.map(String)];\n },\n };\n}\n", "import { SimpleGitFactory } from '../../typings';\n\nimport * as api from './api';\nimport {\n abortPlugin,\n blockUnsafeOperationsPlugin,\n commandConfigPrefixingPlugin,\n completionDetectionPlugin,\n customBinaryPlugin,\n errorDetectionHandler,\n errorDetectionPlugin,\n PluginStore,\n progressMonitorPlugin,\n spawnOptionsPlugin,\n timeoutPlugin,\n} from './plugins';\nimport { suffixPathsPlugin } from './plugins/suffix-paths.plugin';\nimport { createInstanceConfig, folderExists } from './utils';\nimport { SimpleGitOptions } from './types';\n\nconst Git = require('../git');\n\n/**\n * Adds the necessary properties to the supplied object to enable it for use as\n * the default export of a module.\n *\n * Eg: `module.exports = esModuleFactory({ something () {} })`\n */\nexport function esModuleFactory(defaultExport: T) {\n return Object.defineProperties(defaultExport, {\n __esModule: { value: true },\n default: { value: defaultExport },\n }) as T & { __esModule: true; default: T };\n}\n\nexport function gitExportFactory(factory: SimpleGitFactory) {\n return Object.assign(factory.bind(null), api);\n}\n\nexport function gitInstanceFactory(\n baseDir?: string | Partial,\n options?: Partial\n) {\n const plugins = new PluginStore();\n const config = createInstanceConfig(\n (baseDir && (typeof baseDir === 'string' ? { baseDir } : baseDir)) || {},\n options\n );\n\n if (!folderExists(config.baseDir)) {\n throw new api.GitConstructError(\n config,\n `Cannot use simple-git on a directory that does not exist`\n );\n }\n\n if (Array.isArray(config.config)) {\n plugins.add(commandConfigPrefixingPlugin(config.config));\n }\n\n plugins.add(blockUnsafeOperationsPlugin(config.unsafe));\n plugins.add(suffixPathsPlugin());\n plugins.add(completionDetectionPlugin(config.completion));\n config.abort && plugins.add(abortPlugin(config.abort));\n config.progress && plugins.add(progressMonitorPlugin(config.progress));\n config.timeout && plugins.add(timeoutPlugin(config.timeout));\n config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions));\n\n plugins.add(errorDetectionPlugin(errorDetectionHandler(true)));\n config.errors && plugins.add(errorDetectionPlugin(config.errors));\n\n customBinaryPlugin(plugins, config.binary, config.unsafe?.allowUnsafeCustomBinary);\n\n return new Git(config, plugins);\n}\n", "import { SimpleGit, SimpleGitOptions } from '../../../typings';\n\nimport { GitResponseError } from '../errors/git-response-error';\nimport { gitInstanceFactory } from '../git-factory';\nimport { SimpleGitTaskCallback } from '../types';\n\nconst functionNamesBuilderApi = ['customBinary', 'env', 'outputHandler', 'silent'];\n\nconst functionNamesPromiseApi = [\n 'add',\n 'addAnnotatedTag',\n 'addConfig',\n 'addRemote',\n 'addTag',\n 'applyPatch',\n 'binaryCatFile',\n 'branch',\n 'branchLocal',\n 'catFile',\n 'checkIgnore',\n 'checkIsRepo',\n 'checkout',\n 'checkoutBranch',\n 'checkoutLatestTag',\n 'checkoutLocalBranch',\n 'clean',\n 'clone',\n 'commit',\n 'cwd',\n 'deleteLocalBranch',\n 'deleteLocalBranches',\n 'diff',\n 'diffSummary',\n 'exec',\n 'fetch',\n 'getRemotes',\n 'init',\n 'listConfig',\n 'listRemote',\n 'log',\n 'merge',\n 'mergeFromTo',\n 'mirror',\n 'mv',\n 'pull',\n 'push',\n 'pushTags',\n 'raw',\n 'rebase',\n 'remote',\n 'removeRemote',\n 'reset',\n 'revert',\n 'revparse',\n 'rm',\n 'rmKeepLocal',\n 'show',\n 'stash',\n 'stashList',\n 'status',\n 'subModule',\n 'submoduleAdd',\n 'submoduleInit',\n 'submoduleUpdate',\n 'tag',\n 'tags',\n 'updateServerInfo',\n];\n\nexport function gitP(\n ...args: [] | [string] | [Partial] | [string, Partial]\n): SimpleGit {\n let git: any;\n\n let chain = Promise.resolve();\n\n try {\n git = gitInstanceFactory(...args);\n } catch (e) {\n chain = Promise.reject(e);\n }\n\n function builderReturn() {\n return promiseApi;\n }\n\n function chainReturn() {\n return chain;\n }\n\n const promiseApi = [...functionNamesBuilderApi, ...functionNamesPromiseApi].reduce(\n (api: any, name: string) => {\n const isAsync = functionNamesPromiseApi.includes(name);\n\n const valid = isAsync ? asyncWrapper(name, git) : syncWrapper(name, git, api);\n const alternative = isAsync ? chainReturn : builderReturn;\n\n Object.defineProperty(api, name, {\n enumerable: false,\n configurable: false,\n value: git ? valid : alternative,\n });\n\n return api;\n },\n {}\n );\n\n return promiseApi as SimpleGit;\n\n function asyncWrapper(fn: string, git: any): (...args: any[]) => Promise {\n return function (...args: any[]) {\n if (typeof args[args.length] === 'function') {\n throw new TypeError(\n 'Promise interface requires that handlers are not supplied inline, ' +\n 'trailing function not allowed in call to ' +\n fn\n );\n }\n\n return chain.then(function () {\n return new Promise(function (resolve, reject) {\n const callback: SimpleGitTaskCallback = (err: Error | null, result?: any) => {\n if (err) {\n return reject(toError(err));\n }\n\n resolve(result);\n };\n args.push(callback);\n\n git[fn].apply(git, args);\n });\n });\n };\n }\n\n function syncWrapper(fn: string, git: any, api: SimpleGit) {\n return (...args: any[]) => {\n git[fn](...args);\n\n return api;\n };\n }\n}\n\nfunction toError(error: Error | string | any): Error {\n if (error instanceof Error) {\n return error;\n }\n\n if (typeof error === 'string') {\n return new Error(error);\n }\n\n return new GitResponseError(error);\n}\n", "import { gitInstanceFactory } from './lib/git-factory';\n\nexport { gitP } from './lib/runners/promise-wrapped';\nexport * from './lib/api';\n\nexport const simpleGit = gitInstanceFactory;\n\nexport default gitInstanceFactory;\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,SAAS,YAA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AACpC;;;ACvJO,IAAM,YAAY;AAEzB,IAAO,cAAQ;", + "names": ["trimmed", "ExitCodes", "commands", "parser", "parsers", "CheckRepoActions", "parser", "trimmed", "CleanOptions", "append", "GitConfigScope", "DiffNameStatus", "ResetMode", "debug", "onError", "parser", "parser", "excludeOptions", "parsers", "parsers", "parsers", "parsers", "parser", "trimmed", "parsers", "parsers", "parsers", "parsers", "parser", "parsers", "disallowedCommand", "parsers", "parser", "GitExecutor", "SimpleGitApi", "Scheduler", "configurationErrorTask", "asArray", "filterArray", "filterPrimitives", "filterString", "filterStringOrStringArray", "filterType", "getTrailingOptions", "trailingFunctionArgument", "trailingOptionsArgument", "applyPatchTask", "branchTask", "branchLocalTask", "deleteBranchesTask", "deleteBranchTask", "checkIgnoreTask", "checkIsRepoTask", "cloneTask", "cloneMirrorTask", "cleanWithOptionsTask", "isCleanOptionsArray", "diffSummaryTask", "fetchTask", "moveTask", "pullTask", "pushTagsTask", "addRemoteTask", "getRemotesTask", "listRemotesTask", "remoteTask", "removeRemoteTask", "getResetMode", "resetTask", "stashListTask", "addSubModuleTask", "initSubModuleTask", "subModuleTask", "updateSubModuleTask", "addAnnotatedTagTask", "addTagTask", "tagListTask", "straightThroughBufferTask", "straightThroughStringTask", "Git", "_a", "input", "plugin", "_a", "_a", "_b", "append", "_a", "git", "args"] +} diff --git a/node_modules/simple-git/dist/esm/package.json b/node_modules/simple-git/dist/esm/package.json new file mode 100644 index 0000000..aead43d --- /dev/null +++ b/node_modules/simple-git/dist/esm/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/node_modules/simple-git/dist/src/lib/api.d.ts b/node_modules/simple-git/dist/src/lib/api.d.ts new file mode 100644 index 0000000..72ccf87 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/api.d.ts @@ -0,0 +1,13 @@ +import { pathspec } from './args/pathspec'; +import { GitConstructError } from './errors/git-construct-error'; +import { GitError } from './errors/git-error'; +import { GitPluginError } from './errors/git-plugin-error'; +import { GitResponseError } from './errors/git-response-error'; +import { TaskConfigurationError } from './errors/task-configuration-error'; +import { CheckRepoActions } from './tasks/check-is-repo'; +import { CleanOptions } from './tasks/clean'; +import { GitConfigScope } from './tasks/config'; +import { DiffNameStatus } from './tasks/diff-name-status'; +import { grepQueryBuilder } from './tasks/grep'; +import { ResetMode } from './tasks/reset'; +export { CheckRepoActions, CleanOptions, DiffNameStatus, GitConfigScope, GitConstructError, GitError, GitPluginError, GitResponseError, ResetMode, TaskConfigurationError, grepQueryBuilder, pathspec, }; diff --git a/node_modules/simple-git/dist/src/lib/args/log-format.d.ts b/node_modules/simple-git/dist/src/lib/args/log-format.d.ts new file mode 100644 index 0000000..4874e16 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/args/log-format.d.ts @@ -0,0 +1,9 @@ +export declare enum LogFormat { + NONE = "", + STAT = "--stat", + NUM_STAT = "--numstat", + NAME_ONLY = "--name-only", + NAME_STATUS = "--name-status" +} +export declare function logFormatFromCommand(customArgs: string[]): LogFormat; +export declare function isLogFormat(customArg: string | unknown): boolean; diff --git a/node_modules/simple-git/dist/src/lib/args/pathspec.d.ts b/node_modules/simple-git/dist/src/lib/args/pathspec.d.ts new file mode 100644 index 0000000..ca72497 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/args/pathspec.d.ts @@ -0,0 +1,3 @@ +export declare function pathspec(...paths: string[]): string; +export declare function isPathSpec(path: string | unknown): path is string; +export declare function toPaths(pathSpec: string): string[]; diff --git a/node_modules/simple-git/dist/src/lib/errors/git-construct-error.d.ts b/node_modules/simple-git/dist/src/lib/errors/git-construct-error.d.ts new file mode 100644 index 0000000..6c6f067 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/errors/git-construct-error.d.ts @@ -0,0 +1,15 @@ +import { GitError } from './git-error'; +import { SimpleGitOptions } from '../types'; +/** + * The `GitConstructError` is thrown when an error occurs in the constructor + * of the `simple-git` instance itself. Most commonly as a result of using + * a `baseDir` option that points to a folder that either does not exist, + * or cannot be read by the user the node script is running as. + * + * Check the `.message` property for more detail including the properties + * passed to the constructor. + */ +export declare class GitConstructError extends GitError { + readonly config: SimpleGitOptions; + constructor(config: SimpleGitOptions, message: string); +} diff --git a/node_modules/simple-git/dist/src/lib/errors/git-error.d.ts b/node_modules/simple-git/dist/src/lib/errors/git-error.d.ts new file mode 100644 index 0000000..2eff39b --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/errors/git-error.d.ts @@ -0,0 +1,30 @@ +import type { SimpleGitTask } from '../types'; +/** + * The `GitError` is thrown when the underlying `git` process throws a + * fatal exception (eg an `ENOENT` exception when attempting to use a + * non-writable directory as the root for your repo), and acts as the + * base class for more specific errors thrown by the parsing of the + * git response or errors in the configuration of the task about to + * be run. + * + * When an exception is thrown, pending tasks in the same instance will + * not be executed. The recommended way to run a series of tasks that + * can independently fail without needing to prevent future tasks from + * running is to catch them individually: + * + * ```typescript + import { gitP, SimpleGit, GitError, PullResult } from 'simple-git'; + + function catchTask (e: GitError) { + return e. + } + + const git = gitP(repoWorkingDir); + const pulled: PullResult | GitError = await git.pull().catch(catchTask); + const pushed: string | GitError = await git.pushTags().catch(catchTask); + ``` + */ +export declare class GitError extends Error { + task?: SimpleGitTask | undefined; + constructor(task?: SimpleGitTask | undefined, message?: string); +} diff --git a/node_modules/simple-git/dist/src/lib/errors/git-plugin-error.d.ts b/node_modules/simple-git/dist/src/lib/errors/git-plugin-error.d.ts new file mode 100644 index 0000000..94d4f8b --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/errors/git-plugin-error.d.ts @@ -0,0 +1,7 @@ +import { SimpleGitOptions, SimpleGitTask } from '../types'; +import { GitError } from './git-error'; +export declare class GitPluginError extends GitError { + task?: SimpleGitTask | undefined; + readonly plugin?: keyof SimpleGitOptions | undefined; + constructor(task?: SimpleGitTask | undefined, plugin?: keyof SimpleGitOptions | undefined, message?: string); +} diff --git a/node_modules/simple-git/dist/src/lib/errors/git-response-error.d.ts b/node_modules/simple-git/dist/src/lib/errors/git-response-error.d.ts new file mode 100644 index 0000000..5d77bb0 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/errors/git-response-error.d.ts @@ -0,0 +1,32 @@ +import { GitError } from './git-error'; +/** + * The `GitResponseError` is the wrapper for a parsed response that is treated as + * a fatal error, for example attempting a `merge` can leave the repo in a corrupted + * state when there are conflicts so the task will reject rather than resolve. + * + * For example, catching the merge conflict exception: + * + * ```typescript + import { gitP, SimpleGit, GitResponseError, MergeSummary } from 'simple-git'; + + const git = gitP(repoRoot); + const mergeOptions: string[] = ['--no-ff', 'other-branch']; + const mergeSummary: MergeSummary = await git.merge(mergeOptions) + .catch((e: GitResponseError) => e.git); + + if (mergeSummary.failed) { + // deal with the error + } + ``` + */ +export declare class GitResponseError extends GitError { + /** + * `.git` access the parsed response that is treated as being an error + */ + readonly git: T; + constructor( + /** + * `.git` access the parsed response that is treated as being an error + */ + git: T, message?: string); +} diff --git a/node_modules/simple-git/dist/src/lib/errors/task-configuration-error.d.ts b/node_modules/simple-git/dist/src/lib/errors/task-configuration-error.d.ts new file mode 100644 index 0000000..9f8a957 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/errors/task-configuration-error.d.ts @@ -0,0 +1,12 @@ +import { GitError } from './git-error'; +/** + * The `TaskConfigurationError` is thrown when a command was incorrectly + * configured. An error of this kind means that no attempt was made to + * run your command through the underlying `git` binary. + * + * Check the `.message` property for more detail on why your configuration + * resulted in an error. + */ +export declare class TaskConfigurationError extends GitError { + constructor(message?: string); +} diff --git a/node_modules/simple-git/dist/src/lib/git-factory.d.ts b/node_modules/simple-git/dist/src/lib/git-factory.d.ts new file mode 100644 index 0000000..12a608f --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/git-factory.d.ts @@ -0,0 +1,15 @@ +import { SimpleGitFactory } from '../../typings'; +import * as api from './api'; +import { SimpleGitOptions } from './types'; +/** + * Adds the necessary properties to the supplied object to enable it for use as + * the default export of a module. + * + * Eg: `module.exports = esModuleFactory({ something () {} })` + */ +export declare function esModuleFactory(defaultExport: T): T & { + __esModule: true; + default: T; +}; +export declare function gitExportFactory(factory: SimpleGitFactory): SimpleGitFactory & typeof api; +export declare function gitInstanceFactory(baseDir?: string | Partial, options?: Partial): any; diff --git a/node_modules/simple-git/dist/src/lib/git-logger.d.ts b/node_modules/simple-git/dist/src/lib/git-logger.d.ts new file mode 100644 index 0000000..7f3748d --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/git-logger.d.ts @@ -0,0 +1,21 @@ +import { Debugger } from 'debug'; +declare type OutputLoggingHandler = (message: string, ...args: any[]) => void; +export interface OutputLogger extends OutputLoggingHandler { + readonly label: string; + info: OutputLoggingHandler; + step(nextStep?: string): OutputLogger; + sibling(name: string): OutputLogger; +} +export declare function createLogger(label: string, verbose?: string | Debugger, initialStep?: string, infoDebugger?: Debugger): OutputLogger; +/** + * The `GitLogger` is used by the main `SimpleGit` runner to handle logging + * any warnings or errors. + */ +export declare class GitLogger { + private _out; + error: OutputLoggingHandler; + warn: OutputLoggingHandler; + constructor(_out?: Debugger); + silent(silence?: boolean): void; +} +export {}; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-branch-delete.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-branch-delete.d.ts new file mode 100644 index 0000000..ee05b45 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-branch-delete.d.ts @@ -0,0 +1,5 @@ +import { BranchMultiDeleteResult } from '../../../typings'; +import { TaskParser } from '../types'; +import { ExitCodes } from '../utils'; +export declare const parseBranchDeletions: TaskParser; +export declare function hasBranchDeletionError(data: string, processExitCode: ExitCodes): boolean; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-branch.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-branch.d.ts new file mode 100644 index 0000000..7c0fe2a --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-branch.d.ts @@ -0,0 +1,2 @@ +import type { BranchSummary } from '../../../typings'; +export declare function parseBranchSummary(stdOut: string): BranchSummary; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-commit.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-commit.d.ts new file mode 100644 index 0000000..1b47298 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-commit.d.ts @@ -0,0 +1,2 @@ +import { CommitResult } from '../../../typings'; +export declare function parseCommitResult(stdOut: string): CommitResult; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-diff-summary.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-diff-summary.d.ts new file mode 100644 index 0000000..4528dc4 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-diff-summary.d.ts @@ -0,0 +1,3 @@ +import { LogFormat } from '../args/log-format'; +import { DiffSummary } from '../responses/DiffSummary'; +export declare function getDiffParser(format?: LogFormat): (stdOut: string) => DiffSummary; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-fetch.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-fetch.d.ts new file mode 100644 index 0000000..98dc1a3 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-fetch.d.ts @@ -0,0 +1,2 @@ +import { FetchResult } from '../../../typings'; +export declare function parseFetchResult(stdOut: string, stdErr: string): FetchResult; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-list-log-summary.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-list-log-summary.d.ts new file mode 100644 index 0000000..e4a30da --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-list-log-summary.d.ts @@ -0,0 +1,6 @@ +import { LogResult } from '../../../typings'; +import { LogFormat } from '../args/log-format'; +export declare const START_BOUNDARY = "\u00F2\u00F2\u00F2\u00F2\u00F2\u00F2 "; +export declare const COMMIT_BOUNDARY = " \u00F2\u00F2"; +export declare const SPLITTER = " \u00F2 "; +export declare function createListLogSummaryParser(splitter?: string, fields?: string[], logFormat?: LogFormat): (stdOut: string) => LogResult; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-merge.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-merge.d.ts new file mode 100644 index 0000000..42435fd --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-merge.d.ts @@ -0,0 +1,11 @@ +import { MergeDetail, MergeResult } from '../../../typings'; +import { TaskParser } from '../types'; +/** + * Parse the complete response from `git.merge` + */ +export declare const parseMergeResult: TaskParser; +/** + * Parse the merge specific detail (ie: not the content also available in the pull detail) from `git.mnerge` + * @param stdOut + */ +export declare const parseMergeDetail: TaskParser; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-move.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-move.d.ts new file mode 100644 index 0000000..a2af49d --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-move.d.ts @@ -0,0 +1,2 @@ +import { MoveResult } from '../../../typings'; +export declare function parseMoveResult(stdOut: string): MoveResult; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-pull.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-pull.d.ts new file mode 100644 index 0000000..95d2877 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-pull.d.ts @@ -0,0 +1,6 @@ +import { PullDetail, PullResult } from '../../../typings'; +import { PullFailedSummary } from '../responses/PullSummary'; +import { TaskParser } from '../types'; +export declare const parsePullDetail: TaskParser; +export declare const parsePullResult: TaskParser; +export declare function parsePullErrorResult(stdOut: string, stdErr: string): "" | PullFailedSummary; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-push.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-push.d.ts new file mode 100644 index 0000000..9bb39b4 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-push.d.ts @@ -0,0 +1,4 @@ +import { PushDetail, PushResult } from '../../../typings'; +import { TaskParser } from '../types'; +export declare const parsePushResult: TaskParser; +export declare const parsePushDetail: TaskParser; diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-remote-messages.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-remote-messages.d.ts new file mode 100644 index 0000000..9c24989 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-remote-messages.d.ts @@ -0,0 +1,5 @@ +import { RemoteMessageResult, RemoteMessages } from '../../../typings'; +export declare function parseRemoteMessages(_stdOut: string, stdErr: string): RemoteMessageResult; +export declare class RemoteMessageSummary implements RemoteMessages { + readonly all: string[]; +} diff --git a/node_modules/simple-git/dist/src/lib/parsers/parse-remote-objects.d.ts b/node_modules/simple-git/dist/src/lib/parsers/parse-remote-objects.d.ts new file mode 100644 index 0000000..513b58a --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/parsers/parse-remote-objects.d.ts @@ -0,0 +1,3 @@ +import { RemoteMessageResult, RemoteMessages } from '../../../typings'; +import { RemoteLineParser } from '../utils'; +export declare const remoteMessagesObjectParsers: RemoteLineParser>[]; diff --git a/node_modules/simple-git/dist/src/lib/plugins/abort-plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/abort-plugin.d.ts new file mode 100644 index 0000000..133f1af --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/abort-plugin.d.ts @@ -0,0 +1,3 @@ +import { SimpleGitOptions } from '../types'; +import { SimpleGitPlugin } from './simple-git-plugin'; +export declare function abortPlugin(signal: SimpleGitOptions['abort']): (SimpleGitPlugin<"spawn.before"> | SimpleGitPlugin<"spawn.after">)[] | undefined; diff --git a/node_modules/simple-git/dist/src/lib/plugins/block-unsafe-operations-plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/block-unsafe-operations-plugin.d.ts new file mode 100644 index 0000000..bb4a7a8 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/block-unsafe-operations-plugin.d.ts @@ -0,0 +1,3 @@ +import type { SimpleGitPlugin } from './simple-git-plugin'; +import type { SimpleGitPluginConfig } from '../types'; +export declare function blockUnsafeOperationsPlugin({ allowUnsafeProtocolOverride, allowUnsafePack, }?: SimpleGitPluginConfig['unsafe']): SimpleGitPlugin<'spawn.args'>; diff --git a/node_modules/simple-git/dist/src/lib/plugins/command-config-prefixing-plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/command-config-prefixing-plugin.d.ts new file mode 100644 index 0000000..b5e4181 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/command-config-prefixing-plugin.d.ts @@ -0,0 +1,2 @@ +import { SimpleGitPlugin } from './simple-git-plugin'; +export declare function commandConfigPrefixingPlugin(configuration: string[]): SimpleGitPlugin<'spawn.args'>; diff --git a/node_modules/simple-git/dist/src/lib/plugins/completion-detection.plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/completion-detection.plugin.d.ts new file mode 100644 index 0000000..766e51d --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/completion-detection.plugin.d.ts @@ -0,0 +1,3 @@ +import { SimpleGitPluginConfig } from '../types'; +import { SimpleGitPlugin } from './simple-git-plugin'; +export declare function completionDetectionPlugin({ onClose, onExit, }?: SimpleGitPluginConfig['completion']): SimpleGitPlugin<'spawn.after'>; diff --git a/node_modules/simple-git/dist/src/lib/plugins/custom-binary.plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/custom-binary.plugin.d.ts new file mode 100644 index 0000000..6c88df9 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/custom-binary.plugin.d.ts @@ -0,0 +1,3 @@ +import type { SimpleGitOptions } from '../types'; +import { PluginStore } from './plugin-store'; +export declare function customBinaryPlugin(plugins: PluginStore, input?: SimpleGitOptions['binary'], allowUnsafe?: boolean): void; diff --git a/node_modules/simple-git/dist/src/lib/plugins/error-detection.plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/error-detection.plugin.d.ts new file mode 100644 index 0000000..095c73a --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/error-detection.plugin.d.ts @@ -0,0 +1,8 @@ +/// +import { GitExecutorResult, SimpleGitPluginConfig } from '../types'; +import { SimpleGitPlugin } from './simple-git-plugin'; +declare type TaskResult = Omit; +declare function isTaskError(result: TaskResult): boolean; +export declare function errorDetectionHandler(overwrite?: boolean, isError?: typeof isTaskError, errorMessage?: (result: TaskResult) => Buffer | Error): (error: Buffer | Error | undefined, result: TaskResult) => Error | Buffer | undefined; +export declare function errorDetectionPlugin(config: SimpleGitPluginConfig['errors']): SimpleGitPlugin<'task.error'>; +export {}; diff --git a/node_modules/simple-git/dist/src/lib/plugins/index.d.ts b/node_modules/simple-git/dist/src/lib/plugins/index.d.ts new file mode 100644 index 0000000..ac80073 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/index.d.ts @@ -0,0 +1,11 @@ +export * from './abort-plugin'; +export * from './block-unsafe-operations-plugin'; +export * from './command-config-prefixing-plugin'; +export * from './completion-detection.plugin'; +export * from './custom-binary.plugin'; +export * from './error-detection.plugin'; +export * from './plugin-store'; +export * from './progress-monitor-plugin'; +export * from './simple-git-plugin'; +export * from './spawn-options-plugin'; +export * from './timout-plugin'; diff --git a/node_modules/simple-git/dist/src/lib/plugins/plugin-store.d.ts b/node_modules/simple-git/dist/src/lib/plugins/plugin-store.d.ts new file mode 100644 index 0000000..5893437 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/plugin-store.d.ts @@ -0,0 +1,11 @@ +import type { SimpleGitPlugin, SimpleGitPluginType, SimpleGitPluginTypes } from './simple-git-plugin'; +import type { SimpleGitPluginConfig } from '../types'; +export declare class PluginStore { + private plugins; + private events; + on(type: K, listener: (data: SimpleGitPluginConfig[K]) => void): void; + reconfigure(type: K, data: SimpleGitPluginConfig[K]): void; + append(type: T, action: SimpleGitPlugin['action']): () => boolean; + add(plugin: void | SimpleGitPlugin | SimpleGitPlugin[]): () => void; + exec(type: T, data: SimpleGitPluginTypes[T]['data'], context: SimpleGitPluginTypes[T]['context']): typeof data; +} diff --git a/node_modules/simple-git/dist/src/lib/plugins/progress-monitor-plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/progress-monitor-plugin.d.ts new file mode 100644 index 0000000..a185dad --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/progress-monitor-plugin.d.ts @@ -0,0 +1,3 @@ +import { SimpleGitOptions } from '../types'; +import { SimpleGitPlugin } from './simple-git-plugin'; +export declare function progressMonitorPlugin(progress: Exclude): (SimpleGitPlugin<"spawn.after"> | SimpleGitPlugin<"spawn.args">)[]; diff --git a/node_modules/simple-git/dist/src/lib/plugins/simple-git-plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/simple-git-plugin.d.ts new file mode 100644 index 0000000..b06ce0c --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/simple-git-plugin.d.ts @@ -0,0 +1,47 @@ +/// +import { ChildProcess, SpawnOptions } from 'child_process'; +import { GitExecutorResult } from '../types'; +declare type SimpleGitTaskPluginContext = { + readonly method: string; + readonly commands: string[]; +}; +export interface SimpleGitPluginTypes { + 'spawn.args': { + data: string[]; + context: SimpleGitTaskPluginContext & {}; + }; + 'spawn.binary': { + data: string; + context: SimpleGitTaskPluginContext & {}; + }; + 'spawn.options': { + data: Partial; + context: SimpleGitTaskPluginContext & {}; + }; + 'spawn.before': { + data: void; + context: SimpleGitTaskPluginContext & { + kill(reason: Error): void; + }; + }; + 'spawn.after': { + data: void; + context: SimpleGitTaskPluginContext & { + spawned: ChildProcess; + close(exitCode: number, reason?: Error): void; + kill(reason: Error): void; + }; + }; + 'task.error': { + data: { + error?: Error; + }; + context: SimpleGitTaskPluginContext & GitExecutorResult; + }; +} +export declare type SimpleGitPluginType = keyof SimpleGitPluginTypes; +export interface SimpleGitPlugin { + action(data: SimpleGitPluginTypes[T]['data'], context: SimpleGitPluginTypes[T]['context']): typeof data; + type: T; +} +export {}; diff --git a/node_modules/simple-git/dist/src/lib/plugins/spawn-options-plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/spawn-options-plugin.d.ts new file mode 100644 index 0000000..77770fe --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/spawn-options-plugin.d.ts @@ -0,0 +1,4 @@ +/// +import { SpawnOptions } from 'child_process'; +import { SimpleGitPlugin } from './simple-git-plugin'; +export declare function spawnOptionsPlugin(spawnOptions: Partial): SimpleGitPlugin<'spawn.options'>; diff --git a/node_modules/simple-git/dist/src/lib/plugins/suffix-paths.plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/suffix-paths.plugin.d.ts new file mode 100644 index 0000000..e865d25 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/suffix-paths.plugin.d.ts @@ -0,0 +1,2 @@ +import { SimpleGitPlugin } from './simple-git-plugin'; +export declare function suffixPathsPlugin(): SimpleGitPlugin<'spawn.args'>; diff --git a/node_modules/simple-git/dist/src/lib/plugins/timout-plugin.d.ts b/node_modules/simple-git/dist/src/lib/plugins/timout-plugin.d.ts new file mode 100644 index 0000000..32d10fa --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/plugins/timout-plugin.d.ts @@ -0,0 +1,3 @@ +import type { SimpleGitPlugin } from './simple-git-plugin'; +import type { SimpleGitOptions } from '../types'; +export declare function timeoutPlugin({ block, stdErr, stdOut, }: Exclude): SimpleGitPlugin<'spawn.after'> | void; diff --git a/node_modules/simple-git/dist/src/lib/responses/BranchDeleteSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/BranchDeleteSummary.d.ts new file mode 100644 index 0000000..e7d3517 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/BranchDeleteSummary.d.ts @@ -0,0 +1,12 @@ +import { BranchMultiDeleteResult, BranchSingleDeleteFailure, BranchSingleDeleteResult, BranchSingleDeleteSuccess } from '../../../typings'; +export declare class BranchDeletionBatch implements BranchMultiDeleteResult { + all: BranchSingleDeleteResult[]; + branches: { + [branchName: string]: BranchSingleDeleteResult; + }; + errors: BranchSingleDeleteResult[]; + get success(): boolean; +} +export declare function branchDeletionSuccess(branch: string, hash: string): BranchSingleDeleteSuccess; +export declare function branchDeletionFailure(branch: string): BranchSingleDeleteFailure; +export declare function isSingleBranchDeleteFailure(test: BranchSingleDeleteResult): test is BranchSingleDeleteSuccess; diff --git a/node_modules/simple-git/dist/src/lib/responses/BranchSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/BranchSummary.d.ts new file mode 100644 index 0000000..9aa3342 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/BranchSummary.d.ts @@ -0,0 +1,14 @@ +import type { BranchSummary, BranchSummaryBranch } from '../../../typings'; +export declare enum BranchStatusIdentifier { + CURRENT = "*", + LINKED = "+" +} +export declare class BranchSummaryResult implements BranchSummary { + all: string[]; + branches: { + [p: string]: BranchSummaryBranch; + }; + current: string; + detached: boolean; + push(status: BranchStatusIdentifier | unknown, detached: boolean, name: string, commit: string, label: string): void; +} diff --git a/node_modules/simple-git/dist/src/lib/responses/CheckIgnore.d.ts b/node_modules/simple-git/dist/src/lib/responses/CheckIgnore.d.ts new file mode 100644 index 0000000..e15478f --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/CheckIgnore.d.ts @@ -0,0 +1,4 @@ +/** + * Parser for the `check-ignore` command - returns each file as a string array + */ +export declare const parseCheckIgnore: (text: string) => string[]; diff --git a/node_modules/simple-git/dist/src/lib/responses/CleanSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/CleanSummary.d.ts new file mode 100644 index 0000000..d49ef04 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/CleanSummary.d.ts @@ -0,0 +1,9 @@ +import { CleanSummary } from '../../../typings'; +export declare class CleanResponse implements CleanSummary { + readonly dryRun: boolean; + paths: string[]; + files: string[]; + folders: string[]; + constructor(dryRun: boolean); +} +export declare function cleanSummaryParser(dryRun: boolean, text: string): CleanSummary; diff --git a/node_modules/simple-git/dist/src/lib/responses/ConfigList.d.ts b/node_modules/simple-git/dist/src/lib/responses/ConfigList.d.ts new file mode 100644 index 0000000..f01ed6a --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/ConfigList.d.ts @@ -0,0 +1,13 @@ +import { ConfigGetResult, ConfigListSummary, ConfigValues } from '../../../typings'; +export declare class ConfigList implements ConfigListSummary { + files: string[]; + values: { + [fileName: string]: ConfigValues; + }; + private _all; + get all(): ConfigValues; + addFile(file: string): ConfigValues; + addValue(file: string, key: string, value: string): void; +} +export declare function configListParser(text: string): ConfigList; +export declare function configGetParser(text: string, key: string): ConfigGetResult; diff --git a/node_modules/simple-git/dist/src/lib/responses/DiffSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/DiffSummary.d.ts new file mode 100644 index 0000000..16d63f0 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/DiffSummary.d.ts @@ -0,0 +1,10 @@ +import { DiffResult, DiffResultBinaryFile, DiffResultTextFile } from '../../../typings'; +/*** + * The DiffSummary is returned as a response to getting `git().status()` + */ +export declare class DiffSummary implements DiffResult { + changed: number; + deletions: number; + insertions: number; + files: Array; +} diff --git a/node_modules/simple-git/dist/src/lib/responses/FileStatusSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/FileStatusSummary.d.ts new file mode 100644 index 0000000..cc370cc --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/FileStatusSummary.d.ts @@ -0,0 +1,9 @@ +import { FileStatusResult } from '../../../typings'; +export declare const fromPathRegex: RegExp; +export declare class FileStatusSummary implements FileStatusResult { + path: string; + index: string; + working_dir: string; + readonly from: string | undefined; + constructor(path: string, index: string, working_dir: string); +} diff --git a/node_modules/simple-git/dist/src/lib/responses/GetRemoteSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/GetRemoteSummary.d.ts new file mode 100644 index 0000000..3ef9109 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/GetRemoteSummary.d.ts @@ -0,0 +1,11 @@ +export interface RemoteWithoutRefs { + name: string; +} +export interface RemoteWithRefs extends RemoteWithoutRefs { + refs: { + fetch: string; + push: string; + }; +} +export declare function parseGetRemotes(text: string): RemoteWithoutRefs[]; +export declare function parseGetRemotesVerbose(text: string): RemoteWithRefs[]; diff --git a/node_modules/simple-git/dist/src/lib/responses/InitSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/InitSummary.d.ts new file mode 100644 index 0000000..634911f --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/InitSummary.d.ts @@ -0,0 +1,9 @@ +import { InitResult } from '../../../typings'; +export declare class InitSummary implements InitResult { + readonly bare: boolean; + readonly path: string; + readonly existing: boolean; + readonly gitDir: string; + constructor(bare: boolean, path: string, existing: boolean, gitDir: string); +} +export declare function parseInit(bare: boolean, path: string, text: string): InitSummary; diff --git a/node_modules/simple-git/dist/src/lib/responses/MergeSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/MergeSummary.d.ts new file mode 100644 index 0000000..519e954 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/MergeSummary.d.ts @@ -0,0 +1,16 @@ +import { MergeConflict, MergeConflictDeletion, MergeDetail, MergeResultStatus } from '../../../typings'; +export declare class MergeSummaryConflict implements MergeConflict { + readonly reason: string; + readonly file: string | null; + readonly meta?: MergeConflictDeletion | undefined; + constructor(reason: string, file?: string | null, meta?: MergeConflictDeletion | undefined); + toString(): string; +} +export declare class MergeSummaryDetail implements MergeDetail { + conflicts: MergeConflict[]; + merges: string[]; + result: MergeResultStatus; + get failed(): boolean; + get reason(): string; + toString(): string; +} diff --git a/node_modules/simple-git/dist/src/lib/responses/PullSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/PullSummary.d.ts new file mode 100644 index 0000000..c5bc9bc --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/PullSummary.d.ts @@ -0,0 +1,25 @@ +import { PullDetailFileChanges, PullDetailSummary, PullFailedResult, PullResult } from '../../../typings'; +export declare class PullSummary implements PullResult { + remoteMessages: { + all: never[]; + }; + created: never[]; + deleted: string[]; + files: string[]; + deletions: PullDetailFileChanges; + insertions: PullDetailFileChanges; + summary: PullDetailSummary; +} +export declare class PullFailedSummary implements PullFailedResult { + remote: string; + hash: { + local: string; + remote: string; + }; + branch: { + local: string; + remote: string; + }; + message: string; + toString(): string; +} diff --git a/node_modules/simple-git/dist/src/lib/responses/StatusSummary.d.ts b/node_modules/simple-git/dist/src/lib/responses/StatusSummary.d.ts new file mode 100644 index 0000000..24e0ea9 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/StatusSummary.d.ts @@ -0,0 +1,19 @@ +import { StatusResult } from '../../../typings'; +export declare class StatusSummary implements StatusResult { + not_added: never[]; + conflicted: never[]; + created: never[]; + deleted: never[]; + ignored: undefined; + modified: never[]; + renamed: never[]; + files: never[]; + staged: never[]; + ahead: number; + behind: number; + current: null; + tracking: null; + detached: boolean; + isClean: () => boolean; +} +export declare const parseStatusSummary: (text: string) => StatusResult; diff --git a/node_modules/simple-git/dist/src/lib/responses/TagList.d.ts b/node_modules/simple-git/dist/src/lib/responses/TagList.d.ts new file mode 100644 index 0000000..b72180d --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/responses/TagList.d.ts @@ -0,0 +1,7 @@ +import { TagResult } from '../../../typings'; +export declare class TagList implements TagResult { + readonly all: string[]; + readonly latest: string | undefined; + constructor(all: string[], latest: string | undefined); +} +export declare const parseTagList: (data: string, customSort?: boolean) => TagList; diff --git a/node_modules/simple-git/dist/src/lib/runners/git-executor-chain.d.ts b/node_modules/simple-git/dist/src/lib/runners/git-executor-chain.d.ts new file mode 100644 index 0000000..ae27d9e --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/runners/git-executor-chain.d.ts @@ -0,0 +1,25 @@ +import { PluginStore } from '../plugins'; +import { outputHandler, SimpleGitExecutor, SimpleGitTask } from '../types'; +import { Scheduler } from './scheduler'; +export declare class GitExecutorChain implements SimpleGitExecutor { + private _executor; + private _scheduler; + private _plugins; + private _chain; + private _queue; + private _cwd; + get cwd(): string; + set cwd(cwd: string); + get env(): import("../types").GitExecutorEnv; + get outputHandler(): outputHandler | undefined; + constructor(_executor: SimpleGitExecutor, _scheduler: Scheduler, _plugins: PluginStore); + chain(): this; + push(task: SimpleGitTask): Promise; + private attemptTask; + private onFatalException; + private attemptRemoteTask; + private attemptEmptyTask; + private handleTaskData; + private gitResponse; + private _beforeSpawn; +} diff --git a/node_modules/simple-git/dist/src/lib/runners/git-executor.d.ts b/node_modules/simple-git/dist/src/lib/runners/git-executor.d.ts new file mode 100644 index 0000000..d76de39 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/runners/git-executor.d.ts @@ -0,0 +1,14 @@ +import type { PluginStore } from '../plugins'; +import type { GitExecutorEnv, outputHandler, SimpleGitExecutor, SimpleGitTask } from '../types'; +import { Scheduler } from './scheduler'; +export declare class GitExecutor implements SimpleGitExecutor { + cwd: string; + private _scheduler; + private _plugins; + private _chain; + env: GitExecutorEnv; + outputHandler?: outputHandler; + constructor(cwd: string, _scheduler: Scheduler, _plugins: PluginStore); + chain(): SimpleGitExecutor; + push(task: SimpleGitTask): Promise; +} diff --git a/node_modules/simple-git/dist/src/lib/runners/promise-wrapped.d.ts b/node_modules/simple-git/dist/src/lib/runners/promise-wrapped.d.ts new file mode 100644 index 0000000..4f8d694 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/runners/promise-wrapped.d.ts @@ -0,0 +1,2 @@ +import { SimpleGit, SimpleGitOptions } from '../../../typings'; +export declare function gitP(...args: [] | [string] | [Partial] | [string, Partial]): SimpleGit; diff --git a/node_modules/simple-git/dist/src/lib/runners/scheduler.d.ts b/node_modules/simple-git/dist/src/lib/runners/scheduler.d.ts new file mode 100644 index 0000000..847ed31 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/runners/scheduler.d.ts @@ -0,0 +1,11 @@ +declare type ScheduleCompleteCallback = () => void; +export declare class Scheduler { + private concurrency; + private logger; + private pending; + private running; + constructor(concurrency?: number); + private schedule; + next(): Promise; +} +export {}; diff --git a/node_modules/simple-git/dist/src/lib/runners/tasks-pending-queue.d.ts b/node_modules/simple-git/dist/src/lib/runners/tasks-pending-queue.d.ts new file mode 100644 index 0000000..61d6073 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/runners/tasks-pending-queue.d.ts @@ -0,0 +1,23 @@ +import { SimpleGitTask } from '../types'; +import { GitError } from '../errors/git-error'; +import { OutputLogger } from '../git-logger'; +declare type AnySimpleGitTask = SimpleGitTask; +declare type TaskInProgress = { + name: string; + logger: OutputLogger; + task: AnySimpleGitTask; +}; +export declare class TasksPendingQueue { + private logLabel; + private _queue; + constructor(logLabel?: string); + private withProgress; + private createProgress; + push(task: AnySimpleGitTask): TaskInProgress; + fatal(err: GitError): void; + complete(task: AnySimpleGitTask): void; + attempt(task: AnySimpleGitTask): TaskInProgress; + static getName(name?: string): string; + private static counter; +} +export {}; diff --git a/node_modules/simple-git/dist/src/lib/simple-git-api.d.ts b/node_modules/simple-git/dist/src/lib/simple-git-api.d.ts new file mode 100644 index 0000000..0fd7761 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/simple-git-api.d.ts @@ -0,0 +1,20 @@ +import { SimpleGitBase } from '../../typings'; +import { outputHandler, SimpleGitExecutor, SimpleGitTask, SimpleGitTaskCallback } from './types'; +export declare class SimpleGitApi implements SimpleGitBase { + private _executor; + constructor(_executor: SimpleGitExecutor); + protected _runTask(task: SimpleGitTask, then?: SimpleGitTaskCallback): any; + add(files: string | string[]): any; + cwd(directory: string | { + path: string; + root?: boolean; + }): any; + hashObject(path: string, write: boolean | unknown): any; + init(bare?: boolean | unknown): any; + merge(): any; + mergeFromTo(remote: string, branch: string): any; + outputHandler(handler: outputHandler): this; + push(): any; + stash(): any; + status(): any; +} diff --git a/node_modules/simple-git/dist/src/lib/task-callback.d.ts b/node_modules/simple-git/dist/src/lib/task-callback.d.ts new file mode 100644 index 0000000..dda89af --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/task-callback.d.ts @@ -0,0 +1,2 @@ +import { SimpleGitTask, SimpleGitTaskCallback } from './types'; +export declare function taskCallback(task: SimpleGitTask, response: Promise, callback?: SimpleGitTaskCallback): void; diff --git a/node_modules/simple-git/dist/src/lib/tasks/apply-patch.d.ts b/node_modules/simple-git/dist/src/lib/tasks/apply-patch.d.ts new file mode 100644 index 0000000..c1e1551 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/apply-patch.d.ts @@ -0,0 +1,3 @@ +import { OptionFlags, Options, StringTask } from '../types'; +export declare type ApplyOptions = Options & OptionFlags<'--stat' | '--numstat' | '--summary' | '--check' | '--index' | '--intent-to-add' | '--3way' | '--apply' | '--no-add' | '-R' | '--reverse' | '--allow-binary-replacement' | '--binary' | '--reject' | '-z' | '--inaccurate-eof' | '--recount' | '--cached' | '--ignore-space-change' | '--ignore-whitespace' | '--verbose' | '--unsafe-paths'> & OptionFlags<'--whitespace', 'nowarn' | 'warn' | 'fix' | 'error' | 'error-all'> & OptionFlags<'--build-fake-ancestor' | '--exclude' | '--include' | '--directory', string> & OptionFlags<'-p' | '-C', number>; +export declare function applyPatchTask(patches: string[], customArgs: string[]): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/branch.d.ts b/node_modules/simple-git/dist/src/lib/tasks/branch.d.ts new file mode 100644 index 0000000..157b2ae --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/branch.d.ts @@ -0,0 +1,7 @@ +import { BranchMultiDeleteResult, BranchSingleDeleteResult, BranchSummary } from '../../../typings'; +import { StringTask } from '../types'; +export declare function containsDeleteBranchCommand(commands: string[]): boolean; +export declare function branchTask(customArgs: string[]): StringTask; +export declare function branchLocalTask(): StringTask; +export declare function deleteBranchesTask(branches: string[], forceDelete?: boolean): StringTask; +export declare function deleteBranchTask(branch: string, forceDelete?: boolean): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/change-working-directory.d.ts b/node_modules/simple-git/dist/src/lib/tasks/change-working-directory.d.ts new file mode 100644 index 0000000..1ad1009 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/change-working-directory.d.ts @@ -0,0 +1,2 @@ +import { SimpleGitExecutor } from '../types'; +export declare function changeWorkingDirectoryTask(directory: string, root?: SimpleGitExecutor): import("./task").EmptyTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/check-ignore.d.ts b/node_modules/simple-git/dist/src/lib/tasks/check-ignore.d.ts new file mode 100644 index 0000000..7b34b8d --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/check-ignore.d.ts @@ -0,0 +1,2 @@ +import { StringTask } from '../types'; +export declare function checkIgnoreTask(paths: string[]): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/check-is-repo.d.ts b/node_modules/simple-git/dist/src/lib/tasks/check-is-repo.d.ts new file mode 100644 index 0000000..580846f --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/check-is-repo.d.ts @@ -0,0 +1,9 @@ +import { Maybe, StringTask } from '../types'; +export declare enum CheckRepoActions { + BARE = "bare", + IN_TREE = "tree", + IS_REPO_ROOT = "root" +} +export declare function checkIsRepoTask(action: Maybe): StringTask; +export declare function checkIsRepoRootTask(): StringTask; +export declare function checkIsBareRepoTask(): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/checkout.d.ts b/node_modules/simple-git/dist/src/lib/tasks/checkout.d.ts new file mode 100644 index 0000000..40bcb4f --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/checkout.d.ts @@ -0,0 +1,2 @@ +import type { SimpleGit } from '../../../typings'; +export default function (): Pick; diff --git a/node_modules/simple-git/dist/src/lib/tasks/clean.d.ts b/node_modules/simple-git/dist/src/lib/tasks/clean.d.ts new file mode 100644 index 0000000..c3f7ce7 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/clean.d.ts @@ -0,0 +1,25 @@ +import { CleanSummary } from '../../../typings'; +import { StringTask } from '../types'; +export declare const CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported"; +export declare const CONFIG_ERROR_MODE_REQUIRED = "Git clean mode parameter (\"n\" or \"f\") is required"; +export declare const CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: "; +/** + * All supported option switches available for use in a `git.clean` operation + */ +export declare enum CleanOptions { + DRY_RUN = "n", + FORCE = "f", + IGNORED_INCLUDED = "x", + IGNORED_ONLY = "X", + EXCLUDING = "e", + QUIET = "q", + RECURSIVE = "d" +} +/** + * The two modes `git.clean` can run in - one of these must be supplied in order + * for the command to not throw a `TaskConfigurationError` + */ +export declare type CleanMode = CleanOptions.FORCE | CleanOptions.DRY_RUN; +export declare function cleanWithOptionsTask(mode: CleanMode | string, customArgs: string[]): import("./task").EmptyTask | StringTask; +export declare function cleanTask(mode: CleanMode, customArgs: string[]): StringTask; +export declare function isCleanOptionsArray(input: string[]): input is CleanOptions[]; diff --git a/node_modules/simple-git/dist/src/lib/tasks/clone.d.ts b/node_modules/simple-git/dist/src/lib/tasks/clone.d.ts new file mode 100644 index 0000000..d1755b1 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/clone.d.ts @@ -0,0 +1,5 @@ +import { EmptyTask } from './task'; +import { OptionFlags, Options, StringTask } from '../types'; +export declare type CloneOptions = Options & OptionFlags<'--bare' | '--dissociate' | '--mirror' | '--no-checkout' | '--no-remote-submodules' | '--no-shallow-submodules' | '--no-single-branch' | '--no-tags' | '--remote-submodules' | '--single-branch' | '--shallow-submodules' | '--verbose'> & OptionFlags<'--depth' | '-j' | '--jobs', number> & OptionFlags<'--branch' | '--origin' | '--recurse-submodules' | '--separate-git-dir' | '--shallow-exclude' | '--shallow-since' | '--template', string>; +export declare function cloneTask(repo: string | undefined, directory: string | undefined, customArgs: string[]): StringTask | EmptyTask; +export declare function cloneMirrorTask(repo: string | undefined, directory: string | undefined, customArgs: string[]): EmptyTask | StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/commit.d.ts b/node_modules/simple-git/dist/src/lib/tasks/commit.d.ts new file mode 100644 index 0000000..e395456 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/commit.d.ts @@ -0,0 +1,4 @@ +import type { CommitResult, SimpleGit } from '../../../typings'; +import type { StringTask } from '../types'; +export declare function commitTask(message: string[], files: string[], customArgs: string[]): StringTask; +export default function (): Pick; diff --git a/node_modules/simple-git/dist/src/lib/tasks/config.d.ts b/node_modules/simple-git/dist/src/lib/tasks/config.d.ts new file mode 100644 index 0000000..d16d557 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/config.d.ts @@ -0,0 +1,8 @@ +import type { SimpleGit } from '../../../typings'; +export declare enum GitConfigScope { + system = "system", + global = "global", + local = "local", + worktree = "worktree" +} +export default function (): Pick; diff --git a/node_modules/simple-git/dist/src/lib/tasks/diff-name-status.d.ts b/node_modules/simple-git/dist/src/lib/tasks/diff-name-status.d.ts new file mode 100644 index 0000000..f142dd1 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/diff-name-status.d.ts @@ -0,0 +1,12 @@ +export declare enum DiffNameStatus { + ADDED = "A", + COPIED = "C", + DELETED = "D", + MODIFIED = "M", + RENAMED = "R", + CHANGED = "T", + UNMERGED = "U", + UNKNOWN = "X", + BROKEN = "B" +} +export declare function isDiffNameStatus(input: string): input is DiffNameStatus; diff --git a/node_modules/simple-git/dist/src/lib/tasks/diff.d.ts b/node_modules/simple-git/dist/src/lib/tasks/diff.d.ts new file mode 100644 index 0000000..8bcd1f2 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/diff.d.ts @@ -0,0 +1,5 @@ +import { StringTask } from '../types'; +import { DiffResult } from '../../../typings'; +import { EmptyTask } from './task'; +export declare function diffSummaryTask(customArgs: string[]): StringTask | EmptyTask; +export declare function validateLogFormatConfig(customArgs: unknown[]): EmptyTask | void; diff --git a/node_modules/simple-git/dist/src/lib/tasks/fetch.d.ts b/node_modules/simple-git/dist/src/lib/tasks/fetch.d.ts new file mode 100644 index 0000000..fbc29c7 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/fetch.d.ts @@ -0,0 +1,4 @@ +import { FetchResult } from '../../../typings'; +import { StringTask } from '../types'; +import { EmptyTask } from './task'; +export declare function fetchTask(remote: string, branch: string, customArgs: string[]): StringTask | EmptyTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/first-commit.d.ts b/node_modules/simple-git/dist/src/lib/tasks/first-commit.d.ts new file mode 100644 index 0000000..912f5e9 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/first-commit.d.ts @@ -0,0 +1,2 @@ +import { SimpleGit } from '../../../typings'; +export default function (): Pick; diff --git a/node_modules/simple-git/dist/src/lib/tasks/grep.d.ts b/node_modules/simple-git/dist/src/lib/tasks/grep.d.ts new file mode 100644 index 0000000..653159a --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/grep.d.ts @@ -0,0 +1,12 @@ +import { SimpleGit } from '../../../typings'; +export interface GitGrepQuery extends Iterable { + /** Adds one or more terms to be grouped as an "and" to any other terms */ + and(...and: string[]): this; + /** Adds one or more search terms - git.grep will "or" this to other terms */ + param(...param: string[]): this; +} +/** + * Creates a new builder for a `git.grep` query with optional params + */ +export declare function grepQueryBuilder(...params: string[]): GitGrepQuery; +export default function (): Pick; diff --git a/node_modules/simple-git/dist/src/lib/tasks/hash-object.d.ts b/node_modules/simple-git/dist/src/lib/tasks/hash-object.d.ts new file mode 100644 index 0000000..cedf3e0 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/hash-object.d.ts @@ -0,0 +1,5 @@ +import { StringTask } from '../types'; +/** + * Task used by `git.hashObject` + */ +export declare function hashObjectTask(filePath: string, write: boolean): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/init.d.ts b/node_modules/simple-git/dist/src/lib/tasks/init.d.ts new file mode 100644 index 0000000..ca7f126 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/init.d.ts @@ -0,0 +1,3 @@ +import { InitResult } from '../../../typings'; +import { StringTask } from '../types'; +export declare function initTask(bare: boolean | undefined, path: string, customArgs: string[]): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/log.d.ts b/node_modules/simple-git/dist/src/lib/tasks/log.d.ts new file mode 100644 index 0000000..cc9293b --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/log.d.ts @@ -0,0 +1,32 @@ +import type { Options, StringTask } from '../types'; +import type { LogResult, SimpleGit } from '../../../typings'; +export interface DefaultLogFields { + hash: string; + date: string; + message: string; + refs: string; + body: string; + author_name: string; + author_email: string; +} +export declare type LogOptions = { + file?: string; + format?: T; + from?: string; + mailMap?: boolean; + maxCount?: number; + multiLine?: boolean; + splitter?: string; + strictDate?: boolean; + symmetric?: boolean; + to?: string; +}; +interface ParsedLogOptions { + fields: string[]; + splitter: string; + commands: string[]; +} +export declare function parseLogOptions(opt?: Options | LogOptions, customArgs?: string[]): ParsedLogOptions; +export declare function logTask(splitter: string, fields: string[], customArgs: string[]): StringTask>; +export default function (): Pick; +export {}; diff --git a/node_modules/simple-git/dist/src/lib/tasks/merge.d.ts b/node_modules/simple-git/dist/src/lib/tasks/merge.d.ts new file mode 100644 index 0000000..663e80b --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/merge.d.ts @@ -0,0 +1,4 @@ +import { MergeResult } from '../../../typings'; +import { StringTask } from '../types'; +import { EmptyTask } from './task'; +export declare function mergeTask(customArgs: string[]): EmptyTask | StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/move.d.ts b/node_modules/simple-git/dist/src/lib/tasks/move.d.ts new file mode 100644 index 0000000..75ae9af --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/move.d.ts @@ -0,0 +1,3 @@ +import { MoveResult } from '../../../typings'; +import { StringTask } from '../types'; +export declare function moveTask(from: string | string[], to: string): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/pull.d.ts b/node_modules/simple-git/dist/src/lib/tasks/pull.d.ts new file mode 100644 index 0000000..c08062f --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/pull.d.ts @@ -0,0 +1,3 @@ +import { PullResult } from '../../../typings'; +import { Maybe, StringTask } from '../types'; +export declare function pullTask(remote: Maybe, branch: Maybe, customArgs: string[]): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/push.d.ts b/node_modules/simple-git/dist/src/lib/tasks/push.d.ts new file mode 100644 index 0000000..4d18c71 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/push.d.ts @@ -0,0 +1,9 @@ +import { PushResult } from '../../../typings'; +import { StringTask } from '../types'; +declare type PushRef = { + remote?: string; + branch?: string; +}; +export declare function pushTagsTask(ref: PushRef | undefined, customArgs: string[]): StringTask; +export declare function pushTask(ref: PushRef | undefined, customArgs: string[]): StringTask; +export {}; diff --git a/node_modules/simple-git/dist/src/lib/tasks/remote.d.ts b/node_modules/simple-git/dist/src/lib/tasks/remote.d.ts new file mode 100644 index 0000000..364697b --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/remote.d.ts @@ -0,0 +1,6 @@ +import { StringTask } from '../types'; +export declare function addRemoteTask(remoteName: string, remoteRepo: string, customArgs: string[]): StringTask; +export declare function getRemotesTask(verbose: boolean): StringTask; +export declare function listRemotesTask(customArgs: string[]): StringTask; +export declare function remoteTask(customArgs: string[]): StringTask; +export declare function removeRemoteTask(remoteName: string): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/reset.d.ts b/node_modules/simple-git/dist/src/lib/tasks/reset.d.ts new file mode 100644 index 0000000..468fe87 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/reset.d.ts @@ -0,0 +1,11 @@ +import { Maybe, OptionFlags, Options } from '../types'; +export declare enum ResetMode { + MIXED = "mixed", + SOFT = "soft", + HARD = "hard", + MERGE = "merge", + KEEP = "keep" +} +export declare type ResetOptions = Options & OptionFlags<'-q' | '--quiet' | '--no-quiet' | '--pathspec-from-nul'> & OptionFlags<'--pathspec-from-file', string>; +export declare function resetTask(mode: Maybe, customArgs: string[]): import("../types").StringTask; +export declare function getResetMode(mode: ResetMode | any): Maybe; diff --git a/node_modules/simple-git/dist/src/lib/tasks/show.d.ts b/node_modules/simple-git/dist/src/lib/tasks/show.d.ts new file mode 100644 index 0000000..7cb154d --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/show.d.ts @@ -0,0 +1,2 @@ +import { SimpleGit } from '../../../typings'; +export default function (): Pick; diff --git a/node_modules/simple-git/dist/src/lib/tasks/stash-list.d.ts b/node_modules/simple-git/dist/src/lib/tasks/stash-list.d.ts new file mode 100644 index 0000000..9470967 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/stash-list.d.ts @@ -0,0 +1,4 @@ +import { LogOptions, LogResult } from '../../../typings'; +import type { StringTask } from '../types'; +import type { EmptyTask } from './task'; +export declare function stashListTask(opt: LogOptions | undefined, customArgs: string[]): EmptyTask | StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/status.d.ts b/node_modules/simple-git/dist/src/lib/tasks/status.d.ts new file mode 100644 index 0000000..45fec0f --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/status.d.ts @@ -0,0 +1,3 @@ +import { StatusResult } from '../../../typings'; +import { StringTask } from '../types'; +export declare function statusTask(customArgs: string[]): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/sub-module.d.ts b/node_modules/simple-git/dist/src/lib/tasks/sub-module.d.ts new file mode 100644 index 0000000..ac4f6f8 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/sub-module.d.ts @@ -0,0 +1,5 @@ +import { StringTask } from '../types'; +export declare function addSubModuleTask(repo: string, path: string): StringTask; +export declare function initSubModuleTask(customArgs: string[]): StringTask; +export declare function subModuleTask(customArgs: string[]): StringTask; +export declare function updateSubModuleTask(customArgs: string[]): StringTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/tag.d.ts b/node_modules/simple-git/dist/src/lib/tasks/tag.d.ts new file mode 100644 index 0000000..b1dbb31 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/tag.d.ts @@ -0,0 +1,18 @@ +import { TagResult } from '../../../typings'; +import { StringTask } from '../types'; +/** + * Task used by `git.tags` + */ +export declare function tagListTask(customArgs?: string[]): StringTask; +/** + * Task used by `git.addTag` + */ +export declare function addTagTask(name: string): StringTask<{ + name: string; +}>; +/** + * Task used by `git.addTag` + */ +export declare function addAnnotatedTagTask(name: string, tagMessage: string): StringTask<{ + name: string; +}>; diff --git a/node_modules/simple-git/dist/src/lib/tasks/task.d.ts b/node_modules/simple-git/dist/src/lib/tasks/task.d.ts new file mode 100644 index 0000000..4f8c6c0 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/task.d.ts @@ -0,0 +1,14 @@ +import type { BufferTask, EmptyTaskParser, SimpleGitTask, StringTask } from '../types'; +export declare const EMPTY_COMMANDS: []; +export declare type EmptyTask = { + commands: typeof EMPTY_COMMANDS; + format: 'empty'; + parser: EmptyTaskParser; + onError?: undefined; +}; +export declare function adhocExecTask(parser: EmptyTaskParser): EmptyTask; +export declare function configurationErrorTask(error: Error | string): EmptyTask; +export declare function straightThroughStringTask(commands: string[], trimmed?: boolean): StringTask; +export declare function straightThroughBufferTask(commands: string[]): BufferTask; +export declare function isBufferTask(task: SimpleGitTask): task is BufferTask; +export declare function isEmptyTask(task: SimpleGitTask): task is EmptyTask; diff --git a/node_modules/simple-git/dist/src/lib/tasks/version.d.ts b/node_modules/simple-git/dist/src/lib/tasks/version.d.ts new file mode 100644 index 0000000..a08dade --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/tasks/version.d.ts @@ -0,0 +1,9 @@ +import type { SimpleGit } from '../../../typings'; +export interface VersionResult { + major: number; + minor: number; + patch: number | string; + agent: string; + installed: boolean; +} +export default function (): Pick; diff --git a/node_modules/simple-git/dist/src/lib/types/handlers.d.ts b/node_modules/simple-git/dist/src/lib/types/handlers.d.ts new file mode 100644 index 0000000..3a788f3 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/types/handlers.d.ts @@ -0,0 +1,21 @@ +import { GitError } from '../errors/git-error'; +/** + * The node-style callback to a task accepts either two arguments with the first as a null + * and the second as the data, or just one argument which is an error. + */ +export declare type SimpleGitTaskCallback = (err: E | null, data: T) => void; +/** + * The event data emitted to the progress handler whenever progress detail is received. + */ +export interface SimpleGitProgressEvent { + /** The underlying method called - push, pull etc */ + method: string; + /** The type of progress being reported, note that any one task may emit many stages - for example `git clone` emits both `receiving` and `resolving` */ + stage: 'compressing' | 'counting' | 'receiving' | 'resolving' | 'unknown' | 'writing' | string; + /** The percent progressed as a number 0 - 100 */ + progress: number; + /** The number of items processed so far */ + processed: number; + /** The total number of items to be processed */ + total: number; +} diff --git a/node_modules/simple-git/dist/src/lib/types/index.d.ts b/node_modules/simple-git/dist/src/lib/types/index.d.ts new file mode 100644 index 0000000..a3f38a5 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/types/index.d.ts @@ -0,0 +1,158 @@ +/// +/// +/// +/// +import type { SpawnOptions } from 'child_process'; +import type { SimpleGitTask } from './tasks'; +import type { SimpleGitProgressEvent } from './handlers'; +export * from './handlers'; +export * from './tasks'; +/** + * Most tasks accept custom options as an array of strings as well as the + * options object. Unless the task is explicitly documented as such, the + * tasks will not accept both formats at the same time, preferring whichever + * appears last in the arguments. + */ +export declare type TaskOptions = string[] | O; +/** + * Options supplied in most tasks as an optional trailing object + */ +export declare type OptionsValues = null | string | number; +export declare type Options = Record; +export declare type OptionFlags = Partial>; +/** + * A function called by the executor immediately after creating a child + * process. Allows the calling application to implement custom handling of + * the incoming stream of data from the `git`. + */ +export declare type outputHandler = (command: string, stdout: NodeJS.ReadableStream, stderr: NodeJS.ReadableStream, args: string[]) => void; +/** + * Environment variables to be passed into the child process. + */ +export declare type GitExecutorEnv = NodeJS.ProcessEnv | undefined; +/** + * Public interface of the Executor + */ +export interface SimpleGitExecutor { + env: GitExecutorEnv; + outputHandler?: outputHandler; + cwd: string; + chain(): SimpleGitExecutor; + push(task: SimpleGitTask): Promise; +} +/** + * The resulting output from running the git child process + */ +export interface GitExecutorResult { + stdOut: Buffer[]; + stdErr: Buffer[]; + exitCode: number; + rejection: Maybe; +} +export interface SimpleGitPluginConfig { + abort: AbortSignal; + /** + * Name of the binary the child processes will spawn - defaults to `git`, + * supply as a tuple to enable the use of platforms that require `git` to be + * called through an alternative binary (eg: `wsl git ...`). + * Note: commands supplied in this way support a restricted set of characters + * and should not be used as a way to supply arbitrary config arguments etc. + */ + binary: string | [string] | [string, string]; + /** + * Configures the events that should be used to determine when the unederlying child process has + * been terminated. + * + * Version 2 will default to use `onClose=true, onExit=50` to mean the `close` event will be + * used to immediately treat the child process as closed and start using the data from `stdOut` + * / `stdErr`, whereas the `exit` event will wait `50ms` before treating the child process + * as closed. + * + * This will be changed in version 3 to use `onClose=true, onExit=false` so that only the + * close event is used to determine the termination of the process. + */ + completion: { + onClose?: boolean | number; + onExit?: boolean | number; + }; + /** + * Configures the content of errors thrown by the `simple-git` instance for each task + */ + errors(error: Buffer | Error | undefined, result: Omit): Buffer | Error | undefined; + /** + * Handler to be called with progress events emitted through the progress plugin + */ + progress(data: SimpleGitProgressEvent): void; + /** + * Configuration for the `timeoutPlugin` + */ + timeout: { + /** + * The number of milliseconds to wait after spawning the process / receiving + * content on the stdOut/stdErr streams before forcibly closing the git process. + */ + block: number; + /** + * Reset timeout plugin after receiving data on `stdErr` - set to `false` to ignore + * `stdErr` content when determining whether to kill the process (defaults to `true`). + */ + stdErr?: boolean; + /** + * Reset timeout plugin after receiving data on `stdOut` - set to `false` to ignore + * `stdOut` content when determining whether to kill the process (defaults to `true`). + */ + stdOut?: boolean; + }; + spawnOptions: Pick; + unsafe: { + /** + * Allows potentially unsafe values to be supplied in the `binary` configuration option and + * `git.customBinary()` method call. + */ + allowUnsafeCustomBinary?: boolean; + /** + * By default `simple-git` prevents the use of inline configuration + * options to override the protocols available for the `git` child + * process to prevent accidental security vulnerabilities when + * unsanitised user data is passed directly into operations such as + * `git.addRemote`, `git.clone` or `git.raw`. + * + * Enable this override to use the `ext::` protocol (see examples on + * [git-scm.com](https://git-scm.com/docs/git-remote-ext#_examples)). + */ + allowUnsafeProtocolOverride?: boolean; + /** + * Given the possibility of using `--upload-pack` and `--receive-pack` as + * attack vectors, the use of these in any command (or the shorthand + * `-u` option in a `clone` operation) are blocked by default. + * + * Enable this override to permit the use of these arguments. + */ + allowUnsafePack?: boolean; + }; +} +/** + * Optional configuration settings to be passed to the `simpleGit` + * builder. + */ +export interface SimpleGitOptions extends Partial { + /** + * Base directory for all tasks run through this `simple-git` instance + */ + baseDir: string; + /** + * Limit for the number of child processes that will be spawned concurrently from a `simple-git` instance + */ + maxConcurrentProcesses: number; + /** + * Per-command configuration parameters to be passed with the `-c` switch to `git` + */ + config: string[]; + /** + * Enable trimming of trailing white-space in `git.raw` + */ + trimmed: boolean; +} +export declare type Maybe = T | undefined; +export declare type MaybeArray = T | T[]; +export declare type Primitives = string | number | boolean; diff --git a/node_modules/simple-git/dist/src/lib/types/tasks.d.ts b/node_modules/simple-git/dist/src/lib/types/tasks.d.ts new file mode 100644 index 0000000..db96d18 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/types/tasks.d.ts @@ -0,0 +1,20 @@ +/// +import { GitExecutorResult, SimpleGitExecutor } from './index'; +import { EmptyTask } from '../tasks/task'; +export declare type TaskResponseFormat = Buffer | string; +export interface TaskParser { + (stdOut: INPUT, stdErr: INPUT): RESPONSE; +} +export interface EmptyTaskParser { + (executor: SimpleGitExecutor): void; +} +export interface SimpleGitTaskConfiguration { + commands: string[]; + format: FORMAT; + parser: TaskParser; + onError?: (result: GitExecutorResult, error: Error, done: (result: Buffer | Buffer[]) => void, fail: (error: string | Error) => void) => void; +} +export declare type StringTask = SimpleGitTaskConfiguration; +export declare type BufferTask = SimpleGitTaskConfiguration; +export declare type RunnableTask = StringTask | BufferTask; +export declare type SimpleGitTask = RunnableTask | EmptyTask; diff --git a/node_modules/simple-git/dist/src/lib/utils/argument-filters.d.ts b/node_modules/simple-git/dist/src/lib/utils/argument-filters.d.ts new file mode 100644 index 0000000..6be6925 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/argument-filters.d.ts @@ -0,0 +1,16 @@ +import { Options, Primitives } from '../types'; +export interface ArgumentFilterPredicate { + (input: any): input is T; +} +export declare function filterType(input: K, filter: ArgumentFilterPredicate): K extends T ? T : undefined; +export declare function filterType(input: K, filter: ArgumentFilterPredicate, def: T): T; +export declare const filterArray: ArgumentFilterPredicate>; +export declare function filterPrimitives(input: unknown, omit?: Array<'boolean' | 'string' | 'number'>): input is Primitives; +export declare const filterString: ArgumentFilterPredicate; +export declare const filterStringArray: ArgumentFilterPredicate; +export declare const filterStringOrStringArray: ArgumentFilterPredicate; +export declare function filterPlainObject(input: T | unknown): input is T; +export declare function filterFunction(input: unknown): input is Function; +export declare const filterHasLength: ArgumentFilterPredicate<{ + length: number; +}>; diff --git a/node_modules/simple-git/dist/src/lib/utils/exit-codes.d.ts b/node_modules/simple-git/dist/src/lib/utils/exit-codes.d.ts new file mode 100644 index 0000000..821c9dd --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/exit-codes.d.ts @@ -0,0 +1,10 @@ +/** + * Known process exit codes used by the task parsers to determine whether an error + * was one they can automatically handle + */ +export declare enum ExitCodes { + SUCCESS = 0, + ERROR = 1, + NOT_FOUND = -2, + UNCLEAN = 128 +} diff --git a/node_modules/simple-git/dist/src/lib/utils/git-output-streams.d.ts b/node_modules/simple-git/dist/src/lib/utils/git-output-streams.d.ts new file mode 100644 index 0000000..72db466 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/git-output-streams.d.ts @@ -0,0 +1,8 @@ +/// +import { TaskResponseFormat } from '../types'; +export declare class GitOutputStreams { + readonly stdOut: T; + readonly stdErr: T; + constructor(stdOut: T, stdErr: T); + asStrings(): GitOutputStreams; +} diff --git a/node_modules/simple-git/dist/src/lib/utils/index.d.ts b/node_modules/simple-git/dist/src/lib/utils/index.d.ts new file mode 100644 index 0000000..04cb604 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/index.d.ts @@ -0,0 +1,8 @@ +export * from './argument-filters'; +export * from './exit-codes'; +export * from './git-output-streams'; +export * from './line-parser'; +export * from './simple-git-options'; +export * from './task-options'; +export * from './task-parser'; +export * from './util'; diff --git a/node_modules/simple-git/dist/src/lib/utils/line-parser.d.ts b/node_modules/simple-git/dist/src/lib/utils/line-parser.d.ts new file mode 100644 index 0000000..27618b9 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/line-parser.d.ts @@ -0,0 +1,15 @@ +export declare class LineParser { + protected matches: string[]; + private _regExp; + constructor(regExp: RegExp | RegExp[], useMatches?: (target: T, match: string[]) => boolean | void); + parse: (line: (offset: number) => string | undefined, target: T) => boolean; + protected useMatches(target: T, match: string[]): boolean | void; + protected resetMatches(): void; + protected prepareMatches(): string[]; + protected addMatch(reg: RegExp, index: number, line?: string): boolean; + protected pushMatch(_index: number, matched: string[]): void; +} +export declare class RemoteLineParser extends LineParser { + protected addMatch(reg: RegExp, index: number, line?: string): boolean; + protected pushMatch(index: number, matched: string[]): void; +} diff --git a/node_modules/simple-git/dist/src/lib/utils/simple-git-options.d.ts b/node_modules/simple-git/dist/src/lib/utils/simple-git-options.d.ts new file mode 100644 index 0000000..552d68d --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/simple-git-options.d.ts @@ -0,0 +1,2 @@ +import { SimpleGitOptions } from '../types'; +export declare function createInstanceConfig(...options: Array | undefined>): SimpleGitOptions; diff --git a/node_modules/simple-git/dist/src/lib/utils/task-options.d.ts b/node_modules/simple-git/dist/src/lib/utils/task-options.d.ts new file mode 100644 index 0000000..23d3705 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/task-options.d.ts @@ -0,0 +1,13 @@ +import { Maybe, Options } from '../types'; +export declare function appendTaskOptions(options: Maybe, commands?: string[]): string[]; +export declare function getTrailingOptions(args: IArguments, initialPrimitive?: number, objectOnly?: boolean): string[]; +/** + * Given any number of arguments, returns the trailing options argument, ignoring a trailing function argument + * if there is one. When not found, the return value is null. + */ +export declare function trailingOptionsArgument(args: IArguments): Maybe; +/** + * Returns either the source argument when it is a `Function`, or the default + * `NOOP` function constant + */ +export declare function trailingFunctionArgument(args: unknown[] | IArguments | unknown, includeNoop?: boolean): Maybe<(...args: any[]) => unknown>; diff --git a/node_modules/simple-git/dist/src/lib/utils/task-parser.d.ts b/node_modules/simple-git/dist/src/lib/utils/task-parser.d.ts new file mode 100644 index 0000000..b1a62b8 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/task-parser.d.ts @@ -0,0 +1,5 @@ +import type { MaybeArray, TaskParser, TaskResponseFormat } from '../types'; +import { GitOutputStreams } from './git-output-streams'; +import { LineParser } from './line-parser'; +export declare function callTaskParser(parser: TaskParser, streams: GitOutputStreams): RESPONSE; +export declare function parseStringResponse(result: T, parsers: LineParser[], texts: MaybeArray, trim?: boolean): T; diff --git a/node_modules/simple-git/dist/src/lib/utils/util.d.ts b/node_modules/simple-git/dist/src/lib/utils/util.d.ts new file mode 100644 index 0000000..d45e761 --- /dev/null +++ b/node_modules/simple-git/dist/src/lib/utils/util.d.ts @@ -0,0 +1,46 @@ +/// +import { Maybe } from '../types'; +export declare const NULL = "\0"; +export declare const NOOP: (...args: any[]) => void; +/** + * Returns either the source argument when it is a `Function`, or the default + * `NOOP` function constant + */ +export declare function asFunction any>(source: T | any): T; +/** + * Determines whether the supplied argument is both a function, and is not + * the `NOOP` function. + */ +export declare function isUserFunction(source: T | any): source is T; +export declare function splitOn(input: string, char: string): [string, string]; +export declare function first(input: T, offset?: number): Maybe; +export declare function first(input: T, offset?: number): Maybe; +export declare function last(input: T, offset?: number): Maybe; +export declare function last(input: T, offset?: number): Maybe; +export declare function last(input: T, offset?: number): Maybe; +export declare function toLinesWithContent(input?: string, trimmed?: boolean, separator?: string): string[]; +declare type LineWithContentCallback = (line: string) => T; +export declare function forEachLineWithContent(input: string, callback: LineWithContentCallback): T[]; +export declare function folderExists(path: string): boolean; +/** + * Adds `item` into the `target` `Array` or `Set` when it is not already present and returns the `item`. + */ +export declare function append(target: T[] | Set, item: T): typeof item; +/** + * Adds `item` into the `target` `Array` when it is not already present and returns the `target`. + */ +export declare function including(target: T[], item: T): typeof target; +export declare function remove(target: Set | T[], item: T): T; +export declare const objectToString: (input: any) => string; +export declare function asArray(source: T | T[]): T[]; +export declare function asStringArray(source: T | T[]): string[]; +export declare function asNumber(source: string | null | undefined, onNaN?: number): number; +export declare function prefixedArray(input: T[], prefix: T): T[]; +export declare function bufferToString(input: Buffer | Buffer[]): string; +/** + * Get a new object from a source object with only the listed properties. + */ +export declare function pick(source: Record, properties: string[]): any; +export declare function delay(duration?: number): Promise; +export declare function orVoid(input: T | false): T | undefined; +export {}; diff --git a/node_modules/simple-git/dist/typings/errors.d.ts b/node_modules/simple-git/dist/typings/errors.d.ts new file mode 100644 index 0000000..36bc705 --- /dev/null +++ b/node_modules/simple-git/dist/typings/errors.d.ts @@ -0,0 +1,5 @@ +export * from '../src/lib/errors/git-error'; +export * from '../src/lib/errors/git-construct-error'; +export * from '../src/lib/errors/git-plugin-error'; +export * from '../src/lib/errors/git-response-error'; +export * from '../src/lib/errors/task-configuration-error'; diff --git a/node_modules/simple-git/dist/typings/index.d.ts b/node_modules/simple-git/dist/typings/index.d.ts new file mode 100644 index 0000000..12449c3 --- /dev/null +++ b/node_modules/simple-git/dist/typings/index.d.ts @@ -0,0 +1,12 @@ +import { SimpleGitFactory } from './simple-git'; + +export * from './simple-git'; +export * from './errors'; +export * from './response'; +export * from './types'; + +export declare const gitP: SimpleGitFactory; + +export declare const simpleGit: SimpleGitFactory; + +export default simpleGit; diff --git a/node_modules/simple-git/dist/typings/response.d.ts b/node_modules/simple-git/dist/typings/response.d.ts new file mode 100644 index 0000000..04f825e --- /dev/null +++ b/node_modules/simple-git/dist/typings/response.d.ts @@ -0,0 +1,555 @@ +import type { DiffNameStatus } from '../src/lib/tasks/diff-name-status'; +import type { DefaultLogFields } from '../src/lib/tasks/log'; + +export interface BranchSummaryBranch { + current: boolean; + name: string; + commit: string; + label: string; + linkedWorkTree: boolean; +} + +export interface BranchSummary { + detached: boolean; + current: string; + all: string[]; + branches: { + [key: string]: BranchSummaryBranch; + }; +} + +/** + * Represents the successful deletion of a single branch + */ +export interface BranchSingleDeleteSuccess { + branch: string; + hash: string; + success: true; +} + +/** + * Represents the failure to delete a single branch + */ +export interface BranchSingleDeleteFailure { + branch: string; + hash: null; + success: false; +} + +export type BranchSingleDeleteResult = BranchSingleDeleteFailure | BranchSingleDeleteSuccess; + +/** + * Represents the status of having deleted a batch of branches + */ +export interface BranchMultiDeleteResult { + /** + * All branches included in the response + */ + all: BranchSingleDeleteResult[]; + + /** + * Branches mapped by their branch name + */ + branches: { [branchName: string]: BranchSingleDeleteResult }; + + /** + * Array of responses that are in error + */ + errors: BranchSingleDeleteResult[]; + + /** + * Flag showing whether all branches were deleted successfully + */ + readonly success: boolean; +} + +export interface CleanSummary { + readonly dryRun: boolean; + paths: string[]; + files: string[]; + folders: string[]; +} + +export interface CommitResult { + author: null | { + email: string; + name: string; + }; + branch: string; + commit: string; + root: boolean; + summary: { + changes: number; + insertions: number; + deletions: number; + }; +} + +/** Represents the response to using `git.getConfig` */ +export interface ConfigGetResult { + /** The key that was searched for */ + key: string; + + /** The single value seen by `git` for this key (equivalent to `git config --get key`) */ + value: string | null; + + /** All possible values for this key no matter the scope (equivalent to `git config --get-all key`) */ + values: string[]; + + /** The file paths from which configuration was read */ + paths: string[]; + + /** + * The full hierarchy of values the property can have had across the + * various scopes that were searched (keys in this Map are the strings + * also found in the `paths` array). + */ + scopes: Map; +} + +/** + * Represents the current git configuration, as defined by the output from `git log` + */ +export interface ConfigListSummary { + /** + * All configuration settings, where local/user settings override user/global settings + * the overridden value will appear in this object. + */ + readonly all: ConfigValues; + + /** + * The file paths configuration was read from + */ + files: string[]; + + /** + * The `ConfigValues` for each of the `files`, use this object to determine + * local repo, user and global settings. + */ + values: { [fileName: string]: ConfigValues }; +} + +/** + * Represents the map of configuration settings + */ +export interface ConfigValues { + [key: string]: string | string[]; +} + +export interface DiffResultTextFile { + file: string; + changes: number; + insertions: number; + deletions: number; + binary: false; + + /** `--name-status` argument needed */ + status?: DiffNameStatus; +} + +export interface DiffResultBinaryFile { + file: string; + before: number; + after: number; + binary: true; + + /** `--name-status` argument needed */ + status?: string; +} + +export interface DiffResult { + /** The total number of files changed as reported in the summary line */ + changed: number; + + /** When present in the diff, lists the details of each file changed */ + files: Array; + + /** The number of files changed with insertions */ + insertions: number; + + /** The number of files changed with deletions */ + deletions: number; +} + +export interface FetchResult { + raw: string; + remote: string | null; + branches: { + name: string; + tracking: string; + }[]; + tags: { + name: string; + tracking: string; + }[]; + updated: { + name: string; + tracking: string; + to: string; + from: string; + }[]; + deleted: { + tracking: string; + }[]; +} + +/** Represents the response to git.grep */ +export interface GrepResult { + paths: Set; + results: Record< + string, + Array<{ + line: number; + path: string; + preview: string; + }> + >; +} + +/** + * The `InitResult` is returned when (re)initialising a git repo. + */ +export interface InitResult { + /** + * Boolean representing whether the `--bare` option was used + */ + readonly bare: boolean; + + /** + * Boolean representing whether the repo already existed (re-initialised rather than initialised) + */ + readonly existing: boolean; + + /** + * The path used when initialising + */ + readonly path: string; + + /** + * The git configuration directory - for a bare repo this is the same as `path`, in non-bare repos + * this will usually be a sub-directory with the name `.git` (or value of the `$GIT_DIR` environment + * variable). + */ + readonly gitDir: string; +} + +/** + * A parsed response summary for calls to `git mv` + */ +export interface MoveResult { + /** + * Array of files moved + */ + moves: Array<{ from: string; to: string }>; +} + +export interface PullDetailFileChanges { + [fileName: string]: number; +} + +export interface PullDetailSummary { + changes: number; + insertions: number; + deletions: number; +} + +export interface PullDetail { + /** Array of all files that are referenced in the pull */ + files: string[]; + + /** Map of file names to the number of insertions in that file */ + insertions: PullDetailFileChanges; + + /** Map of file names to the number of deletions in that file */ + deletions: PullDetailFileChanges; + + summary: PullDetailSummary; + + /** Array of file names that have been created */ + created: string[]; + + /** Array of file names that have been deleted */ + deleted: string[]; +} + +export interface PullResult extends PullDetail, RemoteMessageResult {} + +/** + * Wrapped with the `GitResponseError` as the exception thrown from a `git.pull` task + * to provide additional detail as to what failed. + */ +export interface PullFailedResult { + remote: string; + hash: { + local: string; + remote: string; + }; + branch: { + local: string; + remote: string; + }; + message: string; +} + +/** + * Represents file name changes in a StatusResult + */ +export interface StatusResultRenamed { + from: string; + to: string; +} + +export interface FileStatusResult { + /** Original location of the file, when the file has been moved */ + from?: string; + + /** Path of the file */ + path: string; + + /** First digit of the status code of the file, e.g. 'M' = modified. + Represents the status of the index if no merge conflicts, otherwise represents + status of one side of the merge. */ + index: string; + + /** Second digit of the status code of the file. Represents status of the working directory + if no merge conflicts, otherwise represents status of other side of a merge. + See https://git-scm.com/docs/git-status#_short_format for full documentation of possible + values and their meanings. */ + working_dir: string; +} + +/** + * The StatusResult is returned for calls to `git.status()`, represents the state of the + * working directory. + */ +export interface StatusResult { + not_added: string[]; + conflicted: string[]; + created: string[]; + deleted: string[]; + + /** + * Ignored files are not listed by default, add `--ignored` to the task options in order to see + * this array of ignored files/paths. + * + * Note: ignored files will not be added to the `files` array, and will not be included in the + * `isClean()` calculation. + */ + ignored?: string[]; + modified: string[]; + renamed: StatusResultRenamed[]; + staged: string[]; + + /** + * All files represented as an array of objects containing the `path` and status in `index` and + * in the `working_dir`. + */ + files: FileStatusResult[]; + + /** + * Number of commits ahead of the tracked branch + */ + ahead: number; + + /** + *Number of commits behind the tracked branch + */ + behind: number; + + /** + * Name of the current branch + */ + current: string | null; + + /** + * Name of the branch being tracked + */ + tracking: string | null; + + /** + * Detached status of the working copy, for more detail of what the working branch + * is detached from use `git.branch()` + */ + detached: boolean; + + /** + * Gets whether this represents a clean working branch. + */ + isClean(): boolean; +} + +/** + * Response retrieved when using the `git.tags` method + */ +export interface TagResult { + /** + * All tag names + */ + all: string[]; + + /** + * The semver latest tag name or `undefined` when no tags are named in the response + */ + latest: string | undefined; +} + +/** + * The ListLogLine represents a single entry in the `git.log`, the properties on the object + * are mixed in depending on the names used in the format (see `DefaultLogFields`), but some + * properties are dependent on the command used. + */ +export interface ListLogLine { + /** + * When using a `--stat=4096` or `--shortstat` options in the `git.log` or `git.stashList`, + * each entry in the `ListLogSummary` will also have a `diff` property representing as much + * detail as was given in the response. + */ + diff?: DiffResult; +} + +export interface LogResult { + all: ReadonlyArray; + total: number; + latest: (T & ListLogLine) | null; +} + +/** + * Where the file was deleted, if there is a modify/delete conflict + */ +export interface MergeConflictDeletion { + deleteRef: string; +} + +/** + * Represents a single file with conflicts in the MergeSummary + */ +export interface MergeConflict { + /** + * Type of conflict + */ + reason: string; + + /** + * Path to file + */ + file: string | null; + + /** + * Additional detail for the specific type of conflict + */ + meta?: MergeConflictDeletion; +} + +export type MergeResultStatus = 'success' | string; + +export interface MergeDetail { + conflicts: MergeConflict[]; + merges: string[]; + result: MergeResultStatus; + readonly failed: boolean; +} + +export type MergeResult = PullResult & MergeDetail; + +/** + * + */ +export interface PushResultPushedItem { + local: string; + remote: string; + + readonly deleted: boolean; + readonly tag: boolean; + readonly branch: boolean; + readonly new: boolean; + readonly alreadyUpdated: boolean; +} + +export interface RemoteMessagesObjectEnumeration { + enumerating: number; + counting: number; + compressing: number; + total: { + count: number; + delta: number; + }; + reused: { + count: number; + delta: number; + }; + packReused: number; +} + +export interface RemoteMessages { + all: string[]; + objects?: RemoteMessagesObjectEnumeration; +} + +export interface PushResultRemoteMessages extends RemoteMessages { + pullRequestUrl?: string; + vulnerabilities?: { + count: number; + summary: string; + url: string; + }; +} + +export interface RemoteMessageResult { + remoteMessages: T; +} + +export interface PushResultBranchUpdate { + head: { + local: string; + remote: string; + }; + hash: { + from: string; + to: string; + }; +} + +export interface PushDetail { + repo?: string; + ref?: { + local: string; + }; + pushed: PushResultPushedItem[]; + branch?: { + local: string; + remote: string; + remoteName: string; + }; + update?: PushResultBranchUpdate; +} + +export interface PushResult extends PushDetail, RemoteMessageResult {} + +/** + * @deprecated + * For consistent naming, please use `CommitResult` instead of `CommitSummary` + */ +export type CommitSummary = CommitResult; + +/** + * @deprecated + * For consistent naming, please use `MergeResult` instead of `MergeSummary` + */ +export type MergeSummary = MergeResult; + +/** + * @deprecated to aid consistent naming, please use `BranchSingleDeleteResult` instead of `BranchDeletionSummary`. + */ +export type BranchDeletionSummary = BranchSingleDeleteResult; + +/** + * @deprecated to aid consistent naming, please use `BranchMultiDeleteResult` instead of `BranchDeletionBatchSummary`. + */ +export type BranchDeletionBatchSummary = BranchMultiDeleteResult; + +export type MoveSummary = MoveResult; + +/** + * @deprecated to aid consistent naming, please use `LogResult` instead of `ListLogSummary`. + */ +export type ListLogSummary = LogResult; diff --git a/node_modules/simple-git/dist/typings/simple-git.d.ts b/node_modules/simple-git/dist/typings/simple-git.d.ts new file mode 100644 index 0000000..2eeae35 --- /dev/null +++ b/node_modules/simple-git/dist/typings/simple-git.d.ts @@ -0,0 +1,1025 @@ +import * as resp from './response'; +import * as types from './types'; +import { GitError } from './errors'; + +export interface SimpleGitFactory { + (baseDir?: string, options?: Partial): SimpleGit; + + (baseDir: string): SimpleGit; + + (options: Partial): SimpleGit; +} + +export type Response = SimpleGit & Promise; + +export interface SimpleGitBase { + /** + * Adds one or more files to source control + */ + add(files: string | string[], callback?: types.SimpleGitTaskCallback): Response; + + /** + * Sets the working directory of the subsequent commands. + */ + cwd( + directory: { path: string; root?: boolean }, + callback?: types.SimpleGitTaskCallback + ): Response; + + cwd( + directory: path, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Compute object ID from a file + */ + hashObject(path: string, callback?: types.SimpleGitTaskCallback): Response; + + hashObject( + path: string, + write?: boolean, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Initialize a git repo + */ + init( + bare: boolean, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + init( + bare: boolean, + callback?: types.SimpleGitTaskCallback + ): Response; + + init( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + init(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Runs a merge, `options` can be either an array of arguments + * supported by the [`git merge`](https://git-scm.com/docs/git-merge) + * or an options object. + * + * Conflicts during the merge result in an error response, + * the response type whether it was an error or success will be a MergeSummary instance. + * When successful, the MergeSummary has all detail from a the PullSummary + * + * @see https://github.com/steveukx/git-js/blob/master/src/responses/MergeSummary.js + * @see https://github.com/steveukx/git-js/blob/master/src/responses/PullSummary.js + */ + merge( + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Merges from one branch to another, equivalent to running `git merge ${remote} ${branch}`, the `options` argument can + * either be an array of additional parameters to pass to the command or null / omitted to be ignored. + */ + mergeFromTo( + remote: string, + branch: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + mergeFromTo( + remote: string, + branch: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Sets a handler function to be called whenever a new child process is created, the handler function will be called + * with the name of the command being run and the stdout & stderr streams used by the ChildProcess. + * + * @example + * require('simple-git') + * .outputHandler(function (command, stdout, stderr) { + * stdout.pipe(process.stdout); + * }) + * .checkout('https://github.com/user/repo.git'); + * + * @see https://nodejs.org/api/child_process.html#child_process_class_childprocess + * @see https://nodejs.org/api/stream.html#stream_class_stream_readable + */ + outputHandler(handler: types.outputHandler | void): this; + + /** + * Pushes the current committed changes to a remote, optionally specify the names of the remote and branch to use + * when pushing. Supply multiple options as an array of strings in the first argument - see examples below. + */ + push( + remote?: string, + branch?: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + push( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + push(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Stash the local repo + */ + stash( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + stash(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Show the working tree status. + */ + status( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + status(callback?: types.SimpleGitTaskCallback): Response; +} + +export interface SimpleGit extends SimpleGitBase { + /** + * Add an annotated tag to the head of the current branch + */ + addAnnotatedTag( + tagName: string, + tagMessage: string, + callback?: types.SimpleGitTaskCallback<{ name: string }> + ): Response<{ name: string }>; + + /** + * Add config to local git instance for the specified `key` (eg: user.name) and value (eg: 'your name'). + * Set `append` to true to append to rather than overwrite the key + */ + addConfig( + key: string, + value: string, + append?: boolean, + scope?: keyof typeof types.GitConfigScope, + callback?: types.SimpleGitTaskCallback + ): Response; + + addConfig( + key: string, + value: string, + append?: boolean, + callback?: types.SimpleGitTaskCallback + ): Response; + + addConfig( + key: string, + value: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Applies a patch to the repo + */ + applyPatch( + patches: string | string[], + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + applyPatch( + patches: string | string[], + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Configuration values visible to git in the current working directory + */ + listConfig( + scope: keyof typeof types.GitConfigScope, + callback?: types.SimpleGitTaskCallback + ): Response; + + listConfig( + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Adds a remote to the list of remotes. + * + * - `remoteName` Name of the repository - eg "upstream" + * - `remoteRepo` Fully qualified SSH or HTTP(S) path to the remote repo + * - `options` Optional additional settings permitted by the `git remote add` command, merged into the command prior to the repo name and remote url + */ + addRemote( + remoteName: string, + remoteRepo: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + addRemote( + remoteName: string, + remoteRepo: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Add a lightweight tag to the head of the current branch + */ + addTag( + name: string, + callback?: types.SimpleGitTaskCallback<{ name: string }> + ): Response<{ name: string }>; + + /** + * Equivalent to `catFile` but will return the native `Buffer` of content from the git command's stdout. + */ + binaryCatFile(options: string[], callback?: types.SimpleGitTaskCallback): Response; + + /** + * List all branches + */ + branch( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * List of local branches + */ + branchLocal( + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Returns a list of objects in a tree based on commit hash. + * Passing in an object hash returns the object's content, size, and type. + * + * Passing "-p" will instruct cat-file to determine the object type, and display its formatted contents. + * + * @see https://git-scm.com/docs/git-cat-file + */ + catFile(options: string[], callback?: types.SimpleGitTaskCallback): Response; + + catFile(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Check if a pathname or pathnames are excluded by .gitignore + * + */ + checkIgnore( + pathNames: string[], + callback?: types.SimpleGitTaskCallback + ): Response; + + checkIgnore(path: string, callback?: types.SimpleGitTaskCallback): Response; + + /** + * Validates that the current working directory is a valid git repo file path. + * + * To make a more specific assertion of the repo, add the `action` argument: + * + * - `bare` to validate that the working directory is inside a bare repo. + * - `root` to validate that the working directory is the root of a repo. + * - `tree` (default value when omitted) to simply validate that the working + * directory is the descendent of a repo + */ + checkIsRepo( + action?: types.CheckRepoActions, + callback?: types.SimpleGitTaskCallback + ): Response; + + checkIsRepo(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Checkout a tag or revision, any number of additional arguments can be passed to the `git checkout` command + * by supplying either a string or array of strings as the `what` parameter. + */ + checkout( + what: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + checkout(what: string, callback?: types.SimpleGitTaskCallback): Response; + + checkout( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Checkout a remote branch - equivalent to `git checkout -b ${branchName} ${startPoint}` + * + * - branchName name of branch. + * - startPoint (e.g origin/development). + */ + checkoutBranch( + branchName: string, + startPoint: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + checkoutBranch( + branchName: string, + startPoint: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Internally uses pull and tags to get the list of tags then checks out the latest tag. + */ + checkoutLatestTag( + branchName: string, + startPoint: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Checkout a local branch - equivalent to `git checkout -b ${branchName}` + */ + checkoutLocalBranch( + branchName: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + checkoutLocalBranch( + branchName: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Deletes unwanted content from the local repo - when supplying the first argument as + * an array of `CleanOptions`, the array must include one of `CleanOptions.FORCE` or + * `CleanOptions.DRY_RUN`. + * + * eg: + * + * ```typescript + await git.clean(CleanOptions.FORCE); + await git.clean(CleanOptions.DRY_RUN + CleanOptions.RECURSIVE); + await git.clean(CleanOptions.FORCE, ['./path']); + await git.clean(CleanOptions.IGNORED + CleanOptions.FORCE, {'./path': null}); + * ``` + */ + clean( + args: types.CleanOptions[], + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + clean( + mode: types.CleanMode | string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + clean( + mode: types.CleanMode | string, + callback?: types.SimpleGitTaskCallback + ): Response; + + clean(options?: types.TaskOptions): Response; + + clean(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Clears the queue of pending commands and returns the wrapper instance for chaining. + */ + clearQueue(): this; + + /** + * Clone a repository into a new directory. + * + * - repoPath repository url to clone e.g. https://github.com/steveukx/git-js.git + * - localPath local folder path to clone to. + * - options supported by [git](https://git-scm.com/docs/git-clone). + */ + clone( + repoPath: string, + localPath: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + clone( + repoPath: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Commits changes in the current working directory - when specific file paths are supplied, only changes on those + * files will be committed. + */ + commit( + message: string | string[], + files?: string | string[], + options?: types.Options, + callback?: types.SimpleGitTaskCallback + ): Response; + + commit( + message: string | string[], + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + commit( + message: string | string[], + files?: string | string[], + callback?: types.SimpleGitTaskCallback + ): Response; + + commit( + message: string | string[], + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Sets the path to a custom git binary, should either be `git` when there is an installation of git available on + * the system path, or a fully qualified path to the executable. + */ + customBinary(command: Exclude): this; + + /** + * Delete one local branch. Supply the branchName as a string to return a + * single `BranchDeletionSummary` instances. + * + * - branchName name of branch + * - forceDelete (optional, defaults to false) set to true to forcibly delete unmerged branches + */ + deleteLocalBranch( + branchName: string, + forceDelete?: boolean, + callback?: types.SimpleGitTaskCallback + ): Response; + + deleteLocalBranch( + branchName: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Delete one or more local branches. Supply the branchName as a string to return a + * single `BranchDeletionSummary` or as an array of branch names to return an array of + * `BranchDeletionSummary` instances. + * + * - branchNames name of branch or array of branch names + * - forceDelete (optional, defaults to false) set to true to forcibly delete unmerged branches + */ + deleteLocalBranches( + branchNames: string[], + forceDelete?: boolean, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Get the diff of the current repo compared to the last commit with a set of options supplied as a string. + */ + diff( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Gets a summary of the diff for files in the repo, uses the `git diff --stat` format to calculate changes. + * + * in order to get staged (only): `--cached` or `--staged`. + */ + diffSummary( + command: string | number, + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + diffSummary( + command: string | number, + callback?: types.SimpleGitTaskCallback + ): Response; + + diffSummary( + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + diffSummary(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Sets an environment variable for the spawned child process, either supply both a name and value as strings or + * a single object to entirely replace the current environment variables. + * + * @param {string|Object} name + * @param {string} [value] + */ + env(name: string, value: string): this; + + env(env: object): this; + + /** + * Calls the supplied `handle` function at the next step in the chain, used to run arbitrary functions synchronously + * before the next task in the git API. + */ + exec(handle: () => void): Response; + + /** + * Updates the local working copy database with changes from the default remote repo and branch. + */ + fetch( + remote: string, + branch: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + fetch( + remote: string, + branch: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + fetch( + remote: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + fetch( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + fetch(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Gets the commit hash of the first commit in the repo + */ + firstCommit(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Gets the current value of a configuration property by it key, optionally specify the scope in which + * to run the command (omit / set to `undefined` to check in the complete overlaid configuration visible + * to the `git` process). + */ + getConfig( + key: string, + scope?: keyof typeof types.GitConfigScope, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Gets the currently available remotes, setting the optional verbose argument to true includes additional + * detail on the remotes themselves. + */ + getRemotes( + callback?: types.SimpleGitTaskCallback + ): Response; + + getRemotes( + verbose?: false, + callback?: types.SimpleGitTaskCallback + ): Response; + + getRemotes( + verbose: true, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Search for files matching the supplied search terms + */ + grep( + searchTerm: string | types.GitGrepQuery, + callback?: types.SimpleGitTaskCallback + ): Response; + + grep( + searchTerm: string | types.GitGrepQuery, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * List remotes by running the `ls-remote` command with any number of arbitrary options + * in either array of object form. + */ + listRemote( + args?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Show commit logs from `HEAD` to the first commit. + * If provided between `options.from` and `options.to` tags or branch. + * + * You can provide `options.file`, which is the path to a file in your repository. Then only this file will be considered. + * + * To use a custom splitter in the log format, set `options.splitter` to be the string the log should be split on. + * + * By default the following fields will be part of the result: + * `hash`: full commit hash + * `date`: author date, ISO 8601-like format + * `message`: subject + ref names, like the --decorate option of git-log + * `author_name`: author name + * `author_email`: author mail + * You can specify `options.format` to be an mapping from key to a format option like `%H` (for commit hash). + * The fields specified in `options.format` will be the fields in the result. + * + * Options can also be supplied as a standard options object for adding custom properties supported by the git log command. + * For any other set of options, supply options as an array of strings to be appended to the git log command. + * + * @returns Response + * + * @see https://git-scm.com/docs/git-log + */ + log( + options?: types.TaskOptions | types.LogOptions, + callback?: types.SimpleGitTaskCallback> + ): Response>; + + /** + * Mirror a git repo + * + * Equivalent to `git.clone(repoPath, localPath, ['--mirror'])`, `clone` allows + * for additional task options. + */ + mirror( + repoPath: string, + localPath: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Moves one or more files to a new destination. + * + * @see https://git-scm.com/docs/git-mv + */ + mv( + from: string | string[], + to: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Fetch from and integrate with another repository or a local branch. In the case that the `git pull` fails with a + * recognised fatal error, the exception thrown by this function will be a `GitResponseError`. + */ + pull( + remote?: string, + branch?: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + pull( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + pull(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Pushes the current tag changes to a remote which can be either a URL or named remote. When not specified uses the + * default configured remote spec. + */ + pushTags( + remote: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + pushTags( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + pushTags(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Executes any command against the git binary. + */ + raw( + commands: string | string[] | types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + raw( + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + raw(...commands: string[]): Response; + + // leading varargs with trailing options/callback + raw( + a: string, + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + raw( + a: string, + b: string, + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + raw( + a: string, + b: string, + c: string, + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + raw( + a: string, + b: string, + c: string, + d: string, + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + raw( + a: string, + b: string, + c: string, + d: string, + e: string, + options: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + // leading varargs with trailing callback + raw(a: string, callback?: types.SimpleGitTaskCallback): Response; + + raw(a: string, b: string, callback?: types.SimpleGitTaskCallback): Response; + + raw( + a: string, + b: string, + c: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + raw( + a: string, + b: string, + c: string, + d: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + raw( + a: string, + b: string, + c: string, + d: string, + e: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Rebases the current working copy. Options can be supplied either as an array of string parameters + * to be sent to the `git rebase` command, or a standard options object. + */ + rebase( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + rebase(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Call any `git remote` function with arguments passed as an array of strings. + */ + remote( + options: string[], + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Removes an entry from the list of remotes. + * + * - remoteName Name of the repository - eg "upstream" + */ + removeRemote(remoteName: string, callback?: types.SimpleGitTaskCallback): Response; + + /** + * Reset a repo. Called without arguments this is a soft reset for the whole repo, + * for explicitly setting the reset mode, supply the first argument as one of the + * supported reset modes. + * + * Trailing options argument can be either a string array, or an extension of the + * ResetOptions, use this argument for supplying arbitrary additional arguments, + * such as restricting the pathspec. + * + * ```typescript + // equivalent to each other + simpleGit().reset(ResetMode.HARD, ['--', 'my-file.txt']); + simpleGit().reset(['--hard', '--', 'my-file.txt']); + simpleGit().reset(ResetMode.HARD, {'--': null, 'my-file.txt': null}); + simpleGit().reset({'--hard': null, '--': null, 'my-file.txt': null}); + ``` + */ + reset( + mode: types.ResetMode, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + reset(mode: types.ResetMode, callback?: types.SimpleGitTaskCallback): Response; + + reset( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Revert one or more commits in the local working copy + * + * - commit The commit to revert. Can be any hash, offset (eg: `HEAD~2`) or range (eg: `master~5..master~2`) + */ + revert( + commit: String, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + revert(commit: String, callback?: types.SimpleGitTaskCallback): Response; + + /** + * Passes the supplied options to `git rev-parse` and returns the string response. Options can be either a + * string array or `Options` object of options compatible with the [rev-parse](https://git-scm.com/docs/git-rev-parse) + * + * Example uses of `rev-parse` include converting friendly commit references (ie: branch names) to SHA1 hashes + * and retrieving meta details about the current repo (eg: the root directory, and whether it was created as + * a bare repo). + */ + revparse( + option: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + revparse( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Removes the named files from source control. + */ + rm(paths: string | string[], callback?: types.SimpleGitTaskCallback): Response; + + /** + * Removes the named files from source control but keeps them on disk rather than deleting them entirely. To + * completely remove the files, use `rm`. + */ + rmKeepLocal( + paths: string | string[], + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Show various types of objects, for example the file at a certain commit + */ + show( + option: string | types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + show(callback?: types.SimpleGitTaskCallback): Response; + + showBuffer(option: string | types.TaskOptions): Response; + + /** + * @deprecated + * + * From version 2.7.0, use of `silent` is deprecated in favour of using the `debug` library, this method will + * be removed in version 3.x. + * + * Please see the [readme](https://github.com/steveukx/git-js/blob/master/readme.md#enable-logging) for more details. + * + * Disables/enables the use of the console for printing warnings and errors, by default messages are not shown in + * a production environment. + * + * @param {boolean} silence + */ + silent(silence?: boolean): this; + + /** + * List the stash(s) of the local repo + */ + stashList( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + stashList(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Call any `git submodule` function with arguments passed as an array of strings. + */ + subModule( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Add a submodule + */ + submoduleAdd( + repo: string, + path: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Initialise submodules + */ + submoduleInit( + moduleName: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + submoduleInit( + moduleName: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + submoduleInit( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + submoduleInit(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Update submodules + */ + submoduleUpdate( + moduleName: string, + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + submoduleUpdate( + moduleName: string, + callback?: types.SimpleGitTaskCallback + ): Response; + + submoduleUpdate( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + submoduleUpdate(callback?: types.SimpleGitTaskCallback): Response; + + /** + * List all tags. When using git 2.7.0 or above, include an options object with `"--sort": "property-name"` to + * sort the tags by that property instead of using the default semantic versioning sort. + * + * Note, supplying this option when it is not supported by your Git version will cause the operation to fail. + */ + tag( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + /** + * Gets a list of tagged versions. + */ + tags( + options?: types.TaskOptions, + callback?: types.SimpleGitTaskCallback + ): Response; + + tags(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Updates repository server info + */ + updateServerInfo(callback?: types.SimpleGitTaskCallback): Response; + + /** + * Retrieves `git` version information, including whether `git` is installed on the `PATH` + */ + version( + callback?: types.SimpleGitTaskCallback + ): Response; +} diff --git a/node_modules/simple-git/dist/typings/types.d.ts b/node_modules/simple-git/dist/typings/types.d.ts new file mode 100644 index 0000000..8e5457d --- /dev/null +++ b/node_modules/simple-git/dist/typings/types.d.ts @@ -0,0 +1,22 @@ +export type { RemoteWithoutRefs, RemoteWithRefs } from '../src/lib/responses/GetRemoteSummary'; +export type { LogOptions, DefaultLogFields } from '../src/lib/tasks/log'; + +export type { + outputHandler, + Options, + TaskOptions, + SimpleGitOptions, + SimpleGitProgressEvent, + SimpleGitTaskCallback, +} from '../src/lib/types'; + +export { pathspec } from '../src/lib/args/pathspec'; +export type { ApplyOptions } from '../src/lib/tasks/apply-patch'; +export { CheckRepoActions } from '../src/lib/tasks/check-is-repo'; +export { CleanOptions, CleanMode } from '../src/lib/tasks/clean'; +export type { CloneOptions } from '../src/lib/tasks/clone'; +export { GitConfigScope } from '../src/lib/tasks/config'; +export { DiffNameStatus } from '../src/lib/tasks/diff-name-status'; +export { GitGrepQuery, grepQueryBuilder } from '../src/lib/tasks/grep'; +export { ResetOptions, ResetMode } from '../src/lib/tasks/reset'; +export type { VersionResult } from '../src/lib/tasks/version'; diff --git a/node_modules/simple-git/package.json b/node_modules/simple-git/package.json new file mode 100644 index 0000000..50c5dad --- /dev/null +++ b/node_modules/simple-git/package.json @@ -0,0 +1,61 @@ +{ + "name": "simple-git", + "description": "Simple GIT interface for node.js", + "version": "3.24.0", + "author": "Steve King ", + "contributors": [ + { + "name": "Steve King", + "email": "steve@mydev.co" + } + ], + "funding": { + "type": "github", + "url": "https://github.com/steveukx/git-js?sponsor=1" + }, + "dependencies": { + "@kwsites/file-exists": "^1.1.1", + "@kwsites/promise-deferred": "^1.1.1", + "debug": "^4.3.4" + }, + "devDependencies": { + "@kwsites/promise-result": "^1.1.0", + "@simple-git/babel-config": "^1.0.0", + "@types/debug": "^4.1.5", + "@types/jest": "^29.2.2", + "@types/node": "^16", + "esbuild": "^0.14.10", + "esbuild-node-externals": "^1.4.1", + "jest": "^29.3.1", + "ts-node": "^9.0.0", + "typescript": "^4.1.2" + }, + "keywords": [ + "git", + "source control", + "vcs" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/steveukx/git-js.git", + "directory": "simple-git" + }, + "main": "dist/cjs/index.js", + "module": "dist/esm/index.js", + "exports": { + ".": { + "types": "./dist/typings/index.d.ts", + "import": "./dist/esm/index.js", + "require": "./dist/cjs/index.js" + }, + "./promise": { + "require": "./promise.js" + } + }, + "types": "./dist/typings/index.d.ts", + "files": [ + "promise.*", + "dist" + ] +} \ No newline at end of file diff --git a/node_modules/simple-git/promise.js b/node_modules/simple-git/promise.js new file mode 100644 index 0000000..9f584b9 --- /dev/null +++ b/node_modules/simple-git/promise.js @@ -0,0 +1,17 @@ +console.error(`============================================= +simple-git has supported promises / async await since version 2.6.0. + Importing from 'simple-git/promise' has been deprecated and will + report this error until the next major release of version 4. + +To upgrade, change all 'simple-git/promise' imports to just 'simple-git' +=============================================`); + +const simpleGit = require('.'); + +module.exports = Object.assign( + function () { + return simpleGit.gitP.apply(null, arguments); + }, + simpleGit, + { default: simpleGit.gitP } +); diff --git a/node_modules/simple-git/readme.md b/node_modules/simple-git/readme.md new file mode 100644 index 0000000..6f338a8 --- /dev/null +++ b/node_modules/simple-git/readme.md @@ -0,0 +1,838 @@ +# Simple Git + +[![NPM version](https://img.shields.io/npm/v/simple-git.svg)](https://www.npmjs.com/package/simple-git) + +A lightweight interface for running `git` commands in any [node.js](https://nodejs.org) application. + +# Installation + +Use your favourite package manager: + +- [npm](https://npmjs.org): `npm install simple-git` +- [yarn](https://yarnpkg.com/): `yarn add simple-git` + +# System Dependencies + +Requires [git](https://git-scm.com/downloads) to be installed and that it can be called using the command `git`. + +# Usage + +Include into your JavaScript app using common js: + +```javascript +// require the library, main export is a function +const simpleGit = require('simple-git'); +simpleGit().clean(simpleGit.CleanOptions.FORCE); + +// or use named properties +const { simpleGit, CleanOptions } = require('simple-git'); +simpleGit().clean(CleanOptions.FORCE); +``` + +Include into your JavaScript app as an ES Module: + +```javascript +import { simpleGit, CleanOptions } from 'simple-git'; + +simpleGit().clean(CleanOptions.FORCE); +``` + +Include in a TypeScript app using the bundled type definitions: + +```typescript +import { simpleGit, SimpleGit, CleanOptions } from 'simple-git'; + +const git: SimpleGit = simpleGit().clean(CleanOptions.FORCE); +``` + +## Configuration + +Configure each `simple-git` instance with a properties object passed to the main `simpleGit` function: + +```typescript +import { simpleGit, SimpleGit, SimpleGitOptions } from 'simple-git'; + +const options: Partial = { + baseDir: process.cwd(), + binary: 'git', + maxConcurrentProcesses: 6, + trimmed: false, +}; + +// when setting all options in a single object +const git: SimpleGit = simpleGit(options); + +// or split out the baseDir, supported for backward compatibility +const git: SimpleGit = simpleGit('/some/path', { binary: 'git' }); +``` + +The first argument can be either a string (representing the working directory for `git` commands to run in), +`SimpleGitOptions` object or `undefined`, the second parameter is an optional `SimpleGitOptions` object. + +All configuration properties are optional, the default values are shown in the example above. + +## Per-command Configuration + +To prefix the commands run by `simple-git` with custom configuration not saved in the git config (ie: using the +`-c` command) supply a `config` option to the instance builder: + +```typescript +// configure the instance with a custom configuration property +const git: SimpleGit = simpleGit('/some/path', { config: ['http.proxy=someproxy'] }); + +// any command executed will be prefixed with this config +// runs: git -c http.proxy=someproxy pull +await git.pull(); +``` + +## Configuring Plugins + +- [AbortController](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-ABORT-CONTROLLER.md) + Terminate pending and future tasks in a `simple-git` instance (requires node >= 16). + +- [Custom Binary](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-CUSTOM-BINARY.md) + Customise the `git` binary `simple-git` uses when spawning `git` child processes. + +- [Completion Detection](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-COMPLETION-DETECTION.md) + Customise how `simple-git` detects the end of a `git` process. + +- [Error Detection](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-ERRORS.md) + Customise the detection of errors from the underlying `git` process. + +- [Progress Events](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-PROGRESS-EVENTS.md) + Receive progress events as `git` works through long-running processes. + +- [Spawned Process Ownership](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-SPAWN-OPTIONS.md) + Configure the system `uid` / `gid` to use for spawned `git` processes. + +- [Timeout](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-TIMEOUT.md) + Automatically kill the wrapped `git` process after a rolling timeout. + +- [Unsafe](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-UNSAFE-ACTIONS.md) + Selectively opt out of `simple-git` safety precautions - for advanced users and use cases. + +## Using Task Promises + +Each task in the API returns the `simpleGit` instance for chaining together multiple tasks, and each +step in the chain is also a `Promise` that can be `await` ed in an `async` function or returned in a +`Promise` chain. + +```javascript +const git = simpleGit(); + +// chain together tasks to await final result +await git.init().addRemote('origin', '...remote.git'); + +// or await each step individually +await git.init(); +await git.addRemote('origin', '...remote.git'); +``` + +### Catching errors in async code + +To catch errors in async code, either wrap the whole chain in a try/catch: + +```javascript +const git = simpleGit(); +try { + await git.init(); + await git.addRemote(name, repoUrl); +} catch (e) { + /* handle all errors here */ +} +``` + +or catch individual steps to permit the main chain to carry on executing rather than +jumping to the final `catch` on the first error: + +```javascript +const git = simpleGit(); +try { + await git.init().catch(ignoreError); + await git.addRemote(name, repoUrl); +} catch (e) { + /* handle all errors here */ +} + +function ignoreError() {} +``` + +## Using Task Callbacks + +In addition to returning a promise, each method can also be called with a trailing callback argument +to handle the result of the task. + +```javascript +const git = simpleGit(); +git.init(onInit).addRemote('origin', 'git@github.com:steveukx/git-js.git', onRemoteAdd); + +function onInit(err, initResult) {} +function onRemoteAdd(err, addRemoteResult) {} +``` + +If any of the steps in the chain result in an error, all pending steps will be cancelled, see the +[parallel tasks](<(#concurrent--parallel-requests)>) section for more information on how to run tasks in parallel rather than in series . + +## Task Responses + +Whether using a trailing callback or a Promise, tasks either return the raw `string` or `Buffer` response from the +`git` binary, or where possible a parsed interpretation of the response. + +For type details of the response for each of the tasks, please see the [TypeScript definitions](https://github.com/steveukx/git-js/blob/main/simple-git/typings/simple-git.d.ts). + +# Upgrading from Version 2 + +From v3 of `simple-git` you can now import as an ES module, Common JS module or as TypeScript with bundled type +definitions. Upgrading from v2 will be seamless for any application not relying on APIs that were marked as deprecated +in v2 (deprecation notices were logged to `stdout` as `console.warn` in v2). + +# API + +| API | What it does | +| ---------------------------------------------------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `.add([fileA, ...], handlerFn)` | adds one or more files to be under source control | +| `.addAnnotatedTag(tagName, tagMessage, handlerFn)` | adds an annotated tag to the head of the current branch | +| `.addTag(name, handlerFn)` | adds a lightweight tag to the head of the current branch | +| `.catFile(options, [handlerFn])` | generate `cat-file` detail, `options` should be an array of strings as supported arguments to the [cat-file](https://git-scm.com/docs/git-cat-file) command | +| `.checkIgnore([filepath, ...], handlerFn)` | checks if filepath excluded by .gitignore rules | +| `.clearQueue()` | immediately clears the queue of pending tasks (note: any command currently in progress will still call its completion callback) | +| `.commit(message, handlerFn)` | commits changes in the current working directory with the supplied message where the message can be either a single string or array of strings to be passed as separate arguments (the `git` command line interface converts these to be separated by double line breaks) | +| `.commit(message, [fileA, ...], options, handlerFn)` | commits changes on the named files with the supplied message, when supplied, the optional options object can contain any other parameters to pass to the commit command, setting the value of the property to be a string will add `name=value` to the command string, setting any other type of value will result in just the key from the object being passed (ie: just `name`), an example of setting the author is below | +| `.customBinary(gitPath)` | sets the command to use to reference git, allows for using a git binary not available on the path environment variable [docs](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-CUSTOM-BINARY.md) | +| `.env(name, value)` | Set environment variables to be passed to the spawned child processes, [see usage in detail below](#environment-variables). | +| `.exec(handlerFn)` | calls a simple function in the current step | +| `.fetch([options, ] handlerFn)` | update the local working copy database with changes from the default remote repo and branch, when supplied the options argument can be a standard [options object](#how-to-specify-options) either an array of string commands as supported by the [git fetch](https://git-scm.com/docs/git-fetch). | +| `.fetch(remote, branch, handlerFn)` | update the local working copy database with changes from a remote repo | +| `.fetch(handlerFn)` | update the local working copy database with changes from the default remote repo and branch | +| `.outputHandler(handlerFn)` | attaches a handler that will be called with the name of the command being run and the `stdout` and `stderr` [readable streams](https://nodejs.org/api/stream.html#stream_class_stream_readable) created by the [child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess) running that command, see [examples](https://github.com/steveukx/git-js/blob/main/examples/git-output-handler.md) | +| `.raw(args, [handlerFn])` | Execute any arbitrary array of commands supported by the underlying git binary. When the git process returns a non-zero signal on exit and it printed something to `stderr`, the command will be treated as an error, otherwise treated as a success. | +| `.rebase([options,] handlerFn)` | Rebases the repo, `options` should be supplied as an array of string parameters supported by the [git rebase](https://git-scm.com/docs/git-rebase) command, or an object of options (see details below for option formats). | +| `.revert(commit , [options , [handlerFn]])` | reverts one or more commits in the working copy. The commit can be any regular commit-ish value (hash, name or offset such as `HEAD~2`) or a range of commits (eg: `master~5..master~2`). When supplied the [options](#how-to-specify-options) argument contain any options accepted by [git-revert](https://git-scm.com/docs/git-revert). | +| `.rm([fileA, ...], handlerFn)` | removes any number of files from source control | +| `.rmKeepLocal([fileA, ...], handlerFn)` | removes files from source control but leaves them on disk | +| `.tag(args[], handlerFn)` | Runs any supported [git tag](https://git-scm.com/docs/git-tag) commands with arguments passed as an array of strings . | +| `.tags([options, ] handlerFn)` | list all tags, use the optional [options](#how-to-specify-options) object to set any options allows by the [git tag](https://git-scm.com/docs/git-tag) command. Tags will be sorted by semantic version number by default, for git versions 2.7 and above, use the `--sort` option to set a custom sort. | + +## git apply + +- `.applyPatch(patch, [options])` applies a single string patch (as generated by `git diff`), optionally configured with the supplied [options](#how-to-specify-options) to set any arguments supported by the [apply](https://git-scm.com/docs/git-apply) command. Returns the unmodified string response from `stdout` of the `git` binary. +- `.applyPatch(patches, [options])` applies an array of string patches (as generated by `git diff`), optionally configured with the supplied [options](#how-to-specify-options) to set any arguments supported by the [apply](https://git-scm.com/docs/git-apply) command. Returns the unmodified string response from `stdout` of the `git` binary. + +## git branch + +- `.branch([options])` uses the supplied [options](#how-to-specify-options) to run any arguments supported by the [branch](https://git-scm.com/docs/git-branch) command. Either returns a [BranchSummaryResult](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/BranchSummary.ts) instance when listing branches, or a [BranchSingleDeleteResult](https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts) type object when the options included `-d`, `-D` or `--delete` which cause it to delete a named branch rather than list existing branches. +- `.branchLocal()` gets a list of local branches as a [BranchSummaryResult](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/BranchSummary.ts) instance +- `.deleteLocalBranch(branchName)` deletes a local branch - treats a failed attempt as an error +- `.deleteLocalBranch(branchName, forceDelete)` deletes a local branch, optionally explicitly setting forceDelete to true - treats a failed attempt as an error +- `.deleteLocalBranches(branchNames)` deletes multiple local branches +- `.deleteLocalBranches(branchNames, forceDelete)` deletes multiple local branches, optionally explicitly setting forceDelete to true + +## git clean + +- `.clean(mode)` clean the working tree. Mode should be "n" - dry run or "f" - force +- `.clean(cleanSwitches [,options])` set `cleanSwitches` to a string containing any number of the supported single character options, optionally with a standard [options](#how-to-specify-options) object + +## git checkout + +- `.checkout(checkoutWhat , [options])` - checks out the supplied tag, revision or branch when supplied as a string, + additional arguments supported by [git checkout](https://git-scm.com/docs/git-checkout) can be supplied as an + [options](#how-to-specify-options) object/array. + +- `.checkout(options)` - check out a tag or revision using the supplied [options](#how-to-specify-options) + +- `.checkoutBranch(branchName, startPoint)` - checks out a new branch from the supplied start point. + +- `.checkoutLocalBranch(branchName)` - checks out a new local branch + +## git clone + +- `.clone(repoPath, [localPath, [options]])` clone a remote repo at `repoPath` to a local directory at `localPath`, optionally with a standard [options](#how-to-specify-options) object of additional arguments to include between `git clone` and the trailing `repo local` arguments +- `.clone(repoPath, [options])` clone a remote repo at `repoPath` to a directory in the current working directory with the same name as the repo + +- `mirror(repoPath, [localPath, [options]])` behaves the same as the `.clone` interface with the [`--mirror` flag](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---mirror) enabled. + +## git config + +- `.addConfig(key, value, append = false, scope = 'local')` add a local configuration property, when `append` is set to + `true` the configuration setting is appended to rather than overwritten in the local config. Use the `scope` argument + to pick where to save the new configuration setting (use the exported `GitConfigScope` enum, or equivalent string + values - `worktree | local | global | system`). +- `.getConfig(key)` get the value(s) for a named key as a [ConfigGetResult](https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts) +- `.getConfig(key, scope)` get the value(s) for a named key as a [ConfigGetResult](https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts) but limit the + scope of the properties searched to a single specified scope (use the exported `GitConfigScope` enum, or equivalent + string values - `worktree | local | global | system`) + +- `.listConfig()` reads the current configuration and returns a [ConfigListSummary](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/ConfigList.ts) +- `.listConfig(scope: GitConfigScope)` as with `listConfig` but returns only those items in a specified scope (note that configuration values are overlaid on top of each other to build the config `git` will actually use - to resolve the configuration you are using use `(await listConfig()).all` without the scope argument) + +## git diff + +- `.diff([ options ])` get the diff of the current repo compared to the last commit, optionally including + any number of other arguments supported by [git diff](https://git-scm.com/docs/git-diff) supplied as an + [options](#how-to-specify-options) object/array. Returns the raw `diff` output as a string. + +- `.diffSummary([ options ])` creates a [DiffResult](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/DiffSummary.ts) + to summarise the diff for files in the repo. Uses the `--stat` format by default which can be overridden + by passing in any of the log format commands (eg: `--numstat` or `--name-stat`) as part of the optional + [options](#how-to-specify-options) object/array. + +## git grep [examples](https://github.com/steveukx/git-js/blob/main/examples/git-grep.md) + +- `.grep(searchTerm)` searches for a single search term across all files in the working tree, optionally passing a standard [options](#how-to-specify-options) object of additional arguments +- `.grep(grepQueryBuilder(...))` use the `grepQueryBuilder` to create a complex query to search for, optionally passing a standard [options](#how-to-specify-options) object of additional arguments + +## git hash-object + +- `.hashObject(filePath, write = false)` computes the object ID value for the contents of the named file (which can be + outside of the work tree), optionally writing the resulting value to the object database. + +## git init + +- `.init(bare , [options])` initialize a repository using the boolean `bare` parameter to intialise a bare repository. + Any number of other arguments supported by [git init](https://git-scm.com/docs/git-init) can be supplied as an + [options](#how-to-specify-options) object/array. + +- `.init([options])` initialize a repository using any arguments supported by + [git init](https://git-scm.com/docs/git-init) supplied as an [options](#how-to-specify-options) object/array. + +## git log + +- `.log([options])` list commits between `options.from` and `options.to` tags or branch (if not specified will + show all history). Use the `options` object to set any [options](#how-to-specify-options) supported by the + [git log](https://git-scm.com/docs/git-log) command or any of the following: + + - `options.file` - the path to a file in your repository to only consider this path. + - `options.format` - custom log format object, keys are the property names used on the returned object, values are the format string from [pretty formats](https://git-scm.com/docs/pretty-formats#Documentation/pretty-formats.txt) + - `options.from` - sets the oldest commit in the range to return, use along with `options.to` to set a bounded range + - `options.mailMap` - defaults to true, enables the use of [mail map](https://git-scm.com/docs/gitmailmap) in returned values for email and name from the default format + - `options.maxCount` - equivalent to setting the `--max-count` option + - `options.multiLine` - enables multiline body values in the default format (disabled by default) + - `options.splitter` - the character sequence to use as a delimiter between fields in the log, should be a value that doesn't appear in any log message (defaults to `ò`) + - `options.strictDate` - switches the authored date value from an ISO 8601-like format to be strict ISO 8601 format + - `options.symmetric` - defaults to true, enables [symmetric revision range](https://git-scm.com/docs/gitrevisions#_dotted_range_notations) rather than a two-dot range + - `options.to` - sets the newset commit in the range to return, use along with `options.from` to set a bounded range + + When only one of `options.from` and `options.to` is supplied, the default value of the omitted option is equivalent to `HEAD`. For any other commit, explicitly supply both from and to commits (for example use `await git.firstCommit()` as the default value of `from` to log since the first commit of the repo). + +## git merge + +- `.merge(options)` runs a merge using any configuration [options](#how-to-specify-options) supported + by [git merge](https://git-scm.com/docs/git-merge). + Conflicts during the merge result in an error response, the response is an instance of + [MergeSummary](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/MergeSummary.ts) whether it was an error or success. + When successful, the MergeSummary has all detail from a the [PullSummary](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/PullSummary.ts) + along with summary detail for the merge. + When the merge failed, the MergeSummary contains summary detail for why the merge failed and which files + prevented the merge. + +- `.mergeFromTo(remote, branch , [options])` - merge from the specified branch into the currently checked out branch, + similar to `.merge` but with the `remote` and `branch` supplied as strings separately to any additional + [options](#how-to-specify-options). + +## git mv + +- `.mv(from, to)` rename or move a single file at `from` to `to` + +- `.mv(from, to)` move all files in the `from` array to the `to` directory + +## git pull + +- `.pull([options])` pulls all updates from the default tracked remote, any arguments supported by + [git pull](https://git-scm.com/docs/git-pull) can be supplied as an [options](#how-to-specify-options) object/array. + +- `.pull(remote, branch, [options])` pulls all updates from the specified remote branch (eg 'origin'/'master') along + with any custom [options](#how-to-specify-options) object/array + +## git push + +- `.push([options])` pushes to a named remote/branch using any supported [options](#how-to-specify-options) + from the [git push](https://git-scm.com/docs/git-push) command. Note that `simple-git` enforces the use of + `--verbose --porcelain` options in order to parse the response. You don't need to supply these options. + +- `.push(remote, branch, [options])` pushes to a named remote/branch, supports additional + [options](#how-to-specify-options) from the [git push](https://git-scm.com/docs/git-push) command. + +- `.pushTags(remote, [options])` pushes local tags to a named remote (equivalent to using `.push([remote, '--tags'])`) + +## git remote + +- `.addRemote(name, repo, [options])` adds a new named remote to be tracked as `name` at the path `repo`, optionally with any supported [options](#how-to-specify-options) for the [git add](https://git-scm.com/docs/git-remote#Documentation/git-remote.txt-emaddem) call. +- `.getRemotes([verbose])` gets a list of the named remotes, supply the optional `verbose` option as `true` to include the URLs and purpose of each ref +- `.listRemote([options])` lists remote repositories - there are so many optional arguments in the underlying `git ls-remote` call, just supply any you want to use as the optional [options](#how-to-specify-options) eg: `git.listRemote(['--heads', '--tags'], console.log)` +- `.remote([options])` runs a `git remote` command with any number of [options](#how-to-specify-options) +- `.removeRemote(name)` removes the named remote + +## git reset + +- `.reset(resetMode, [resetOptions])` resets the repository, sets the reset mode to one of the supported types (use a constant from + the exported `ResetMode` enum, or a string equivalent: `mixed`, `soft`, `hard`, `merge`, `keep`). Any number of other arguments + supported by [git reset](https://git-scm.com/docs/git-reset) can be supplied as an [options](#how-to-specify-options) object/array. + +- `.reset(resetOptions)` resets the repository with the supplied [options](#how-to-specify-options) + +- `.reset()` resets the repository in `soft` mode. + +## git rev-parse / repo properties + +- `.revparse([options])` sends the supplied [options](#how-to-specify-options) to [git rev-parse](https://git-scm.com/docs/git-rev-parse) and returns the string response from `git`. + +- `.checkIsRepo()` gets whether the current working directory is a descendent of a git repository. +- `.checkIsRepo('bare')` gets whether the current working directory is within a bare git repo (see either [git clone --bare](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---bare) or [git init --bare](https://git-scm.com/docs/git-init#Documentation/git-init.txt---bare)). +- `.checkIsRepo('root')` gets whether the current working directory is the root directory for a repo (sub-directories will return false). + +- `.firstCommit()` gets the commit hash of the first commit made to the current repo. + +## git show + +- `.show(options)` show various types of objects for example the file content at a certain commit. `options` is the single value string or any [options](#how-to-specify-options) supported by the [git show](https://git-scm.com/docs/git-show) command. +- `.showBuffer(options)` same as the `.show` API, but returns the Buffer content directly to allow for showing binary file content. + +## git status + +- `.status([options])` gets the status of the current repo, resulting in a [StatusResult](https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts). Additional arguments + supported by [git status](https://git-scm.com/docs/git-status) can be supplied as an [options](#how-to-specify-options) object/array. + +## git submodule + +- `.subModule(options)` Run a `git submodule` command with on or more arguments passed in as an [options](#how-to-specify-options) array or object +- `.submoduleAdd(repo, path)` Adds a new sub module +- `.submoduleInit([options]` Initialises sub modules, the optional [options](#how-to-specify-options) argument can be used to pass extra options to the `git submodule init` command. +- `.submoduleUpdate(subModuleName, [options])` Updates sub modules, can be called with a sub module name and [options](#how-to-specify-options), just the options or with no arguments + +## git stash + +- `.stash([ options ])` Stash the working directory, optional first argument can be an array of string arguments or [options](#how-to-specify-options) object to pass to the [git stash](https://git-scm.com/docs/git-stash) command. + +- `.stashList([ options ])` Retrieves the stash list, optional first argument can be an object in the same format as used in [git log](#git-log). + +## git version [examples](https://github.com/steveukx/git-js/blob/main/examples/git-version.md) + +- `.version()` retrieve the major, minor and patch for the currently installed `git`. Use the `.installed` property of the result to determine whether `git` is accessible on the path. + +## changing the working directory [examples](https://github.com/steveukx/git-js/blob/main/examples/git-change-working-directory.md) + +- `.cwd(workingDirectory)` Sets the working directory for all future commands - note, this will change the working for the root instance, any chain created from the root will also be changed. +- `.cwd({ path, root = false })` Sets the working directory for all future commands either in the current chain of commands (where `root` is omitted or set to `false`) or in the main instance (where `root` is `true`). + +## How to Specify Options + +Where the task accepts custom options (eg: `pull` or `commit`), these can be supplied as an object, the keys of which +will all be merged as trailing arguments in the command string, or as a simple array of strings. + +### Options as an Object + +When the value of the property in the options object is a `string`, that name value +pair will be included in the command string as `name=value`. For example: + +```javascript +// results in 'git pull origin master --no-rebase' +git.pull('origin', 'master', { '--no-rebase': null }); + +// results in 'git pull origin master --rebase=true' +git.pull('origin', 'master', { '--rebase': 'true' }); +``` + +### Options as an Array + +Options can also be supplied as an array of strings to be merged into the task's commands +in the same way as when an object is used: + +```javascript +// results in 'git pull origin master --no-rebase' +git.pull('origin', 'master', ['--no-rebase']); +``` + +# Release History + +Major release 3.x changes the packaging of the library, making it consumable as a CommonJS module, ES module as well as +with TypeScript (see [usage](#usage) above). The library is now published as a single file, so please ensure your +application hasn't been making use of non-documented APIs by importing from a sub-directory path. + +See also: + +- [release notes v3](https://github.com/steveukx/git-js/blob/main/simple-git/CHANGELOG.md) +- [release notes v2](https://github.com/steveukx/git-js/blob/main/docs/RELEASE-NOTES-V2.md) + +# Concurrent / Parallel Requests + +When the methods of `simple-git` are chained together, they create an execution chain that will run in series, useful +for when the tasks themselves are order-dependent, eg: + +```typescript +simpleGit().init().addRemote('origin', 'https://some-repo.git').fetch(); +``` + +Each task requires that the one before it has been run successfully before it is called, any errors in a +step of the chain should prevent later steps from being attempted. + +When the methods of `simple-git` are called on the root instance (ie: `git = simpleGit()`) rather than chained +off another task, it starts a new chain and will not be affected failures in tasks already being run. Useful +for when the tasks are independent of each other, eg: + +```typescript +const git = simpleGit(); +const results = await Promise.all([ + git.raw('rev-parse', '--show-cdup').catch(swallow), + git.raw('rev-parse', '--show-prefix').catch(swallow), +]); +function swallow(err) { + return null; +} +``` + +Each `simple-git` instance limits the number of spawned child processes that can be run simultaneously and +manages the queue of pending tasks for you. Configure this value by passing an options object to the +`simpleGit` function, eg: + +```typescript +const git = simpleGit({ maxConcurrentProcesses: 10 }); +``` + +Treating tasks called on the root instance as the start of separate chains is a change to the behaviour of +`simple-git` and was added in version `2.11.0`. + +# Complex Requests + +When no suitable wrapper exists in the interface for creating a request, run the command directly +using `git.raw([...], handler)`. The array of commands are passed directly to the `git` binary: + +```javascript +const path = '/path/to/repo'; +const commands = ['config', '--global', 'advice.pushNonFastForward', 'false']; + +// using an array of commands and node-style callback +simpleGit(path).raw(commands, (err, result) => { + // err is null unless this command failed + // result is the raw output of this command +}); + +// using a var-args of strings and awaiting rather than using the callback +const result = await simpleGit(path).raw(...commands); + +// automatically trim trailing white-space in responses +const result = await simpleGit(path, { trimmed: true }).raw(...commands); +``` + +# Authentication + +The easiest way to supply a username / password to the remote host is to include it in the URL, for example: + +```javascript +const USER = 'something'; +const PASS = 'somewhere'; +const REPO = 'github.com/username/private-repo'; + +const remote = `https://${USER}:${PASS}@${REPO}`; + +simpleGit() + .clone(remote) + .then(() => console.log('finished')) + .catch((err) => console.error('failed: ', err)); +``` + +Be sure to not enable debug logging when using this mechanism for authentication +to ensure passwords aren't logged to stdout. + +# Environment Variables + +Pass one or more environment variables to the child processes spawned by `simple-git` with the `.env` method which +supports passing either an object of name=value pairs or setting a single variable at a time: + +```javascript +const GIT_SSH_COMMAND = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'; + +simpleGit() + .env('GIT_SSH_COMMAND', GIT_SSH_COMMAND) + .status((err, status) => { + /* */ + }); + +simpleGit() + .env({ ...process.env, GIT_SSH_COMMAND }) + .status() + .then((status) => {}) + .catch((err) => {}); +``` + +Note - when passing environment variables into the child process, these will replace the standard `process.env` +variables, the example above creates a new object based on `process.env` but with the `GIT_SSH_COMMAND` property added. + +# Exception Handling + +When the `git` process exits with a non-zero status (or in some cases like `merge` the git process exits with a +successful zero code but there are conflicts in the merge) the task will reject with a `GitError` when there is no +available parser to handle the error or a +`GitResponseError` for when there is. + +See the `err` property of the callback: + +```javascript +git.merge((err, mergeSummary) => { + if (err.git) { + mergeSummary = err.git; // the failed mergeSummary + } +}); +``` + +Catch errors with try/catch in async code: + +```javascript +try { + const mergeSummary = await git.merge(); + console.log(`Merged ${mergeSummary.merges.length} files`); +} catch (err) { + // err.message - the string summary of the error + // err.stack - some stack trace detail + // err.git - where a parser was able to run, this is the parsed content + + console.error(`Merge resulted in ${err.git.conflicts.length} conflicts`); +} +``` + +Catch errors with a `.catch` on the promise: + +```javascript +const mergeSummary = await git.merge().catch((err) => { + if (err.git) { + return err.git; + } // the unsuccessful mergeSummary + throw err; // some other error, so throw +}); + +if (mergeSummary.failed) { + console.error(`Merge resulted in ${mergeSummary.conflicts.length} conflicts`); +} +``` + +With typed errors available in TypeScript + +```typescript +import { simpleGit, MergeSummary, GitResponseError } from 'simple-git'; +try { + const mergeSummary = await simpleGit().merge(); + console.log(`Merged ${mergeSummary.merges.length} files`); +} catch (err) { + // err.message - the string summary of the error + // err.stack - some stack trace detail + // err.git - where a parser was able to run, this is the parsed content + const mergeSummary: MergeSummary = (err as GitResponseError).git; + const conflicts = mergeSummary?.conflicts || []; + + console.error(`Merge resulted in ${conflicts.length} conflicts`); +} +``` + +# Troubleshooting / FAQ + +### Enable logging + +See the [debug logging guide](https://github.com/steveukx/git-js/blob/main/docs/DEBUG-LOGGING-GUIDE.md) for logging examples and how to +make use of the [debug](https://www.npmjs.com/package/debug) library's programmatic interface +in your application. + +### Enable Verbose Logging + +See the [debug logging guide](https://github.com/steveukx/git-js/blob/main/docs/DEBUG-LOGGING-GUIDE.md#verbose-logging-options) for +the full list of verbose logging options to use with the +[debug](https://www.npmjs.com/package/debug) library. + +### Every command returns ENOENT error message + +There are a few potential reasons: + +- `git` isn't available as a binary for the user running the main `node` process, custom paths to the binary can be used + with the `.customBinary(...)` API option. + +- the working directory passed in to the main `simple-git` function isn't accessible, check it is read/write accessible + by the user running the `node` process. This library uses + [@kwsites/file-exists](https://www.npmjs.com/package/@kwsites/file-exists) to validate the working directory exists, + to output its logs add `@kwsites/file-exists` to your `DEBUG` environment variable. eg: + + `DEBUG=@kwsites/file-exists,simple-git node ./your-app.js` + +### Log format fails + +The properties of `git log` are fetched using the `--pretty=format` argument which supports different tokens depending +on the version of `git` - for example the `%D` token used to show the refs was added in git `2.2.3`, for any version +before that please ensure you are supplying your own format object with properties supported by the version of git you +are using. + +For more details of the supported tokens, please see the +[official `git log` documentation](https://git-scm.com/docs/git-log#_pretty_formats) + +### Log response properties are out of order + +The properties of `git.log` are fetched using the character sequence `ò` as a delimiter. If your commit messages +use this sequence, supply a custom `splitter` in the options, for example: `git.log({ splitter: '💻' })` + +### Pull / Diff / Merge summary responses don't recognise any files + +- Enable verbose logs with the environment variable `DEBUG=simple-git:task:*,simple-git:output:*` +- Check the output (for example: `simple-git:output:diff:1 [stdOut] 1 file changed, 1 insertion(+)`) +- Check the `stdOut` output is the same as you would expect to see when running the command directly in terminal +- Check the language used in the response is english locale + +In some cases `git` will show progress messages or additional detail on error states in the output for +`stdErr` that will help debug your issue, these messages are also included in the verbose log. + +### Legacy Node Versions + +From `v3.x`, `simple-git` will drop support for `node.js` version 10 or below, to use in a lower version of node will +result in errors such as: + +- `Object.fromEntries is not a function` +- `Object.entries is not a function` +- `message.flatMap is not a function` + +To resolve these issues, either upgrade to a newer version of node.js or ensure you are using the necessary polyfills +from `core-js` - see [Legacy Node Versions](https://github.com/steveukx/git-js/blob/main/docs/LEGACY_NODE_VERSIONS.md). + +# Examples + +### using a pathspec to limit the scope of the task + +If the `simple-git` API doesn't explicitly limit the scope of the task being run (ie: `git.add()` requires the files to +be added, but `git.status()` will run against the entire repo), add a `pathspec` to the command using trailing options: + +```typescript +import { simpleGit, pathspec } from "simple-git"; + +const git = simpleGit(); +const wholeRepoStatus = await git.status(); +const subDirStatusUsingOptArray = await git.status([pathspec('sub-dir')]); +const subDirStatusUsingOptObject = await git.status({ 'sub-dir': pathspec('sub-dir') }); +``` + +### async await + +```javascript +async function status(workingDir) { + let statusSummary = null; + try { + statusSummary = await simpleGit(workingDir).status(); + } catch (e) { + // handle the error + } + + return statusSummary; +} + +// using the async function +status(__dirname + '/some-repo').then((status) => console.log(status)); +``` + +### Initialise a git repo if necessary + +```javascript +const git = simpleGit(__dirname); + +git.checkIsRepo() + .then((isRepo) => !isRepo && initialiseRepo(git)) + .then(() => git.fetch()); + +function initialiseRepo(git) { + return git.init().then(() => git.addRemote('origin', 'https://some.git.repo')); +} +``` + +### Update repo and get a list of tags + +```javascript +simpleGit(__dirname + '/some-repo') + .pull() + .tags((err, tags) => console.log('Latest available tag: %s', tags.latest)); + +// update repo and when there are changes, restart the app +simpleGit().pull((err, update) => { + if (update && update.summary.changes) { + require('child_process').exec('npm restart'); + } +}); +``` + +### Starting a new repo + +```javascript +simpleGit() + .init() + .add('./*') + .commit('first commit!') + .addRemote('origin', 'https://github.com/user/repo.git') + .push('origin', 'master'); +``` + +### push with `-u` + +```javascript +simpleGit() + .add('./*') + .commit('first commit!') + .addRemote('origin', 'some-repo-url') + .push(['-u', 'origin', 'master'], () => console.log('done')); +``` + +### Piping to the console for long-running tasks + +See [progress events](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-PROGRESS-EVENTS.md) for more details on +logging progress updates. + +```javascript +const git = simpleGit({ + progress({ method, stage, progress }) { + console.log(`git.${method} ${stage} stage ${progress}% complete`); + }, +}); +git.checkout('https://github.com/user/repo.git'); +``` + +### Update repo and print messages when there are changes, restart the app + +```javascript +// when using a chain +simpleGit() + .exec(() => console.log('Starting pull...')) + .pull((err, update) => { + if (update && update.summary.changes) { + require('child_process').exec('npm restart'); + } + }) + .exec(() => console.log('pull done.')); + +// when using async and optional chaining +const git = simpleGit(); +console.log('Starting pull...'); +if ((await git.pull())?.summary.changes) { + require('child_process').exec('npm restart'); +} +console.log('pull done.'); +``` + +### Get a full commits list, and then only between 0.11.0 and 0.12.0 tags + +```javascript +console.log(await simpleGit().log()); +console.log(await simpleGit().log('0.11.0', '0.12.0')); +``` + +### Set the local configuration for author, then author for an individual commit + +```javascript +simpleGit() + .addConfig('user.name', 'Some One') + .addConfig('user.email', 'some@one.com') + .commit('committed as "Some One"', 'file-one') + .commit('committed as "Another Person"', 'file-two', { + '--author': '"Another Person "', + }); +``` + +### Get remote repositories + +```javascript +simpleGit().listRemote(['--get-url'], (err, data) => { + if (!err) { + console.log('Remote url for repository at ' + __dirname + ':'); + console.log(data); + } +}); +``` diff --git a/node_modules/supports-color/browser.js b/node_modules/supports-color/browser.js new file mode 100644 index 0000000..62afa3a --- /dev/null +++ b/node_modules/supports-color/browser.js @@ -0,0 +1,5 @@ +'use strict'; +module.exports = { + stdout: false, + stderr: false +}; diff --git a/node_modules/supports-color/index.js b/node_modules/supports-color/index.js new file mode 100644 index 0000000..6fada39 --- /dev/null +++ b/node_modules/supports-color/index.js @@ -0,0 +1,135 @@ +'use strict'; +const os = require('os'); +const tty = require('tty'); +const hasFlag = require('has-flag'); + +const {env} = process; + +let forceColor; +if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false') || + hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + forceColor = 1; +} + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || + hasFlag('color=full') || + hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os.release().split('.'); + if ( + Number(osRelease[0]) >= 10 && + Number(osRelease[2]) >= 10586 + ) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +module.exports = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty.isatty(1))), + stderr: translateLevel(supportsColor(true, tty.isatty(2))) +}; diff --git a/node_modules/supports-color/license b/node_modules/supports-color/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/supports-color/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/supports-color/package.json b/node_modules/supports-color/package.json new file mode 100644 index 0000000..f7182ed --- /dev/null +++ b/node_modules/supports-color/package.json @@ -0,0 +1,53 @@ +{ + "name": "supports-color", + "version": "7.2.0", + "description": "Detect whether a terminal supports color", + "license": "MIT", + "repository": "chalk/supports-color", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js", + "browser.js" + ], + "keywords": [ + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "ansi", + "styles", + "tty", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "support", + "supports", + "capability", + "detect", + "truecolor", + "16m" + ], + "dependencies": { + "has-flag": "^4.0.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "import-fresh": "^3.0.0", + "xo": "^0.24.0" + }, + "browser": "browser.js" +} diff --git a/node_modules/supports-color/readme.md b/node_modules/supports-color/readme.md new file mode 100644 index 0000000..3654228 --- /dev/null +++ b/node_modules/supports-color/readme.md @@ -0,0 +1,76 @@ +# supports-color [![Build Status](https://travis-ci.org/chalk/supports-color.svg?branch=master)](https://travis-ci.org/chalk/supports-color) + +> Detect whether a terminal supports color + + +## Install + +``` +$ npm install supports-color +``` + + +## Usage + +```js +const supportsColor = require('supports-color'); + +if (supportsColor.stdout) { + console.log('Terminal stdout supports color'); +} + +if (supportsColor.stdout.has256) { + console.log('Terminal stdout supports 256 colors'); +} + +if (supportsColor.stderr.has16m) { + console.log('Terminal stderr supports 16 million colors (truecolor)'); +} +``` + + +## API + +Returns an `Object` with a `stdout` and `stderr` property for testing either streams. Each property is an `Object`, or `false` if color is not supported. + +The `stdout`/`stderr` objects specifies a level of support for color through a `.level` property and a corresponding flag: + +- `.level = 1` and `.hasBasic = true`: Basic color support (16 colors) +- `.level = 2` and `.has256 = true`: 256 color support +- `.level = 3` and `.has16m = true`: Truecolor support (16 million colors) + + +## Info + +It obeys the `--color` and `--no-color` CLI flags. + +For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks. + +Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively. + + +## Related + +- [supports-color-cli](https://github.com/chalk/supports-color-cli) - CLI for this module +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- diff --git a/node_modules/tr46/.npmignore b/node_modules/tr46/.npmignore new file mode 100644 index 0000000..96e9161 --- /dev/null +++ b/node_modules/tr46/.npmignore @@ -0,0 +1,4 @@ +scripts/ +test/ + +!lib/mapping_table.json diff --git a/node_modules/tr46/index.js b/node_modules/tr46/index.js new file mode 100644 index 0000000..9ce12ca --- /dev/null +++ b/node_modules/tr46/index.js @@ -0,0 +1,193 @@ +"use strict"; + +var punycode = require("punycode"); +var mappingTable = require("./lib/mappingTable.json"); + +var PROCESSING_OPTIONS = { + TRANSITIONAL: 0, + NONTRANSITIONAL: 1 +}; + +function normalize(str) { // fix bug in v8 + return str.split('\u0000').map(function (s) { return s.normalize('NFC'); }).join('\u0000'); +} + +function findStatus(val) { + var start = 0; + var end = mappingTable.length - 1; + + while (start <= end) { + var mid = Math.floor((start + end) / 2); + + var target = mappingTable[mid]; + if (target[0][0] <= val && target[0][1] >= val) { + return target; + } else if (target[0][0] > val) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return null; +} + +var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + +function countSymbols(string) { + return string + // replace every surrogate pair with a BMP symbol + .replace(regexAstralSymbols, '_') + // then get the length + .length; +} + +function mapChars(domain_name, useSTD3, processing_option) { + var hasError = false; + var processed = ""; + + var len = countSymbols(domain_name); + for (var i = 0; i < len; ++i) { + var codePoint = domain_name.codePointAt(i); + var status = findStatus(codePoint); + + switch (status[1]) { + case "disallowed": + hasError = true; + processed += String.fromCodePoint(codePoint); + break; + case "ignored": + break; + case "mapped": + processed += String.fromCodePoint.apply(String, status[2]); + break; + case "deviation": + if (processing_option === PROCESSING_OPTIONS.TRANSITIONAL) { + processed += String.fromCodePoint.apply(String, status[2]); + } else { + processed += String.fromCodePoint(codePoint); + } + break; + case "valid": + processed += String.fromCodePoint(codePoint); + break; + case "disallowed_STD3_mapped": + if (useSTD3) { + hasError = true; + processed += String.fromCodePoint(codePoint); + } else { + processed += String.fromCodePoint.apply(String, status[2]); + } + break; + case "disallowed_STD3_valid": + if (useSTD3) { + hasError = true; + } + + processed += String.fromCodePoint(codePoint); + break; + } + } + + return { + string: processed, + error: hasError + }; +} + +var combiningMarksRegex = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D]|\uD800[\uDDFD\uDEE0\uDF76-\uDF7A]|\uD802[\uDE01-\uDE03\uDE05\uDE06\uDE0C-\uDE0F\uDE38-\uDE3A\uDE3F\uDEE5\uDEE6]|\uD804[\uDC00-\uDC02\uDC38-\uDC46\uDC7F-\uDC82\uDCB0-\uDCBA\uDD00-\uDD02\uDD27-\uDD34\uDD73\uDD80-\uDD82\uDDB3-\uDDC0\uDE2C-\uDE37\uDEDF-\uDEEA\uDF01-\uDF03\uDF3C\uDF3E-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF62\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDCB0-\uDCC3\uDDAF-\uDDB5\uDDB8-\uDDC0\uDE30-\uDE40\uDEAB-\uDEB7]|\uD81A[\uDEF0-\uDEF4\uDF30-\uDF36]|\uD81B[\uDF51-\uDF7E\uDF8F-\uDF92]|\uD82F[\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD83A[\uDCD0-\uDCD6]|\uDB40[\uDD00-\uDDEF]/; + +function validateLabel(label, processing_option) { + if (label.substr(0, 4) === "xn--") { + label = punycode.toUnicode(label); + processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL; + } + + var error = false; + + if (normalize(label) !== label || + (label[3] === "-" && label[4] === "-") || + label[0] === "-" || label[label.length - 1] === "-" || + label.indexOf(".") !== -1 || + label.search(combiningMarksRegex) === 0) { + error = true; + } + + var len = countSymbols(label); + for (var i = 0; i < len; ++i) { + var status = findStatus(label.codePointAt(i)); + if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") || + (processing === PROCESSING_OPTIONS.NONTRANSITIONAL && + status[1] !== "valid" && status[1] !== "deviation")) { + error = true; + break; + } + } + + return { + label: label, + error: error + }; +} + +function processing(domain_name, useSTD3, processing_option) { + var result = mapChars(domain_name, useSTD3, processing_option); + result.string = normalize(result.string); + + var labels = result.string.split("."); + for (var i = 0; i < labels.length; ++i) { + try { + var validation = validateLabel(labels[i]); + labels[i] = validation.label; + result.error = result.error || validation.error; + } catch(e) { + result.error = true; + } + } + + return { + string: labels.join("."), + error: result.error + }; +} + +module.exports.toASCII = function(domain_name, useSTD3, processing_option, verifyDnsLength) { + var result = processing(domain_name, useSTD3, processing_option); + var labels = result.string.split("."); + labels = labels.map(function(l) { + try { + return punycode.toASCII(l); + } catch(e) { + result.error = true; + return l; + } + }); + + if (verifyDnsLength) { + var total = labels.slice(0, labels.length - 1).join(".").length; + if (total.length > 253 || total.length === 0) { + result.error = true; + } + + for (var i=0; i < labels.length; ++i) { + if (labels.length > 63 || labels.length === 0) { + result.error = true; + break; + } + } + } + + if (result.error) return null; + return labels.join("."); +}; + +module.exports.toUnicode = function(domain_name, useSTD3) { + var result = processing(domain_name, useSTD3, PROCESSING_OPTIONS.NONTRANSITIONAL); + + return { + domain: result.string, + error: result.error + }; +}; + +module.exports.PROCESSING_OPTIONS = PROCESSING_OPTIONS; diff --git a/node_modules/tr46/lib/.gitkeep b/node_modules/tr46/lib/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/tr46/lib/mappingTable.json b/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 0000000..89cf19a --- /dev/null +++ b/node_modules/tr46/lib/mappingTable.json @@ -0,0 +1 @@ +[[[0,44],"disallowed_STD3_valid"],[[45,46],"valid"],[[47,47],"disallowed_STD3_valid"],[[48,57],"valid"],[[58,64],"disallowed_STD3_valid"],[[65,65],"mapped",[97]],[[66,66],"mapped",[98]],[[67,67],"mapped",[99]],[[68,68],"mapped",[100]],[[69,69],"mapped",[101]],[[70,70],"mapped",[102]],[[71,71],"mapped",[103]],[[72,72],"mapped",[104]],[[73,73],"mapped",[105]],[[74,74],"mapped",[106]],[[75,75],"mapped",[107]],[[76,76],"mapped",[108]],[[77,77],"mapped",[109]],[[78,78],"mapped",[110]],[[79,79],"mapped",[111]],[[80,80],"mapped",[112]],[[81,81],"mapped",[113]],[[82,82],"mapped",[114]],[[83,83],"mapped",[115]],[[84,84],"mapped",[116]],[[85,85],"mapped",[117]],[[86,86],"mapped",[118]],[[87,87],"mapped",[119]],[[88,88],"mapped",[120]],[[89,89],"mapped",[121]],[[90,90],"mapped",[122]],[[91,96],"disallowed_STD3_valid"],[[97,122],"valid"],[[123,127],"disallowed_STD3_valid"],[[128,159],"disallowed"],[[160,160],"disallowed_STD3_mapped",[32]],[[161,167],"valid",[],"NV8"],[[168,168],"disallowed_STD3_mapped",[32,776]],[[169,169],"valid",[],"NV8"],[[170,170],"mapped",[97]],[[171,172],"valid",[],"NV8"],[[173,173],"ignored"],[[174,174],"valid",[],"NV8"],[[175,175],"disallowed_STD3_mapped",[32,772]],[[176,177],"valid",[],"NV8"],[[178,178],"mapped",[50]],[[179,179],"mapped",[51]],[[180,180],"disallowed_STD3_mapped",[32,769]],[[181,181],"mapped",[956]],[[182,182],"valid",[],"NV8"],[[183,183],"valid"],[[184,184],"disallowed_STD3_mapped",[32,807]],[[185,185],"mapped",[49]],[[186,186],"mapped",[111]],[[187,187],"valid",[],"NV8"],[[188,188],"mapped",[49,8260,52]],[[189,189],"mapped",[49,8260,50]],[[190,190],"mapped",[51,8260,52]],[[191,191],"valid",[],"NV8"],[[192,192],"mapped",[224]],[[193,193],"mapped",[225]],[[194,194],"mapped",[226]],[[195,195],"mapped",[227]],[[196,196],"mapped",[228]],[[197,197],"mapped",[229]],[[198,198],"mapped",[230]],[[199,199],"mapped",[231]],[[200,200],"mapped",[232]],[[201,201],"mapped",[233]],[[202,202],"mapped",[234]],[[203,203],"mapped",[235]],[[204,204],"mapped",[236]],[[205,205],"mapped",[237]],[[206,206],"mapped",[238]],[[207,207],"mapped",[239]],[[208,208],"mapped",[240]],[[209,209],"mapped",[241]],[[210,210],"mapped",[242]],[[211,211],"mapped",[243]],[[212,212],"mapped",[244]],[[213,213],"mapped",[245]],[[214,214],"mapped",[246]],[[215,215],"valid",[],"NV8"],[[216,216],"mapped",[248]],[[217,217],"mapped",[249]],[[218,218],"mapped",[250]],[[219,219],"mapped",[251]],[[220,220],"mapped",[252]],[[221,221],"mapped",[253]],[[222,222],"mapped",[254]],[[223,223],"deviation",[115,115]],[[224,246],"valid"],[[247,247],"valid",[],"NV8"],[[248,255],"valid"],[[256,256],"mapped",[257]],[[257,257],"valid"],[[258,258],"mapped",[259]],[[259,259],"valid"],[[260,260],"mapped",[261]],[[261,261],"valid"],[[262,262],"mapped",[263]],[[263,263],"valid"],[[264,264],"mapped",[265]],[[265,265],"valid"],[[266,266],"mapped",[267]],[[267,267],"valid"],[[268,268],"mapped",[269]],[[269,269],"valid"],[[270,270],"mapped",[271]],[[271,271],"valid"],[[272,272],"mapped",[273]],[[273,273],"valid"],[[274,274],"mapped",[275]],[[275,275],"valid"],[[276,276],"mapped",[277]],[[277,277],"valid"],[[278,278],"mapped",[279]],[[279,279],"valid"],[[280,280],"mapped",[281]],[[281,281],"valid"],[[282,282],"mapped",[283]],[[283,283],"valid"],[[284,284],"mapped",[285]],[[285,285],"valid"],[[286,286],"mapped",[287]],[[287,287],"valid"],[[288,288],"mapped",[289]],[[289,289],"valid"],[[290,290],"mapped",[291]],[[291,291],"valid"],[[292,292],"mapped",[293]],[[293,293],"valid"],[[294,294],"mapped",[295]],[[295,295],"valid"],[[296,296],"mapped",[297]],[[297,297],"valid"],[[298,298],"mapped",[299]],[[299,299],"valid"],[[300,300],"mapped",[301]],[[301,301],"valid"],[[302,302],"mapped",[303]],[[303,303],"valid"],[[304,304],"mapped",[105,775]],[[305,305],"valid"],[[306,307],"mapped",[105,106]],[[308,308],"mapped",[309]],[[309,309],"valid"],[[310,310],"mapped",[311]],[[311,312],"valid"],[[313,313],"mapped",[314]],[[314,314],"valid"],[[315,315],"mapped",[316]],[[316,316],"valid"],[[317,317],"mapped",[318]],[[318,318],"valid"],[[319,320],"mapped",[108,183]],[[321,321],"mapped",[322]],[[322,322],"valid"],[[323,323],"mapped",[324]],[[324,324],"valid"],[[325,325],"mapped",[326]],[[326,326],"valid"],[[327,327],"mapped",[328]],[[328,328],"valid"],[[329,329],"mapped",[700,110]],[[330,330],"mapped",[331]],[[331,331],"valid"],[[332,332],"mapped",[333]],[[333,333],"valid"],[[334,334],"mapped",[335]],[[335,335],"valid"],[[336,336],"mapped",[337]],[[337,337],"valid"],[[338,338],"mapped",[339]],[[339,339],"valid"],[[340,340],"mapped",[341]],[[341,341],"valid"],[[342,342],"mapped",[343]],[[343,343],"valid"],[[344,344],"mapped",[345]],[[345,345],"valid"],[[346,346],"mapped",[347]],[[347,347],"valid"],[[348,348],"mapped",[349]],[[349,349],"valid"],[[350,350],"mapped",[351]],[[351,351],"valid"],[[352,352],"mapped",[353]],[[353,353],"valid"],[[354,354],"mapped",[355]],[[355,355],"valid"],[[356,356],"mapped",[357]],[[357,357],"valid"],[[358,358],"mapped",[359]],[[359,359],"valid"],[[360,360],"mapped",[361]],[[361,361],"valid"],[[362,362],"mapped",[363]],[[363,363],"valid"],[[364,364],"mapped",[365]],[[365,365],"valid"],[[366,366],"mapped",[367]],[[367,367],"valid"],[[368,368],"mapped",[369]],[[369,369],"valid"],[[370,370],"mapped",[371]],[[371,371],"valid"],[[372,372],"mapped",[373]],[[373,373],"valid"],[[374,374],"mapped",[375]],[[375,375],"valid"],[[376,376],"mapped",[255]],[[377,377],"mapped",[378]],[[378,378],"valid"],[[379,379],"mapped",[380]],[[380,380],"valid"],[[381,381],"mapped",[382]],[[382,382],"valid"],[[383,383],"mapped",[115]],[[384,384],"valid"],[[385,385],"mapped",[595]],[[386,386],"mapped",[387]],[[387,387],"valid"],[[388,388],"mapped",[389]],[[389,389],"valid"],[[390,390],"mapped",[596]],[[391,391],"mapped",[392]],[[392,392],"valid"],[[393,393],"mapped",[598]],[[394,394],"mapped",[599]],[[395,395],"mapped",[396]],[[396,397],"valid"],[[398,398],"mapped",[477]],[[399,399],"mapped",[601]],[[400,400],"mapped",[603]],[[401,401],"mapped",[402]],[[402,402],"valid"],[[403,403],"mapped",[608]],[[404,404],"mapped",[611]],[[405,405],"valid"],[[406,406],"mapped",[617]],[[407,407],"mapped",[616]],[[408,408],"mapped",[409]],[[409,411],"valid"],[[412,412],"mapped",[623]],[[413,413],"mapped",[626]],[[414,414],"valid"],[[415,415],"mapped",[629]],[[416,416],"mapped",[417]],[[417,417],"valid"],[[418,418],"mapped",[419]],[[419,419],"valid"],[[420,420],"mapped",[421]],[[421,421],"valid"],[[422,422],"mapped",[640]],[[423,423],"mapped",[424]],[[424,424],"valid"],[[425,425],"mapped",[643]],[[426,427],"valid"],[[428,428],"mapped",[429]],[[429,429],"valid"],[[430,430],"mapped",[648]],[[431,431],"mapped",[432]],[[432,432],"valid"],[[433,433],"mapped",[650]],[[434,434],"mapped",[651]],[[435,435],"mapped",[436]],[[436,436],"valid"],[[437,437],"mapped",[438]],[[438,438],"valid"],[[439,439],"mapped",[658]],[[440,440],"mapped",[441]],[[441,443],"valid"],[[444,444],"mapped",[445]],[[445,451],"valid"],[[452,454],"mapped",[100,382]],[[455,457],"mapped",[108,106]],[[458,460],"mapped",[110,106]],[[461,461],"mapped",[462]],[[462,462],"valid"],[[463,463],"mapped",[464]],[[464,464],"valid"],[[465,465],"mapped",[466]],[[466,466],"valid"],[[467,467],"mapped",[468]],[[468,468],"valid"],[[469,469],"mapped",[470]],[[470,470],"valid"],[[471,471],"mapped",[472]],[[472,472],"valid"],[[473,473],"mapped",[474]],[[474,474],"valid"],[[475,475],"mapped",[476]],[[476,477],"valid"],[[478,478],"mapped",[479]],[[479,479],"valid"],[[480,480],"mapped",[481]],[[481,481],"valid"],[[482,482],"mapped",[483]],[[483,483],"valid"],[[484,484],"mapped",[485]],[[485,485],"valid"],[[486,486],"mapped",[487]],[[487,487],"valid"],[[488,488],"mapped",[489]],[[489,489],"valid"],[[490,490],"mapped",[491]],[[491,491],"valid"],[[492,492],"mapped",[493]],[[493,493],"valid"],[[494,494],"mapped",[495]],[[495,496],"valid"],[[497,499],"mapped",[100,122]],[[500,500],"mapped",[501]],[[501,501],"valid"],[[502,502],"mapped",[405]],[[503,503],"mapped",[447]],[[504,504],"mapped",[505]],[[505,505],"valid"],[[506,506],"mapped",[507]],[[507,507],"valid"],[[508,508],"mapped",[509]],[[509,509],"valid"],[[510,510],"mapped",[511]],[[511,511],"valid"],[[512,512],"mapped",[513]],[[513,513],"valid"],[[514,514],"mapped",[515]],[[515,515],"valid"],[[516,516],"mapped",[517]],[[517,517],"valid"],[[518,518],"mapped",[519]],[[519,519],"valid"],[[520,520],"mapped",[521]],[[521,521],"valid"],[[522,522],"mapped",[523]],[[523,523],"valid"],[[524,524],"mapped",[525]],[[525,525],"valid"],[[526,526],"mapped",[527]],[[527,527],"valid"],[[528,528],"mapped",[529]],[[529,529],"valid"],[[530,530],"mapped",[531]],[[531,531],"valid"],[[532,532],"mapped",[533]],[[533,533],"valid"],[[534,534],"mapped",[535]],[[535,535],"valid"],[[536,536],"mapped",[537]],[[537,537],"valid"],[[538,538],"mapped",[539]],[[539,539],"valid"],[[540,540],"mapped",[541]],[[541,541],"valid"],[[542,542],"mapped",[543]],[[543,543],"valid"],[[544,544],"mapped",[414]],[[545,545],"valid"],[[546,546],"mapped",[547]],[[547,547],"valid"],[[548,548],"mapped",[549]],[[549,549],"valid"],[[550,550],"mapped",[551]],[[551,551],"valid"],[[552,552],"mapped",[553]],[[553,553],"valid"],[[554,554],"mapped",[555]],[[555,555],"valid"],[[556,556],"mapped",[557]],[[557,557],"valid"],[[558,558],"mapped",[559]],[[559,559],"valid"],[[560,560],"mapped",[561]],[[561,561],"valid"],[[562,562],"mapped",[563]],[[563,563],"valid"],[[564,566],"valid"],[[567,569],"valid"],[[570,570],"mapped",[11365]],[[571,571],"mapped",[572]],[[572,572],"valid"],[[573,573],"mapped",[410]],[[574,574],"mapped",[11366]],[[575,576],"valid"],[[577,577],"mapped",[578]],[[578,578],"valid"],[[579,579],"mapped",[384]],[[580,580],"mapped",[649]],[[581,581],"mapped",[652]],[[582,582],"mapped",[583]],[[583,583],"valid"],[[584,584],"mapped",[585]],[[585,585],"valid"],[[586,586],"mapped",[587]],[[587,587],"valid"],[[588,588],"mapped",[589]],[[589,589],"valid"],[[590,590],"mapped",[591]],[[591,591],"valid"],[[592,680],"valid"],[[681,685],"valid"],[[686,687],"valid"],[[688,688],"mapped",[104]],[[689,689],"mapped",[614]],[[690,690],"mapped",[106]],[[691,691],"mapped",[114]],[[692,692],"mapped",[633]],[[693,693],"mapped",[635]],[[694,694],"mapped",[641]],[[695,695],"mapped",[119]],[[696,696],"mapped",[121]],[[697,705],"valid"],[[706,709],"valid",[],"NV8"],[[710,721],"valid"],[[722,727],"valid",[],"NV8"],[[728,728],"disallowed_STD3_mapped",[32,774]],[[729,729],"disallowed_STD3_mapped",[32,775]],[[730,730],"disallowed_STD3_mapped",[32,778]],[[731,731],"disallowed_STD3_mapped",[32,808]],[[732,732],"disallowed_STD3_mapped",[32,771]],[[733,733],"disallowed_STD3_mapped",[32,779]],[[734,734],"valid",[],"NV8"],[[735,735],"valid",[],"NV8"],[[736,736],"mapped",[611]],[[737,737],"mapped",[108]],[[738,738],"mapped",[115]],[[739,739],"mapped",[120]],[[740,740],"mapped",[661]],[[741,745],"valid",[],"NV8"],[[746,747],"valid",[],"NV8"],[[748,748],"valid"],[[749,749],"valid",[],"NV8"],[[750,750],"valid"],[[751,767],"valid",[],"NV8"],[[768,831],"valid"],[[832,832],"mapped",[768]],[[833,833],"mapped",[769]],[[834,834],"valid"],[[835,835],"mapped",[787]],[[836,836],"mapped",[776,769]],[[837,837],"mapped",[953]],[[838,846],"valid"],[[847,847],"ignored"],[[848,855],"valid"],[[856,860],"valid"],[[861,863],"valid"],[[864,865],"valid"],[[866,866],"valid"],[[867,879],"valid"],[[880,880],"mapped",[881]],[[881,881],"valid"],[[882,882],"mapped",[883]],[[883,883],"valid"],[[884,884],"mapped",[697]],[[885,885],"valid"],[[886,886],"mapped",[887]],[[887,887],"valid"],[[888,889],"disallowed"],[[890,890],"disallowed_STD3_mapped",[32,953]],[[891,893],"valid"],[[894,894],"disallowed_STD3_mapped",[59]],[[895,895],"mapped",[1011]],[[896,899],"disallowed"],[[900,900],"disallowed_STD3_mapped",[32,769]],[[901,901],"disallowed_STD3_mapped",[32,776,769]],[[902,902],"mapped",[940]],[[903,903],"mapped",[183]],[[904,904],"mapped",[941]],[[905,905],"mapped",[942]],[[906,906],"mapped",[943]],[[907,907],"disallowed"],[[908,908],"mapped",[972]],[[909,909],"disallowed"],[[910,910],"mapped",[973]],[[911,911],"mapped",[974]],[[912,912],"valid"],[[913,913],"mapped",[945]],[[914,914],"mapped",[946]],[[915,915],"mapped",[947]],[[916,916],"mapped",[948]],[[917,917],"mapped",[949]],[[918,918],"mapped",[950]],[[919,919],"mapped",[951]],[[920,920],"mapped",[952]],[[921,921],"mapped",[953]],[[922,922],"mapped",[954]],[[923,923],"mapped",[955]],[[924,924],"mapped",[956]],[[925,925],"mapped",[957]],[[926,926],"mapped",[958]],[[927,927],"mapped",[959]],[[928,928],"mapped",[960]],[[929,929],"mapped",[961]],[[930,930],"disallowed"],[[931,931],"mapped",[963]],[[932,932],"mapped",[964]],[[933,933],"mapped",[965]],[[934,934],"mapped",[966]],[[935,935],"mapped",[967]],[[936,936],"mapped",[968]],[[937,937],"mapped",[969]],[[938,938],"mapped",[970]],[[939,939],"mapped",[971]],[[940,961],"valid"],[[962,962],"deviation",[963]],[[963,974],"valid"],[[975,975],"mapped",[983]],[[976,976],"mapped",[946]],[[977,977],"mapped",[952]],[[978,978],"mapped",[965]],[[979,979],"mapped",[973]],[[980,980],"mapped",[971]],[[981,981],"mapped",[966]],[[982,982],"mapped",[960]],[[983,983],"valid"],[[984,984],"mapped",[985]],[[985,985],"valid"],[[986,986],"mapped",[987]],[[987,987],"valid"],[[988,988],"mapped",[989]],[[989,989],"valid"],[[990,990],"mapped",[991]],[[991,991],"valid"],[[992,992],"mapped",[993]],[[993,993],"valid"],[[994,994],"mapped",[995]],[[995,995],"valid"],[[996,996],"mapped",[997]],[[997,997],"valid"],[[998,998],"mapped",[999]],[[999,999],"valid"],[[1000,1000],"mapped",[1001]],[[1001,1001],"valid"],[[1002,1002],"mapped",[1003]],[[1003,1003],"valid"],[[1004,1004],"mapped",[1005]],[[1005,1005],"valid"],[[1006,1006],"mapped",[1007]],[[1007,1007],"valid"],[[1008,1008],"mapped",[954]],[[1009,1009],"mapped",[961]],[[1010,1010],"mapped",[963]],[[1011,1011],"valid"],[[1012,1012],"mapped",[952]],[[1013,1013],"mapped",[949]],[[1014,1014],"valid",[],"NV8"],[[1015,1015],"mapped",[1016]],[[1016,1016],"valid"],[[1017,1017],"mapped",[963]],[[1018,1018],"mapped",[1019]],[[1019,1019],"valid"],[[1020,1020],"valid"],[[1021,1021],"mapped",[891]],[[1022,1022],"mapped",[892]],[[1023,1023],"mapped",[893]],[[1024,1024],"mapped",[1104]],[[1025,1025],"mapped",[1105]],[[1026,1026],"mapped",[1106]],[[1027,1027],"mapped",[1107]],[[1028,1028],"mapped",[1108]],[[1029,1029],"mapped",[1109]],[[1030,1030],"mapped",[1110]],[[1031,1031],"mapped",[1111]],[[1032,1032],"mapped",[1112]],[[1033,1033],"mapped",[1113]],[[1034,1034],"mapped",[1114]],[[1035,1035],"mapped",[1115]],[[1036,1036],"mapped",[1116]],[[1037,1037],"mapped",[1117]],[[1038,1038],"mapped",[1118]],[[1039,1039],"mapped",[1119]],[[1040,1040],"mapped",[1072]],[[1041,1041],"mapped",[1073]],[[1042,1042],"mapped",[1074]],[[1043,1043],"mapped",[1075]],[[1044,1044],"mapped",[1076]],[[1045,1045],"mapped",[1077]],[[1046,1046],"mapped",[1078]],[[1047,1047],"mapped",[1079]],[[1048,1048],"mapped",[1080]],[[1049,1049],"mapped",[1081]],[[1050,1050],"mapped",[1082]],[[1051,1051],"mapped",[1083]],[[1052,1052],"mapped",[1084]],[[1053,1053],"mapped",[1085]],[[1054,1054],"mapped",[1086]],[[1055,1055],"mapped",[1087]],[[1056,1056],"mapped",[1088]],[[1057,1057],"mapped",[1089]],[[1058,1058],"mapped",[1090]],[[1059,1059],"mapped",[1091]],[[1060,1060],"mapped",[1092]],[[1061,1061],"mapped",[1093]],[[1062,1062],"mapped",[1094]],[[1063,1063],"mapped",[1095]],[[1064,1064],"mapped",[1096]],[[1065,1065],"mapped",[1097]],[[1066,1066],"mapped",[1098]],[[1067,1067],"mapped",[1099]],[[1068,1068],"mapped",[1100]],[[1069,1069],"mapped",[1101]],[[1070,1070],"mapped",[1102]],[[1071,1071],"mapped",[1103]],[[1072,1103],"valid"],[[1104,1104],"valid"],[[1105,1116],"valid"],[[1117,1117],"valid"],[[1118,1119],"valid"],[[1120,1120],"mapped",[1121]],[[1121,1121],"valid"],[[1122,1122],"mapped",[1123]],[[1123,1123],"valid"],[[1124,1124],"mapped",[1125]],[[1125,1125],"valid"],[[1126,1126],"mapped",[1127]],[[1127,1127],"valid"],[[1128,1128],"mapped",[1129]],[[1129,1129],"valid"],[[1130,1130],"mapped",[1131]],[[1131,1131],"valid"],[[1132,1132],"mapped",[1133]],[[1133,1133],"valid"],[[1134,1134],"mapped",[1135]],[[1135,1135],"valid"],[[1136,1136],"mapped",[1137]],[[1137,1137],"valid"],[[1138,1138],"mapped",[1139]],[[1139,1139],"valid"],[[1140,1140],"mapped",[1141]],[[1141,1141],"valid"],[[1142,1142],"mapped",[1143]],[[1143,1143],"valid"],[[1144,1144],"mapped",[1145]],[[1145,1145],"valid"],[[1146,1146],"mapped",[1147]],[[1147,1147],"valid"],[[1148,1148],"mapped",[1149]],[[1149,1149],"valid"],[[1150,1150],"mapped",[1151]],[[1151,1151],"valid"],[[1152,1152],"mapped",[1153]],[[1153,1153],"valid"],[[1154,1154],"valid",[],"NV8"],[[1155,1158],"valid"],[[1159,1159],"valid"],[[1160,1161],"valid",[],"NV8"],[[1162,1162],"mapped",[1163]],[[1163,1163],"valid"],[[1164,1164],"mapped",[1165]],[[1165,1165],"valid"],[[1166,1166],"mapped",[1167]],[[1167,1167],"valid"],[[1168,1168],"mapped",[1169]],[[1169,1169],"valid"],[[1170,1170],"mapped",[1171]],[[1171,1171],"valid"],[[1172,1172],"mapped",[1173]],[[1173,1173],"valid"],[[1174,1174],"mapped",[1175]],[[1175,1175],"valid"],[[1176,1176],"mapped",[1177]],[[1177,1177],"valid"],[[1178,1178],"mapped",[1179]],[[1179,1179],"valid"],[[1180,1180],"mapped",[1181]],[[1181,1181],"valid"],[[1182,1182],"mapped",[1183]],[[1183,1183],"valid"],[[1184,1184],"mapped",[1185]],[[1185,1185],"valid"],[[1186,1186],"mapped",[1187]],[[1187,1187],"valid"],[[1188,1188],"mapped",[1189]],[[1189,1189],"valid"],[[1190,1190],"mapped",[1191]],[[1191,1191],"valid"],[[1192,1192],"mapped",[1193]],[[1193,1193],"valid"],[[1194,1194],"mapped",[1195]],[[1195,1195],"valid"],[[1196,1196],"mapped",[1197]],[[1197,1197],"valid"],[[1198,1198],"mapped",[1199]],[[1199,1199],"valid"],[[1200,1200],"mapped",[1201]],[[1201,1201],"valid"],[[1202,1202],"mapped",[1203]],[[1203,1203],"valid"],[[1204,1204],"mapped",[1205]],[[1205,1205],"valid"],[[1206,1206],"mapped",[1207]],[[1207,1207],"valid"],[[1208,1208],"mapped",[1209]],[[1209,1209],"valid"],[[1210,1210],"mapped",[1211]],[[1211,1211],"valid"],[[1212,1212],"mapped",[1213]],[[1213,1213],"valid"],[[1214,1214],"mapped",[1215]],[[1215,1215],"valid"],[[1216,1216],"disallowed"],[[1217,1217],"mapped",[1218]],[[1218,1218],"valid"],[[1219,1219],"mapped",[1220]],[[1220,1220],"valid"],[[1221,1221],"mapped",[1222]],[[1222,1222],"valid"],[[1223,1223],"mapped",[1224]],[[1224,1224],"valid"],[[1225,1225],"mapped",[1226]],[[1226,1226],"valid"],[[1227,1227],"mapped",[1228]],[[1228,1228],"valid"],[[1229,1229],"mapped",[1230]],[[1230,1230],"valid"],[[1231,1231],"valid"],[[1232,1232],"mapped",[1233]],[[1233,1233],"valid"],[[1234,1234],"mapped",[1235]],[[1235,1235],"valid"],[[1236,1236],"mapped",[1237]],[[1237,1237],"valid"],[[1238,1238],"mapped",[1239]],[[1239,1239],"valid"],[[1240,1240],"mapped",[1241]],[[1241,1241],"valid"],[[1242,1242],"mapped",[1243]],[[1243,1243],"valid"],[[1244,1244],"mapped",[1245]],[[1245,1245],"valid"],[[1246,1246],"mapped",[1247]],[[1247,1247],"valid"],[[1248,1248],"mapped",[1249]],[[1249,1249],"valid"],[[1250,1250],"mapped",[1251]],[[1251,1251],"valid"],[[1252,1252],"mapped",[1253]],[[1253,1253],"valid"],[[1254,1254],"mapped",[1255]],[[1255,1255],"valid"],[[1256,1256],"mapped",[1257]],[[1257,1257],"valid"],[[1258,1258],"mapped",[1259]],[[1259,1259],"valid"],[[1260,1260],"mapped",[1261]],[[1261,1261],"valid"],[[1262,1262],"mapped",[1263]],[[1263,1263],"valid"],[[1264,1264],"mapped",[1265]],[[1265,1265],"valid"],[[1266,1266],"mapped",[1267]],[[1267,1267],"valid"],[[1268,1268],"mapped",[1269]],[[1269,1269],"valid"],[[1270,1270],"mapped",[1271]],[[1271,1271],"valid"],[[1272,1272],"mapped",[1273]],[[1273,1273],"valid"],[[1274,1274],"mapped",[1275]],[[1275,1275],"valid"],[[1276,1276],"mapped",[1277]],[[1277,1277],"valid"],[[1278,1278],"mapped",[1279]],[[1279,1279],"valid"],[[1280,1280],"mapped",[1281]],[[1281,1281],"valid"],[[1282,1282],"mapped",[1283]],[[1283,1283],"valid"],[[1284,1284],"mapped",[1285]],[[1285,1285],"valid"],[[1286,1286],"mapped",[1287]],[[1287,1287],"valid"],[[1288,1288],"mapped",[1289]],[[1289,1289],"valid"],[[1290,1290],"mapped",[1291]],[[1291,1291],"valid"],[[1292,1292],"mapped",[1293]],[[1293,1293],"valid"],[[1294,1294],"mapped",[1295]],[[1295,1295],"valid"],[[1296,1296],"mapped",[1297]],[[1297,1297],"valid"],[[1298,1298],"mapped",[1299]],[[1299,1299],"valid"],[[1300,1300],"mapped",[1301]],[[1301,1301],"valid"],[[1302,1302],"mapped",[1303]],[[1303,1303],"valid"],[[1304,1304],"mapped",[1305]],[[1305,1305],"valid"],[[1306,1306],"mapped",[1307]],[[1307,1307],"valid"],[[1308,1308],"mapped",[1309]],[[1309,1309],"valid"],[[1310,1310],"mapped",[1311]],[[1311,1311],"valid"],[[1312,1312],"mapped",[1313]],[[1313,1313],"valid"],[[1314,1314],"mapped",[1315]],[[1315,1315],"valid"],[[1316,1316],"mapped",[1317]],[[1317,1317],"valid"],[[1318,1318],"mapped",[1319]],[[1319,1319],"valid"],[[1320,1320],"mapped",[1321]],[[1321,1321],"valid"],[[1322,1322],"mapped",[1323]],[[1323,1323],"valid"],[[1324,1324],"mapped",[1325]],[[1325,1325],"valid"],[[1326,1326],"mapped",[1327]],[[1327,1327],"valid"],[[1328,1328],"disallowed"],[[1329,1329],"mapped",[1377]],[[1330,1330],"mapped",[1378]],[[1331,1331],"mapped",[1379]],[[1332,1332],"mapped",[1380]],[[1333,1333],"mapped",[1381]],[[1334,1334],"mapped",[1382]],[[1335,1335],"mapped",[1383]],[[1336,1336],"mapped",[1384]],[[1337,1337],"mapped",[1385]],[[1338,1338],"mapped",[1386]],[[1339,1339],"mapped",[1387]],[[1340,1340],"mapped",[1388]],[[1341,1341],"mapped",[1389]],[[1342,1342],"mapped",[1390]],[[1343,1343],"mapped",[1391]],[[1344,1344],"mapped",[1392]],[[1345,1345],"mapped",[1393]],[[1346,1346],"mapped",[1394]],[[1347,1347],"mapped",[1395]],[[1348,1348],"mapped",[1396]],[[1349,1349],"mapped",[1397]],[[1350,1350],"mapped",[1398]],[[1351,1351],"mapped",[1399]],[[1352,1352],"mapped",[1400]],[[1353,1353],"mapped",[1401]],[[1354,1354],"mapped",[1402]],[[1355,1355],"mapped",[1403]],[[1356,1356],"mapped",[1404]],[[1357,1357],"mapped",[1405]],[[1358,1358],"mapped",[1406]],[[1359,1359],"mapped",[1407]],[[1360,1360],"mapped",[1408]],[[1361,1361],"mapped",[1409]],[[1362,1362],"mapped",[1410]],[[1363,1363],"mapped",[1411]],[[1364,1364],"mapped",[1412]],[[1365,1365],"mapped",[1413]],[[1366,1366],"mapped",[1414]],[[1367,1368],"disallowed"],[[1369,1369],"valid"],[[1370,1375],"valid",[],"NV8"],[[1376,1376],"disallowed"],[[1377,1414],"valid"],[[1415,1415],"mapped",[1381,1410]],[[1416,1416],"disallowed"],[[1417,1417],"valid",[],"NV8"],[[1418,1418],"valid",[],"NV8"],[[1419,1420],"disallowed"],[[1421,1422],"valid",[],"NV8"],[[1423,1423],"valid",[],"NV8"],[[1424,1424],"disallowed"],[[1425,1441],"valid"],[[1442,1442],"valid"],[[1443,1455],"valid"],[[1456,1465],"valid"],[[1466,1466],"valid"],[[1467,1469],"valid"],[[1470,1470],"valid",[],"NV8"],[[1471,1471],"valid"],[[1472,1472],"valid",[],"NV8"],[[1473,1474],"valid"],[[1475,1475],"valid",[],"NV8"],[[1476,1476],"valid"],[[1477,1477],"valid"],[[1478,1478],"valid",[],"NV8"],[[1479,1479],"valid"],[[1480,1487],"disallowed"],[[1488,1514],"valid"],[[1515,1519],"disallowed"],[[1520,1524],"valid"],[[1525,1535],"disallowed"],[[1536,1539],"disallowed"],[[1540,1540],"disallowed"],[[1541,1541],"disallowed"],[[1542,1546],"valid",[],"NV8"],[[1547,1547],"valid",[],"NV8"],[[1548,1548],"valid",[],"NV8"],[[1549,1551],"valid",[],"NV8"],[[1552,1557],"valid"],[[1558,1562],"valid"],[[1563,1563],"valid",[],"NV8"],[[1564,1564],"disallowed"],[[1565,1565],"disallowed"],[[1566,1566],"valid",[],"NV8"],[[1567,1567],"valid",[],"NV8"],[[1568,1568],"valid"],[[1569,1594],"valid"],[[1595,1599],"valid"],[[1600,1600],"valid",[],"NV8"],[[1601,1618],"valid"],[[1619,1621],"valid"],[[1622,1624],"valid"],[[1625,1630],"valid"],[[1631,1631],"valid"],[[1632,1641],"valid"],[[1642,1645],"valid",[],"NV8"],[[1646,1647],"valid"],[[1648,1652],"valid"],[[1653,1653],"mapped",[1575,1652]],[[1654,1654],"mapped",[1608,1652]],[[1655,1655],"mapped",[1735,1652]],[[1656,1656],"mapped",[1610,1652]],[[1657,1719],"valid"],[[1720,1721],"valid"],[[1722,1726],"valid"],[[1727,1727],"valid"],[[1728,1742],"valid"],[[1743,1743],"valid"],[[1744,1747],"valid"],[[1748,1748],"valid",[],"NV8"],[[1749,1756],"valid"],[[1757,1757],"disallowed"],[[1758,1758],"valid",[],"NV8"],[[1759,1768],"valid"],[[1769,1769],"valid",[],"NV8"],[[1770,1773],"valid"],[[1774,1775],"valid"],[[1776,1785],"valid"],[[1786,1790],"valid"],[[1791,1791],"valid"],[[1792,1805],"valid",[],"NV8"],[[1806,1806],"disallowed"],[[1807,1807],"disallowed"],[[1808,1836],"valid"],[[1837,1839],"valid"],[[1840,1866],"valid"],[[1867,1868],"disallowed"],[[1869,1871],"valid"],[[1872,1901],"valid"],[[1902,1919],"valid"],[[1920,1968],"valid"],[[1969,1969],"valid"],[[1970,1983],"disallowed"],[[1984,2037],"valid"],[[2038,2042],"valid",[],"NV8"],[[2043,2047],"disallowed"],[[2048,2093],"valid"],[[2094,2095],"disallowed"],[[2096,2110],"valid",[],"NV8"],[[2111,2111],"disallowed"],[[2112,2139],"valid"],[[2140,2141],"disallowed"],[[2142,2142],"valid",[],"NV8"],[[2143,2207],"disallowed"],[[2208,2208],"valid"],[[2209,2209],"valid"],[[2210,2220],"valid"],[[2221,2226],"valid"],[[2227,2228],"valid"],[[2229,2274],"disallowed"],[[2275,2275],"valid"],[[2276,2302],"valid"],[[2303,2303],"valid"],[[2304,2304],"valid"],[[2305,2307],"valid"],[[2308,2308],"valid"],[[2309,2361],"valid"],[[2362,2363],"valid"],[[2364,2381],"valid"],[[2382,2382],"valid"],[[2383,2383],"valid"],[[2384,2388],"valid"],[[2389,2389],"valid"],[[2390,2391],"valid"],[[2392,2392],"mapped",[2325,2364]],[[2393,2393],"mapped",[2326,2364]],[[2394,2394],"mapped",[2327,2364]],[[2395,2395],"mapped",[2332,2364]],[[2396,2396],"mapped",[2337,2364]],[[2397,2397],"mapped",[2338,2364]],[[2398,2398],"mapped",[2347,2364]],[[2399,2399],"mapped",[2351,2364]],[[2400,2403],"valid"],[[2404,2405],"valid",[],"NV8"],[[2406,2415],"valid"],[[2416,2416],"valid",[],"NV8"],[[2417,2418],"valid"],[[2419,2423],"valid"],[[2424,2424],"valid"],[[2425,2426],"valid"],[[2427,2428],"valid"],[[2429,2429],"valid"],[[2430,2431],"valid"],[[2432,2432],"valid"],[[2433,2435],"valid"],[[2436,2436],"disallowed"],[[2437,2444],"valid"],[[2445,2446],"disallowed"],[[2447,2448],"valid"],[[2449,2450],"disallowed"],[[2451,2472],"valid"],[[2473,2473],"disallowed"],[[2474,2480],"valid"],[[2481,2481],"disallowed"],[[2482,2482],"valid"],[[2483,2485],"disallowed"],[[2486,2489],"valid"],[[2490,2491],"disallowed"],[[2492,2492],"valid"],[[2493,2493],"valid"],[[2494,2500],"valid"],[[2501,2502],"disallowed"],[[2503,2504],"valid"],[[2505,2506],"disallowed"],[[2507,2509],"valid"],[[2510,2510],"valid"],[[2511,2518],"disallowed"],[[2519,2519],"valid"],[[2520,2523],"disallowed"],[[2524,2524],"mapped",[2465,2492]],[[2525,2525],"mapped",[2466,2492]],[[2526,2526],"disallowed"],[[2527,2527],"mapped",[2479,2492]],[[2528,2531],"valid"],[[2532,2533],"disallowed"],[[2534,2545],"valid"],[[2546,2554],"valid",[],"NV8"],[[2555,2555],"valid",[],"NV8"],[[2556,2560],"disallowed"],[[2561,2561],"valid"],[[2562,2562],"valid"],[[2563,2563],"valid"],[[2564,2564],"disallowed"],[[2565,2570],"valid"],[[2571,2574],"disallowed"],[[2575,2576],"valid"],[[2577,2578],"disallowed"],[[2579,2600],"valid"],[[2601,2601],"disallowed"],[[2602,2608],"valid"],[[2609,2609],"disallowed"],[[2610,2610],"valid"],[[2611,2611],"mapped",[2610,2620]],[[2612,2612],"disallowed"],[[2613,2613],"valid"],[[2614,2614],"mapped",[2616,2620]],[[2615,2615],"disallowed"],[[2616,2617],"valid"],[[2618,2619],"disallowed"],[[2620,2620],"valid"],[[2621,2621],"disallowed"],[[2622,2626],"valid"],[[2627,2630],"disallowed"],[[2631,2632],"valid"],[[2633,2634],"disallowed"],[[2635,2637],"valid"],[[2638,2640],"disallowed"],[[2641,2641],"valid"],[[2642,2648],"disallowed"],[[2649,2649],"mapped",[2582,2620]],[[2650,2650],"mapped",[2583,2620]],[[2651,2651],"mapped",[2588,2620]],[[2652,2652],"valid"],[[2653,2653],"disallowed"],[[2654,2654],"mapped",[2603,2620]],[[2655,2661],"disallowed"],[[2662,2676],"valid"],[[2677,2677],"valid"],[[2678,2688],"disallowed"],[[2689,2691],"valid"],[[2692,2692],"disallowed"],[[2693,2699],"valid"],[[2700,2700],"valid"],[[2701,2701],"valid"],[[2702,2702],"disallowed"],[[2703,2705],"valid"],[[2706,2706],"disallowed"],[[2707,2728],"valid"],[[2729,2729],"disallowed"],[[2730,2736],"valid"],[[2737,2737],"disallowed"],[[2738,2739],"valid"],[[2740,2740],"disallowed"],[[2741,2745],"valid"],[[2746,2747],"disallowed"],[[2748,2757],"valid"],[[2758,2758],"disallowed"],[[2759,2761],"valid"],[[2762,2762],"disallowed"],[[2763,2765],"valid"],[[2766,2767],"disallowed"],[[2768,2768],"valid"],[[2769,2783],"disallowed"],[[2784,2784],"valid"],[[2785,2787],"valid"],[[2788,2789],"disallowed"],[[2790,2799],"valid"],[[2800,2800],"valid",[],"NV8"],[[2801,2801],"valid",[],"NV8"],[[2802,2808],"disallowed"],[[2809,2809],"valid"],[[2810,2816],"disallowed"],[[2817,2819],"valid"],[[2820,2820],"disallowed"],[[2821,2828],"valid"],[[2829,2830],"disallowed"],[[2831,2832],"valid"],[[2833,2834],"disallowed"],[[2835,2856],"valid"],[[2857,2857],"disallowed"],[[2858,2864],"valid"],[[2865,2865],"disallowed"],[[2866,2867],"valid"],[[2868,2868],"disallowed"],[[2869,2869],"valid"],[[2870,2873],"valid"],[[2874,2875],"disallowed"],[[2876,2883],"valid"],[[2884,2884],"valid"],[[2885,2886],"disallowed"],[[2887,2888],"valid"],[[2889,2890],"disallowed"],[[2891,2893],"valid"],[[2894,2901],"disallowed"],[[2902,2903],"valid"],[[2904,2907],"disallowed"],[[2908,2908],"mapped",[2849,2876]],[[2909,2909],"mapped",[2850,2876]],[[2910,2910],"disallowed"],[[2911,2913],"valid"],[[2914,2915],"valid"],[[2916,2917],"disallowed"],[[2918,2927],"valid"],[[2928,2928],"valid",[],"NV8"],[[2929,2929],"valid"],[[2930,2935],"valid",[],"NV8"],[[2936,2945],"disallowed"],[[2946,2947],"valid"],[[2948,2948],"disallowed"],[[2949,2954],"valid"],[[2955,2957],"disallowed"],[[2958,2960],"valid"],[[2961,2961],"disallowed"],[[2962,2965],"valid"],[[2966,2968],"disallowed"],[[2969,2970],"valid"],[[2971,2971],"disallowed"],[[2972,2972],"valid"],[[2973,2973],"disallowed"],[[2974,2975],"valid"],[[2976,2978],"disallowed"],[[2979,2980],"valid"],[[2981,2983],"disallowed"],[[2984,2986],"valid"],[[2987,2989],"disallowed"],[[2990,2997],"valid"],[[2998,2998],"valid"],[[2999,3001],"valid"],[[3002,3005],"disallowed"],[[3006,3010],"valid"],[[3011,3013],"disallowed"],[[3014,3016],"valid"],[[3017,3017],"disallowed"],[[3018,3021],"valid"],[[3022,3023],"disallowed"],[[3024,3024],"valid"],[[3025,3030],"disallowed"],[[3031,3031],"valid"],[[3032,3045],"disallowed"],[[3046,3046],"valid"],[[3047,3055],"valid"],[[3056,3058],"valid",[],"NV8"],[[3059,3066],"valid",[],"NV8"],[[3067,3071],"disallowed"],[[3072,3072],"valid"],[[3073,3075],"valid"],[[3076,3076],"disallowed"],[[3077,3084],"valid"],[[3085,3085],"disallowed"],[[3086,3088],"valid"],[[3089,3089],"disallowed"],[[3090,3112],"valid"],[[3113,3113],"disallowed"],[[3114,3123],"valid"],[[3124,3124],"valid"],[[3125,3129],"valid"],[[3130,3132],"disallowed"],[[3133,3133],"valid"],[[3134,3140],"valid"],[[3141,3141],"disallowed"],[[3142,3144],"valid"],[[3145,3145],"disallowed"],[[3146,3149],"valid"],[[3150,3156],"disallowed"],[[3157,3158],"valid"],[[3159,3159],"disallowed"],[[3160,3161],"valid"],[[3162,3162],"valid"],[[3163,3167],"disallowed"],[[3168,3169],"valid"],[[3170,3171],"valid"],[[3172,3173],"disallowed"],[[3174,3183],"valid"],[[3184,3191],"disallowed"],[[3192,3199],"valid",[],"NV8"],[[3200,3200],"disallowed"],[[3201,3201],"valid"],[[3202,3203],"valid"],[[3204,3204],"disallowed"],[[3205,3212],"valid"],[[3213,3213],"disallowed"],[[3214,3216],"valid"],[[3217,3217],"disallowed"],[[3218,3240],"valid"],[[3241,3241],"disallowed"],[[3242,3251],"valid"],[[3252,3252],"disallowed"],[[3253,3257],"valid"],[[3258,3259],"disallowed"],[[3260,3261],"valid"],[[3262,3268],"valid"],[[3269,3269],"disallowed"],[[3270,3272],"valid"],[[3273,3273],"disallowed"],[[3274,3277],"valid"],[[3278,3284],"disallowed"],[[3285,3286],"valid"],[[3287,3293],"disallowed"],[[3294,3294],"valid"],[[3295,3295],"disallowed"],[[3296,3297],"valid"],[[3298,3299],"valid"],[[3300,3301],"disallowed"],[[3302,3311],"valid"],[[3312,3312],"disallowed"],[[3313,3314],"valid"],[[3315,3328],"disallowed"],[[3329,3329],"valid"],[[3330,3331],"valid"],[[3332,3332],"disallowed"],[[3333,3340],"valid"],[[3341,3341],"disallowed"],[[3342,3344],"valid"],[[3345,3345],"disallowed"],[[3346,3368],"valid"],[[3369,3369],"valid"],[[3370,3385],"valid"],[[3386,3386],"valid"],[[3387,3388],"disallowed"],[[3389,3389],"valid"],[[3390,3395],"valid"],[[3396,3396],"valid"],[[3397,3397],"disallowed"],[[3398,3400],"valid"],[[3401,3401],"disallowed"],[[3402,3405],"valid"],[[3406,3406],"valid"],[[3407,3414],"disallowed"],[[3415,3415],"valid"],[[3416,3422],"disallowed"],[[3423,3423],"valid"],[[3424,3425],"valid"],[[3426,3427],"valid"],[[3428,3429],"disallowed"],[[3430,3439],"valid"],[[3440,3445],"valid",[],"NV8"],[[3446,3448],"disallowed"],[[3449,3449],"valid",[],"NV8"],[[3450,3455],"valid"],[[3456,3457],"disallowed"],[[3458,3459],"valid"],[[3460,3460],"disallowed"],[[3461,3478],"valid"],[[3479,3481],"disallowed"],[[3482,3505],"valid"],[[3506,3506],"disallowed"],[[3507,3515],"valid"],[[3516,3516],"disallowed"],[[3517,3517],"valid"],[[3518,3519],"disallowed"],[[3520,3526],"valid"],[[3527,3529],"disallowed"],[[3530,3530],"valid"],[[3531,3534],"disallowed"],[[3535,3540],"valid"],[[3541,3541],"disallowed"],[[3542,3542],"valid"],[[3543,3543],"disallowed"],[[3544,3551],"valid"],[[3552,3557],"disallowed"],[[3558,3567],"valid"],[[3568,3569],"disallowed"],[[3570,3571],"valid"],[[3572,3572],"valid",[],"NV8"],[[3573,3584],"disallowed"],[[3585,3634],"valid"],[[3635,3635],"mapped",[3661,3634]],[[3636,3642],"valid"],[[3643,3646],"disallowed"],[[3647,3647],"valid",[],"NV8"],[[3648,3662],"valid"],[[3663,3663],"valid",[],"NV8"],[[3664,3673],"valid"],[[3674,3675],"valid",[],"NV8"],[[3676,3712],"disallowed"],[[3713,3714],"valid"],[[3715,3715],"disallowed"],[[3716,3716],"valid"],[[3717,3718],"disallowed"],[[3719,3720],"valid"],[[3721,3721],"disallowed"],[[3722,3722],"valid"],[[3723,3724],"disallowed"],[[3725,3725],"valid"],[[3726,3731],"disallowed"],[[3732,3735],"valid"],[[3736,3736],"disallowed"],[[3737,3743],"valid"],[[3744,3744],"disallowed"],[[3745,3747],"valid"],[[3748,3748],"disallowed"],[[3749,3749],"valid"],[[3750,3750],"disallowed"],[[3751,3751],"valid"],[[3752,3753],"disallowed"],[[3754,3755],"valid"],[[3756,3756],"disallowed"],[[3757,3762],"valid"],[[3763,3763],"mapped",[3789,3762]],[[3764,3769],"valid"],[[3770,3770],"disallowed"],[[3771,3773],"valid"],[[3774,3775],"disallowed"],[[3776,3780],"valid"],[[3781,3781],"disallowed"],[[3782,3782],"valid"],[[3783,3783],"disallowed"],[[3784,3789],"valid"],[[3790,3791],"disallowed"],[[3792,3801],"valid"],[[3802,3803],"disallowed"],[[3804,3804],"mapped",[3755,3737]],[[3805,3805],"mapped",[3755,3745]],[[3806,3807],"valid"],[[3808,3839],"disallowed"],[[3840,3840],"valid"],[[3841,3850],"valid",[],"NV8"],[[3851,3851],"valid"],[[3852,3852],"mapped",[3851]],[[3853,3863],"valid",[],"NV8"],[[3864,3865],"valid"],[[3866,3871],"valid",[],"NV8"],[[3872,3881],"valid"],[[3882,3892],"valid",[],"NV8"],[[3893,3893],"valid"],[[3894,3894],"valid",[],"NV8"],[[3895,3895],"valid"],[[3896,3896],"valid",[],"NV8"],[[3897,3897],"valid"],[[3898,3901],"valid",[],"NV8"],[[3902,3906],"valid"],[[3907,3907],"mapped",[3906,4023]],[[3908,3911],"valid"],[[3912,3912],"disallowed"],[[3913,3916],"valid"],[[3917,3917],"mapped",[3916,4023]],[[3918,3921],"valid"],[[3922,3922],"mapped",[3921,4023]],[[3923,3926],"valid"],[[3927,3927],"mapped",[3926,4023]],[[3928,3931],"valid"],[[3932,3932],"mapped",[3931,4023]],[[3933,3944],"valid"],[[3945,3945],"mapped",[3904,4021]],[[3946,3946],"valid"],[[3947,3948],"valid"],[[3949,3952],"disallowed"],[[3953,3954],"valid"],[[3955,3955],"mapped",[3953,3954]],[[3956,3956],"valid"],[[3957,3957],"mapped",[3953,3956]],[[3958,3958],"mapped",[4018,3968]],[[3959,3959],"mapped",[4018,3953,3968]],[[3960,3960],"mapped",[4019,3968]],[[3961,3961],"mapped",[4019,3953,3968]],[[3962,3968],"valid"],[[3969,3969],"mapped",[3953,3968]],[[3970,3972],"valid"],[[3973,3973],"valid",[],"NV8"],[[3974,3979],"valid"],[[3980,3983],"valid"],[[3984,3986],"valid"],[[3987,3987],"mapped",[3986,4023]],[[3988,3989],"valid"],[[3990,3990],"valid"],[[3991,3991],"valid"],[[3992,3992],"disallowed"],[[3993,3996],"valid"],[[3997,3997],"mapped",[3996,4023]],[[3998,4001],"valid"],[[4002,4002],"mapped",[4001,4023]],[[4003,4006],"valid"],[[4007,4007],"mapped",[4006,4023]],[[4008,4011],"valid"],[[4012,4012],"mapped",[4011,4023]],[[4013,4013],"valid"],[[4014,4016],"valid"],[[4017,4023],"valid"],[[4024,4024],"valid"],[[4025,4025],"mapped",[3984,4021]],[[4026,4028],"valid"],[[4029,4029],"disallowed"],[[4030,4037],"valid",[],"NV8"],[[4038,4038],"valid"],[[4039,4044],"valid",[],"NV8"],[[4045,4045],"disallowed"],[[4046,4046],"valid",[],"NV8"],[[4047,4047],"valid",[],"NV8"],[[4048,4049],"valid",[],"NV8"],[[4050,4052],"valid",[],"NV8"],[[4053,4056],"valid",[],"NV8"],[[4057,4058],"valid",[],"NV8"],[[4059,4095],"disallowed"],[[4096,4129],"valid"],[[4130,4130],"valid"],[[4131,4135],"valid"],[[4136,4136],"valid"],[[4137,4138],"valid"],[[4139,4139],"valid"],[[4140,4146],"valid"],[[4147,4149],"valid"],[[4150,4153],"valid"],[[4154,4159],"valid"],[[4160,4169],"valid"],[[4170,4175],"valid",[],"NV8"],[[4176,4185],"valid"],[[4186,4249],"valid"],[[4250,4253],"valid"],[[4254,4255],"valid",[],"NV8"],[[4256,4293],"disallowed"],[[4294,4294],"disallowed"],[[4295,4295],"mapped",[11559]],[[4296,4300],"disallowed"],[[4301,4301],"mapped",[11565]],[[4302,4303],"disallowed"],[[4304,4342],"valid"],[[4343,4344],"valid"],[[4345,4346],"valid"],[[4347,4347],"valid",[],"NV8"],[[4348,4348],"mapped",[4316]],[[4349,4351],"valid"],[[4352,4441],"valid",[],"NV8"],[[4442,4446],"valid",[],"NV8"],[[4447,4448],"disallowed"],[[4449,4514],"valid",[],"NV8"],[[4515,4519],"valid",[],"NV8"],[[4520,4601],"valid",[],"NV8"],[[4602,4607],"valid",[],"NV8"],[[4608,4614],"valid"],[[4615,4615],"valid"],[[4616,4678],"valid"],[[4679,4679],"valid"],[[4680,4680],"valid"],[[4681,4681],"disallowed"],[[4682,4685],"valid"],[[4686,4687],"disallowed"],[[4688,4694],"valid"],[[4695,4695],"disallowed"],[[4696,4696],"valid"],[[4697,4697],"disallowed"],[[4698,4701],"valid"],[[4702,4703],"disallowed"],[[4704,4742],"valid"],[[4743,4743],"valid"],[[4744,4744],"valid"],[[4745,4745],"disallowed"],[[4746,4749],"valid"],[[4750,4751],"disallowed"],[[4752,4782],"valid"],[[4783,4783],"valid"],[[4784,4784],"valid"],[[4785,4785],"disallowed"],[[4786,4789],"valid"],[[4790,4791],"disallowed"],[[4792,4798],"valid"],[[4799,4799],"disallowed"],[[4800,4800],"valid"],[[4801,4801],"disallowed"],[[4802,4805],"valid"],[[4806,4807],"disallowed"],[[4808,4814],"valid"],[[4815,4815],"valid"],[[4816,4822],"valid"],[[4823,4823],"disallowed"],[[4824,4846],"valid"],[[4847,4847],"valid"],[[4848,4878],"valid"],[[4879,4879],"valid"],[[4880,4880],"valid"],[[4881,4881],"disallowed"],[[4882,4885],"valid"],[[4886,4887],"disallowed"],[[4888,4894],"valid"],[[4895,4895],"valid"],[[4896,4934],"valid"],[[4935,4935],"valid"],[[4936,4954],"valid"],[[4955,4956],"disallowed"],[[4957,4958],"valid"],[[4959,4959],"valid"],[[4960,4960],"valid",[],"NV8"],[[4961,4988],"valid",[],"NV8"],[[4989,4991],"disallowed"],[[4992,5007],"valid"],[[5008,5017],"valid",[],"NV8"],[[5018,5023],"disallowed"],[[5024,5108],"valid"],[[5109,5109],"valid"],[[5110,5111],"disallowed"],[[5112,5112],"mapped",[5104]],[[5113,5113],"mapped",[5105]],[[5114,5114],"mapped",[5106]],[[5115,5115],"mapped",[5107]],[[5116,5116],"mapped",[5108]],[[5117,5117],"mapped",[5109]],[[5118,5119],"disallowed"],[[5120,5120],"valid",[],"NV8"],[[5121,5740],"valid"],[[5741,5742],"valid",[],"NV8"],[[5743,5750],"valid"],[[5751,5759],"valid"],[[5760,5760],"disallowed"],[[5761,5786],"valid"],[[5787,5788],"valid",[],"NV8"],[[5789,5791],"disallowed"],[[5792,5866],"valid"],[[5867,5872],"valid",[],"NV8"],[[5873,5880],"valid"],[[5881,5887],"disallowed"],[[5888,5900],"valid"],[[5901,5901],"disallowed"],[[5902,5908],"valid"],[[5909,5919],"disallowed"],[[5920,5940],"valid"],[[5941,5942],"valid",[],"NV8"],[[5943,5951],"disallowed"],[[5952,5971],"valid"],[[5972,5983],"disallowed"],[[5984,5996],"valid"],[[5997,5997],"disallowed"],[[5998,6000],"valid"],[[6001,6001],"disallowed"],[[6002,6003],"valid"],[[6004,6015],"disallowed"],[[6016,6067],"valid"],[[6068,6069],"disallowed"],[[6070,6099],"valid"],[[6100,6102],"valid",[],"NV8"],[[6103,6103],"valid"],[[6104,6107],"valid",[],"NV8"],[[6108,6108],"valid"],[[6109,6109],"valid"],[[6110,6111],"disallowed"],[[6112,6121],"valid"],[[6122,6127],"disallowed"],[[6128,6137],"valid",[],"NV8"],[[6138,6143],"disallowed"],[[6144,6149],"valid",[],"NV8"],[[6150,6150],"disallowed"],[[6151,6154],"valid",[],"NV8"],[[6155,6157],"ignored"],[[6158,6158],"disallowed"],[[6159,6159],"disallowed"],[[6160,6169],"valid"],[[6170,6175],"disallowed"],[[6176,6263],"valid"],[[6264,6271],"disallowed"],[[6272,6313],"valid"],[[6314,6314],"valid"],[[6315,6319],"disallowed"],[[6320,6389],"valid"],[[6390,6399],"disallowed"],[[6400,6428],"valid"],[[6429,6430],"valid"],[[6431,6431],"disallowed"],[[6432,6443],"valid"],[[6444,6447],"disallowed"],[[6448,6459],"valid"],[[6460,6463],"disallowed"],[[6464,6464],"valid",[],"NV8"],[[6465,6467],"disallowed"],[[6468,6469],"valid",[],"NV8"],[[6470,6509],"valid"],[[6510,6511],"disallowed"],[[6512,6516],"valid"],[[6517,6527],"disallowed"],[[6528,6569],"valid"],[[6570,6571],"valid"],[[6572,6575],"disallowed"],[[6576,6601],"valid"],[[6602,6607],"disallowed"],[[6608,6617],"valid"],[[6618,6618],"valid",[],"XV8"],[[6619,6621],"disallowed"],[[6622,6623],"valid",[],"NV8"],[[6624,6655],"valid",[],"NV8"],[[6656,6683],"valid"],[[6684,6685],"disallowed"],[[6686,6687],"valid",[],"NV8"],[[6688,6750],"valid"],[[6751,6751],"disallowed"],[[6752,6780],"valid"],[[6781,6782],"disallowed"],[[6783,6793],"valid"],[[6794,6799],"disallowed"],[[6800,6809],"valid"],[[6810,6815],"disallowed"],[[6816,6822],"valid",[],"NV8"],[[6823,6823],"valid"],[[6824,6829],"valid",[],"NV8"],[[6830,6831],"disallowed"],[[6832,6845],"valid"],[[6846,6846],"valid",[],"NV8"],[[6847,6911],"disallowed"],[[6912,6987],"valid"],[[6988,6991],"disallowed"],[[6992,7001],"valid"],[[7002,7018],"valid",[],"NV8"],[[7019,7027],"valid"],[[7028,7036],"valid",[],"NV8"],[[7037,7039],"disallowed"],[[7040,7082],"valid"],[[7083,7085],"valid"],[[7086,7097],"valid"],[[7098,7103],"valid"],[[7104,7155],"valid"],[[7156,7163],"disallowed"],[[7164,7167],"valid",[],"NV8"],[[7168,7223],"valid"],[[7224,7226],"disallowed"],[[7227,7231],"valid",[],"NV8"],[[7232,7241],"valid"],[[7242,7244],"disallowed"],[[7245,7293],"valid"],[[7294,7295],"valid",[],"NV8"],[[7296,7359],"disallowed"],[[7360,7367],"valid",[],"NV8"],[[7368,7375],"disallowed"],[[7376,7378],"valid"],[[7379,7379],"valid",[],"NV8"],[[7380,7410],"valid"],[[7411,7414],"valid"],[[7415,7415],"disallowed"],[[7416,7417],"valid"],[[7418,7423],"disallowed"],[[7424,7467],"valid"],[[7468,7468],"mapped",[97]],[[7469,7469],"mapped",[230]],[[7470,7470],"mapped",[98]],[[7471,7471],"valid"],[[7472,7472],"mapped",[100]],[[7473,7473],"mapped",[101]],[[7474,7474],"mapped",[477]],[[7475,7475],"mapped",[103]],[[7476,7476],"mapped",[104]],[[7477,7477],"mapped",[105]],[[7478,7478],"mapped",[106]],[[7479,7479],"mapped",[107]],[[7480,7480],"mapped",[108]],[[7481,7481],"mapped",[109]],[[7482,7482],"mapped",[110]],[[7483,7483],"valid"],[[7484,7484],"mapped",[111]],[[7485,7485],"mapped",[547]],[[7486,7486],"mapped",[112]],[[7487,7487],"mapped",[114]],[[7488,7488],"mapped",[116]],[[7489,7489],"mapped",[117]],[[7490,7490],"mapped",[119]],[[7491,7491],"mapped",[97]],[[7492,7492],"mapped",[592]],[[7493,7493],"mapped",[593]],[[7494,7494],"mapped",[7426]],[[7495,7495],"mapped",[98]],[[7496,7496],"mapped",[100]],[[7497,7497],"mapped",[101]],[[7498,7498],"mapped",[601]],[[7499,7499],"mapped",[603]],[[7500,7500],"mapped",[604]],[[7501,7501],"mapped",[103]],[[7502,7502],"valid"],[[7503,7503],"mapped",[107]],[[7504,7504],"mapped",[109]],[[7505,7505],"mapped",[331]],[[7506,7506],"mapped",[111]],[[7507,7507],"mapped",[596]],[[7508,7508],"mapped",[7446]],[[7509,7509],"mapped",[7447]],[[7510,7510],"mapped",[112]],[[7511,7511],"mapped",[116]],[[7512,7512],"mapped",[117]],[[7513,7513],"mapped",[7453]],[[7514,7514],"mapped",[623]],[[7515,7515],"mapped",[118]],[[7516,7516],"mapped",[7461]],[[7517,7517],"mapped",[946]],[[7518,7518],"mapped",[947]],[[7519,7519],"mapped",[948]],[[7520,7520],"mapped",[966]],[[7521,7521],"mapped",[967]],[[7522,7522],"mapped",[105]],[[7523,7523],"mapped",[114]],[[7524,7524],"mapped",[117]],[[7525,7525],"mapped",[118]],[[7526,7526],"mapped",[946]],[[7527,7527],"mapped",[947]],[[7528,7528],"mapped",[961]],[[7529,7529],"mapped",[966]],[[7530,7530],"mapped",[967]],[[7531,7531],"valid"],[[7532,7543],"valid"],[[7544,7544],"mapped",[1085]],[[7545,7578],"valid"],[[7579,7579],"mapped",[594]],[[7580,7580],"mapped",[99]],[[7581,7581],"mapped",[597]],[[7582,7582],"mapped",[240]],[[7583,7583],"mapped",[604]],[[7584,7584],"mapped",[102]],[[7585,7585],"mapped",[607]],[[7586,7586],"mapped",[609]],[[7587,7587],"mapped",[613]],[[7588,7588],"mapped",[616]],[[7589,7589],"mapped",[617]],[[7590,7590],"mapped",[618]],[[7591,7591],"mapped",[7547]],[[7592,7592],"mapped",[669]],[[7593,7593],"mapped",[621]],[[7594,7594],"mapped",[7557]],[[7595,7595],"mapped",[671]],[[7596,7596],"mapped",[625]],[[7597,7597],"mapped",[624]],[[7598,7598],"mapped",[626]],[[7599,7599],"mapped",[627]],[[7600,7600],"mapped",[628]],[[7601,7601],"mapped",[629]],[[7602,7602],"mapped",[632]],[[7603,7603],"mapped",[642]],[[7604,7604],"mapped",[643]],[[7605,7605],"mapped",[427]],[[7606,7606],"mapped",[649]],[[7607,7607],"mapped",[650]],[[7608,7608],"mapped",[7452]],[[7609,7609],"mapped",[651]],[[7610,7610],"mapped",[652]],[[7611,7611],"mapped",[122]],[[7612,7612],"mapped",[656]],[[7613,7613],"mapped",[657]],[[7614,7614],"mapped",[658]],[[7615,7615],"mapped",[952]],[[7616,7619],"valid"],[[7620,7626],"valid"],[[7627,7654],"valid"],[[7655,7669],"valid"],[[7670,7675],"disallowed"],[[7676,7676],"valid"],[[7677,7677],"valid"],[[7678,7679],"valid"],[[7680,7680],"mapped",[7681]],[[7681,7681],"valid"],[[7682,7682],"mapped",[7683]],[[7683,7683],"valid"],[[7684,7684],"mapped",[7685]],[[7685,7685],"valid"],[[7686,7686],"mapped",[7687]],[[7687,7687],"valid"],[[7688,7688],"mapped",[7689]],[[7689,7689],"valid"],[[7690,7690],"mapped",[7691]],[[7691,7691],"valid"],[[7692,7692],"mapped",[7693]],[[7693,7693],"valid"],[[7694,7694],"mapped",[7695]],[[7695,7695],"valid"],[[7696,7696],"mapped",[7697]],[[7697,7697],"valid"],[[7698,7698],"mapped",[7699]],[[7699,7699],"valid"],[[7700,7700],"mapped",[7701]],[[7701,7701],"valid"],[[7702,7702],"mapped",[7703]],[[7703,7703],"valid"],[[7704,7704],"mapped",[7705]],[[7705,7705],"valid"],[[7706,7706],"mapped",[7707]],[[7707,7707],"valid"],[[7708,7708],"mapped",[7709]],[[7709,7709],"valid"],[[7710,7710],"mapped",[7711]],[[7711,7711],"valid"],[[7712,7712],"mapped",[7713]],[[7713,7713],"valid"],[[7714,7714],"mapped",[7715]],[[7715,7715],"valid"],[[7716,7716],"mapped",[7717]],[[7717,7717],"valid"],[[7718,7718],"mapped",[7719]],[[7719,7719],"valid"],[[7720,7720],"mapped",[7721]],[[7721,7721],"valid"],[[7722,7722],"mapped",[7723]],[[7723,7723],"valid"],[[7724,7724],"mapped",[7725]],[[7725,7725],"valid"],[[7726,7726],"mapped",[7727]],[[7727,7727],"valid"],[[7728,7728],"mapped",[7729]],[[7729,7729],"valid"],[[7730,7730],"mapped",[7731]],[[7731,7731],"valid"],[[7732,7732],"mapped",[7733]],[[7733,7733],"valid"],[[7734,7734],"mapped",[7735]],[[7735,7735],"valid"],[[7736,7736],"mapped",[7737]],[[7737,7737],"valid"],[[7738,7738],"mapped",[7739]],[[7739,7739],"valid"],[[7740,7740],"mapped",[7741]],[[7741,7741],"valid"],[[7742,7742],"mapped",[7743]],[[7743,7743],"valid"],[[7744,7744],"mapped",[7745]],[[7745,7745],"valid"],[[7746,7746],"mapped",[7747]],[[7747,7747],"valid"],[[7748,7748],"mapped",[7749]],[[7749,7749],"valid"],[[7750,7750],"mapped",[7751]],[[7751,7751],"valid"],[[7752,7752],"mapped",[7753]],[[7753,7753],"valid"],[[7754,7754],"mapped",[7755]],[[7755,7755],"valid"],[[7756,7756],"mapped",[7757]],[[7757,7757],"valid"],[[7758,7758],"mapped",[7759]],[[7759,7759],"valid"],[[7760,7760],"mapped",[7761]],[[7761,7761],"valid"],[[7762,7762],"mapped",[7763]],[[7763,7763],"valid"],[[7764,7764],"mapped",[7765]],[[7765,7765],"valid"],[[7766,7766],"mapped",[7767]],[[7767,7767],"valid"],[[7768,7768],"mapped",[7769]],[[7769,7769],"valid"],[[7770,7770],"mapped",[7771]],[[7771,7771],"valid"],[[7772,7772],"mapped",[7773]],[[7773,7773],"valid"],[[7774,7774],"mapped",[7775]],[[7775,7775],"valid"],[[7776,7776],"mapped",[7777]],[[7777,7777],"valid"],[[7778,7778],"mapped",[7779]],[[7779,7779],"valid"],[[7780,7780],"mapped",[7781]],[[7781,7781],"valid"],[[7782,7782],"mapped",[7783]],[[7783,7783],"valid"],[[7784,7784],"mapped",[7785]],[[7785,7785],"valid"],[[7786,7786],"mapped",[7787]],[[7787,7787],"valid"],[[7788,7788],"mapped",[7789]],[[7789,7789],"valid"],[[7790,7790],"mapped",[7791]],[[7791,7791],"valid"],[[7792,7792],"mapped",[7793]],[[7793,7793],"valid"],[[7794,7794],"mapped",[7795]],[[7795,7795],"valid"],[[7796,7796],"mapped",[7797]],[[7797,7797],"valid"],[[7798,7798],"mapped",[7799]],[[7799,7799],"valid"],[[7800,7800],"mapped",[7801]],[[7801,7801],"valid"],[[7802,7802],"mapped",[7803]],[[7803,7803],"valid"],[[7804,7804],"mapped",[7805]],[[7805,7805],"valid"],[[7806,7806],"mapped",[7807]],[[7807,7807],"valid"],[[7808,7808],"mapped",[7809]],[[7809,7809],"valid"],[[7810,7810],"mapped",[7811]],[[7811,7811],"valid"],[[7812,7812],"mapped",[7813]],[[7813,7813],"valid"],[[7814,7814],"mapped",[7815]],[[7815,7815],"valid"],[[7816,7816],"mapped",[7817]],[[7817,7817],"valid"],[[7818,7818],"mapped",[7819]],[[7819,7819],"valid"],[[7820,7820],"mapped",[7821]],[[7821,7821],"valid"],[[7822,7822],"mapped",[7823]],[[7823,7823],"valid"],[[7824,7824],"mapped",[7825]],[[7825,7825],"valid"],[[7826,7826],"mapped",[7827]],[[7827,7827],"valid"],[[7828,7828],"mapped",[7829]],[[7829,7833],"valid"],[[7834,7834],"mapped",[97,702]],[[7835,7835],"mapped",[7777]],[[7836,7837],"valid"],[[7838,7838],"mapped",[115,115]],[[7839,7839],"valid"],[[7840,7840],"mapped",[7841]],[[7841,7841],"valid"],[[7842,7842],"mapped",[7843]],[[7843,7843],"valid"],[[7844,7844],"mapped",[7845]],[[7845,7845],"valid"],[[7846,7846],"mapped",[7847]],[[7847,7847],"valid"],[[7848,7848],"mapped",[7849]],[[7849,7849],"valid"],[[7850,7850],"mapped",[7851]],[[7851,7851],"valid"],[[7852,7852],"mapped",[7853]],[[7853,7853],"valid"],[[7854,7854],"mapped",[7855]],[[7855,7855],"valid"],[[7856,7856],"mapped",[7857]],[[7857,7857],"valid"],[[7858,7858],"mapped",[7859]],[[7859,7859],"valid"],[[7860,7860],"mapped",[7861]],[[7861,7861],"valid"],[[7862,7862],"mapped",[7863]],[[7863,7863],"valid"],[[7864,7864],"mapped",[7865]],[[7865,7865],"valid"],[[7866,7866],"mapped",[7867]],[[7867,7867],"valid"],[[7868,7868],"mapped",[7869]],[[7869,7869],"valid"],[[7870,7870],"mapped",[7871]],[[7871,7871],"valid"],[[7872,7872],"mapped",[7873]],[[7873,7873],"valid"],[[7874,7874],"mapped",[7875]],[[7875,7875],"valid"],[[7876,7876],"mapped",[7877]],[[7877,7877],"valid"],[[7878,7878],"mapped",[7879]],[[7879,7879],"valid"],[[7880,7880],"mapped",[7881]],[[7881,7881],"valid"],[[7882,7882],"mapped",[7883]],[[7883,7883],"valid"],[[7884,7884],"mapped",[7885]],[[7885,7885],"valid"],[[7886,7886],"mapped",[7887]],[[7887,7887],"valid"],[[7888,7888],"mapped",[7889]],[[7889,7889],"valid"],[[7890,7890],"mapped",[7891]],[[7891,7891],"valid"],[[7892,7892],"mapped",[7893]],[[7893,7893],"valid"],[[7894,7894],"mapped",[7895]],[[7895,7895],"valid"],[[7896,7896],"mapped",[7897]],[[7897,7897],"valid"],[[7898,7898],"mapped",[7899]],[[7899,7899],"valid"],[[7900,7900],"mapped",[7901]],[[7901,7901],"valid"],[[7902,7902],"mapped",[7903]],[[7903,7903],"valid"],[[7904,7904],"mapped",[7905]],[[7905,7905],"valid"],[[7906,7906],"mapped",[7907]],[[7907,7907],"valid"],[[7908,7908],"mapped",[7909]],[[7909,7909],"valid"],[[7910,7910],"mapped",[7911]],[[7911,7911],"valid"],[[7912,7912],"mapped",[7913]],[[7913,7913],"valid"],[[7914,7914],"mapped",[7915]],[[7915,7915],"valid"],[[7916,7916],"mapped",[7917]],[[7917,7917],"valid"],[[7918,7918],"mapped",[7919]],[[7919,7919],"valid"],[[7920,7920],"mapped",[7921]],[[7921,7921],"valid"],[[7922,7922],"mapped",[7923]],[[7923,7923],"valid"],[[7924,7924],"mapped",[7925]],[[7925,7925],"valid"],[[7926,7926],"mapped",[7927]],[[7927,7927],"valid"],[[7928,7928],"mapped",[7929]],[[7929,7929],"valid"],[[7930,7930],"mapped",[7931]],[[7931,7931],"valid"],[[7932,7932],"mapped",[7933]],[[7933,7933],"valid"],[[7934,7934],"mapped",[7935]],[[7935,7935],"valid"],[[7936,7943],"valid"],[[7944,7944],"mapped",[7936]],[[7945,7945],"mapped",[7937]],[[7946,7946],"mapped",[7938]],[[7947,7947],"mapped",[7939]],[[7948,7948],"mapped",[7940]],[[7949,7949],"mapped",[7941]],[[7950,7950],"mapped",[7942]],[[7951,7951],"mapped",[7943]],[[7952,7957],"valid"],[[7958,7959],"disallowed"],[[7960,7960],"mapped",[7952]],[[7961,7961],"mapped",[7953]],[[7962,7962],"mapped",[7954]],[[7963,7963],"mapped",[7955]],[[7964,7964],"mapped",[7956]],[[7965,7965],"mapped",[7957]],[[7966,7967],"disallowed"],[[7968,7975],"valid"],[[7976,7976],"mapped",[7968]],[[7977,7977],"mapped",[7969]],[[7978,7978],"mapped",[7970]],[[7979,7979],"mapped",[7971]],[[7980,7980],"mapped",[7972]],[[7981,7981],"mapped",[7973]],[[7982,7982],"mapped",[7974]],[[7983,7983],"mapped",[7975]],[[7984,7991],"valid"],[[7992,7992],"mapped",[7984]],[[7993,7993],"mapped",[7985]],[[7994,7994],"mapped",[7986]],[[7995,7995],"mapped",[7987]],[[7996,7996],"mapped",[7988]],[[7997,7997],"mapped",[7989]],[[7998,7998],"mapped",[7990]],[[7999,7999],"mapped",[7991]],[[8000,8005],"valid"],[[8006,8007],"disallowed"],[[8008,8008],"mapped",[8000]],[[8009,8009],"mapped",[8001]],[[8010,8010],"mapped",[8002]],[[8011,8011],"mapped",[8003]],[[8012,8012],"mapped",[8004]],[[8013,8013],"mapped",[8005]],[[8014,8015],"disallowed"],[[8016,8023],"valid"],[[8024,8024],"disallowed"],[[8025,8025],"mapped",[8017]],[[8026,8026],"disallowed"],[[8027,8027],"mapped",[8019]],[[8028,8028],"disallowed"],[[8029,8029],"mapped",[8021]],[[8030,8030],"disallowed"],[[8031,8031],"mapped",[8023]],[[8032,8039],"valid"],[[8040,8040],"mapped",[8032]],[[8041,8041],"mapped",[8033]],[[8042,8042],"mapped",[8034]],[[8043,8043],"mapped",[8035]],[[8044,8044],"mapped",[8036]],[[8045,8045],"mapped",[8037]],[[8046,8046],"mapped",[8038]],[[8047,8047],"mapped",[8039]],[[8048,8048],"valid"],[[8049,8049],"mapped",[940]],[[8050,8050],"valid"],[[8051,8051],"mapped",[941]],[[8052,8052],"valid"],[[8053,8053],"mapped",[942]],[[8054,8054],"valid"],[[8055,8055],"mapped",[943]],[[8056,8056],"valid"],[[8057,8057],"mapped",[972]],[[8058,8058],"valid"],[[8059,8059],"mapped",[973]],[[8060,8060],"valid"],[[8061,8061],"mapped",[974]],[[8062,8063],"disallowed"],[[8064,8064],"mapped",[7936,953]],[[8065,8065],"mapped",[7937,953]],[[8066,8066],"mapped",[7938,953]],[[8067,8067],"mapped",[7939,953]],[[8068,8068],"mapped",[7940,953]],[[8069,8069],"mapped",[7941,953]],[[8070,8070],"mapped",[7942,953]],[[8071,8071],"mapped",[7943,953]],[[8072,8072],"mapped",[7936,953]],[[8073,8073],"mapped",[7937,953]],[[8074,8074],"mapped",[7938,953]],[[8075,8075],"mapped",[7939,953]],[[8076,8076],"mapped",[7940,953]],[[8077,8077],"mapped",[7941,953]],[[8078,8078],"mapped",[7942,953]],[[8079,8079],"mapped",[7943,953]],[[8080,8080],"mapped",[7968,953]],[[8081,8081],"mapped",[7969,953]],[[8082,8082],"mapped",[7970,953]],[[8083,8083],"mapped",[7971,953]],[[8084,8084],"mapped",[7972,953]],[[8085,8085],"mapped",[7973,953]],[[8086,8086],"mapped",[7974,953]],[[8087,8087],"mapped",[7975,953]],[[8088,8088],"mapped",[7968,953]],[[8089,8089],"mapped",[7969,953]],[[8090,8090],"mapped",[7970,953]],[[8091,8091],"mapped",[7971,953]],[[8092,8092],"mapped",[7972,953]],[[8093,8093],"mapped",[7973,953]],[[8094,8094],"mapped",[7974,953]],[[8095,8095],"mapped",[7975,953]],[[8096,8096],"mapped",[8032,953]],[[8097,8097],"mapped",[8033,953]],[[8098,8098],"mapped",[8034,953]],[[8099,8099],"mapped",[8035,953]],[[8100,8100],"mapped",[8036,953]],[[8101,8101],"mapped",[8037,953]],[[8102,8102],"mapped",[8038,953]],[[8103,8103],"mapped",[8039,953]],[[8104,8104],"mapped",[8032,953]],[[8105,8105],"mapped",[8033,953]],[[8106,8106],"mapped",[8034,953]],[[8107,8107],"mapped",[8035,953]],[[8108,8108],"mapped",[8036,953]],[[8109,8109],"mapped",[8037,953]],[[8110,8110],"mapped",[8038,953]],[[8111,8111],"mapped",[8039,953]],[[8112,8113],"valid"],[[8114,8114],"mapped",[8048,953]],[[8115,8115],"mapped",[945,953]],[[8116,8116],"mapped",[940,953]],[[8117,8117],"disallowed"],[[8118,8118],"valid"],[[8119,8119],"mapped",[8118,953]],[[8120,8120],"mapped",[8112]],[[8121,8121],"mapped",[8113]],[[8122,8122],"mapped",[8048]],[[8123,8123],"mapped",[940]],[[8124,8124],"mapped",[945,953]],[[8125,8125],"disallowed_STD3_mapped",[32,787]],[[8126,8126],"mapped",[953]],[[8127,8127],"disallowed_STD3_mapped",[32,787]],[[8128,8128],"disallowed_STD3_mapped",[32,834]],[[8129,8129],"disallowed_STD3_mapped",[32,776,834]],[[8130,8130],"mapped",[8052,953]],[[8131,8131],"mapped",[951,953]],[[8132,8132],"mapped",[942,953]],[[8133,8133],"disallowed"],[[8134,8134],"valid"],[[8135,8135],"mapped",[8134,953]],[[8136,8136],"mapped",[8050]],[[8137,8137],"mapped",[941]],[[8138,8138],"mapped",[8052]],[[8139,8139],"mapped",[942]],[[8140,8140],"mapped",[951,953]],[[8141,8141],"disallowed_STD3_mapped",[32,787,768]],[[8142,8142],"disallowed_STD3_mapped",[32,787,769]],[[8143,8143],"disallowed_STD3_mapped",[32,787,834]],[[8144,8146],"valid"],[[8147,8147],"mapped",[912]],[[8148,8149],"disallowed"],[[8150,8151],"valid"],[[8152,8152],"mapped",[8144]],[[8153,8153],"mapped",[8145]],[[8154,8154],"mapped",[8054]],[[8155,8155],"mapped",[943]],[[8156,8156],"disallowed"],[[8157,8157],"disallowed_STD3_mapped",[32,788,768]],[[8158,8158],"disallowed_STD3_mapped",[32,788,769]],[[8159,8159],"disallowed_STD3_mapped",[32,788,834]],[[8160,8162],"valid"],[[8163,8163],"mapped",[944]],[[8164,8167],"valid"],[[8168,8168],"mapped",[8160]],[[8169,8169],"mapped",[8161]],[[8170,8170],"mapped",[8058]],[[8171,8171],"mapped",[973]],[[8172,8172],"mapped",[8165]],[[8173,8173],"disallowed_STD3_mapped",[32,776,768]],[[8174,8174],"disallowed_STD3_mapped",[32,776,769]],[[8175,8175],"disallowed_STD3_mapped",[96]],[[8176,8177],"disallowed"],[[8178,8178],"mapped",[8060,953]],[[8179,8179],"mapped",[969,953]],[[8180,8180],"mapped",[974,953]],[[8181,8181],"disallowed"],[[8182,8182],"valid"],[[8183,8183],"mapped",[8182,953]],[[8184,8184],"mapped",[8056]],[[8185,8185],"mapped",[972]],[[8186,8186],"mapped",[8060]],[[8187,8187],"mapped",[974]],[[8188,8188],"mapped",[969,953]],[[8189,8189],"disallowed_STD3_mapped",[32,769]],[[8190,8190],"disallowed_STD3_mapped",[32,788]],[[8191,8191],"disallowed"],[[8192,8202],"disallowed_STD3_mapped",[32]],[[8203,8203],"ignored"],[[8204,8205],"deviation",[]],[[8206,8207],"disallowed"],[[8208,8208],"valid",[],"NV8"],[[8209,8209],"mapped",[8208]],[[8210,8214],"valid",[],"NV8"],[[8215,8215],"disallowed_STD3_mapped",[32,819]],[[8216,8227],"valid",[],"NV8"],[[8228,8230],"disallowed"],[[8231,8231],"valid",[],"NV8"],[[8232,8238],"disallowed"],[[8239,8239],"disallowed_STD3_mapped",[32]],[[8240,8242],"valid",[],"NV8"],[[8243,8243],"mapped",[8242,8242]],[[8244,8244],"mapped",[8242,8242,8242]],[[8245,8245],"valid",[],"NV8"],[[8246,8246],"mapped",[8245,8245]],[[8247,8247],"mapped",[8245,8245,8245]],[[8248,8251],"valid",[],"NV8"],[[8252,8252],"disallowed_STD3_mapped",[33,33]],[[8253,8253],"valid",[],"NV8"],[[8254,8254],"disallowed_STD3_mapped",[32,773]],[[8255,8262],"valid",[],"NV8"],[[8263,8263],"disallowed_STD3_mapped",[63,63]],[[8264,8264],"disallowed_STD3_mapped",[63,33]],[[8265,8265],"disallowed_STD3_mapped",[33,63]],[[8266,8269],"valid",[],"NV8"],[[8270,8274],"valid",[],"NV8"],[[8275,8276],"valid",[],"NV8"],[[8277,8278],"valid",[],"NV8"],[[8279,8279],"mapped",[8242,8242,8242,8242]],[[8280,8286],"valid",[],"NV8"],[[8287,8287],"disallowed_STD3_mapped",[32]],[[8288,8288],"ignored"],[[8289,8291],"disallowed"],[[8292,8292],"ignored"],[[8293,8293],"disallowed"],[[8294,8297],"disallowed"],[[8298,8303],"disallowed"],[[8304,8304],"mapped",[48]],[[8305,8305],"mapped",[105]],[[8306,8307],"disallowed"],[[8308,8308],"mapped",[52]],[[8309,8309],"mapped",[53]],[[8310,8310],"mapped",[54]],[[8311,8311],"mapped",[55]],[[8312,8312],"mapped",[56]],[[8313,8313],"mapped",[57]],[[8314,8314],"disallowed_STD3_mapped",[43]],[[8315,8315],"mapped",[8722]],[[8316,8316],"disallowed_STD3_mapped",[61]],[[8317,8317],"disallowed_STD3_mapped",[40]],[[8318,8318],"disallowed_STD3_mapped",[41]],[[8319,8319],"mapped",[110]],[[8320,8320],"mapped",[48]],[[8321,8321],"mapped",[49]],[[8322,8322],"mapped",[50]],[[8323,8323],"mapped",[51]],[[8324,8324],"mapped",[52]],[[8325,8325],"mapped",[53]],[[8326,8326],"mapped",[54]],[[8327,8327],"mapped",[55]],[[8328,8328],"mapped",[56]],[[8329,8329],"mapped",[57]],[[8330,8330],"disallowed_STD3_mapped",[43]],[[8331,8331],"mapped",[8722]],[[8332,8332],"disallowed_STD3_mapped",[61]],[[8333,8333],"disallowed_STD3_mapped",[40]],[[8334,8334],"disallowed_STD3_mapped",[41]],[[8335,8335],"disallowed"],[[8336,8336],"mapped",[97]],[[8337,8337],"mapped",[101]],[[8338,8338],"mapped",[111]],[[8339,8339],"mapped",[120]],[[8340,8340],"mapped",[601]],[[8341,8341],"mapped",[104]],[[8342,8342],"mapped",[107]],[[8343,8343],"mapped",[108]],[[8344,8344],"mapped",[109]],[[8345,8345],"mapped",[110]],[[8346,8346],"mapped",[112]],[[8347,8347],"mapped",[115]],[[8348,8348],"mapped",[116]],[[8349,8351],"disallowed"],[[8352,8359],"valid",[],"NV8"],[[8360,8360],"mapped",[114,115]],[[8361,8362],"valid",[],"NV8"],[[8363,8363],"valid",[],"NV8"],[[8364,8364],"valid",[],"NV8"],[[8365,8367],"valid",[],"NV8"],[[8368,8369],"valid",[],"NV8"],[[8370,8373],"valid",[],"NV8"],[[8374,8376],"valid",[],"NV8"],[[8377,8377],"valid",[],"NV8"],[[8378,8378],"valid",[],"NV8"],[[8379,8381],"valid",[],"NV8"],[[8382,8382],"valid",[],"NV8"],[[8383,8399],"disallowed"],[[8400,8417],"valid",[],"NV8"],[[8418,8419],"valid",[],"NV8"],[[8420,8426],"valid",[],"NV8"],[[8427,8427],"valid",[],"NV8"],[[8428,8431],"valid",[],"NV8"],[[8432,8432],"valid",[],"NV8"],[[8433,8447],"disallowed"],[[8448,8448],"disallowed_STD3_mapped",[97,47,99]],[[8449,8449],"disallowed_STD3_mapped",[97,47,115]],[[8450,8450],"mapped",[99]],[[8451,8451],"mapped",[176,99]],[[8452,8452],"valid",[],"NV8"],[[8453,8453],"disallowed_STD3_mapped",[99,47,111]],[[8454,8454],"disallowed_STD3_mapped",[99,47,117]],[[8455,8455],"mapped",[603]],[[8456,8456],"valid",[],"NV8"],[[8457,8457],"mapped",[176,102]],[[8458,8458],"mapped",[103]],[[8459,8462],"mapped",[104]],[[8463,8463],"mapped",[295]],[[8464,8465],"mapped",[105]],[[8466,8467],"mapped",[108]],[[8468,8468],"valid",[],"NV8"],[[8469,8469],"mapped",[110]],[[8470,8470],"mapped",[110,111]],[[8471,8472],"valid",[],"NV8"],[[8473,8473],"mapped",[112]],[[8474,8474],"mapped",[113]],[[8475,8477],"mapped",[114]],[[8478,8479],"valid",[],"NV8"],[[8480,8480],"mapped",[115,109]],[[8481,8481],"mapped",[116,101,108]],[[8482,8482],"mapped",[116,109]],[[8483,8483],"valid",[],"NV8"],[[8484,8484],"mapped",[122]],[[8485,8485],"valid",[],"NV8"],[[8486,8486],"mapped",[969]],[[8487,8487],"valid",[],"NV8"],[[8488,8488],"mapped",[122]],[[8489,8489],"valid",[],"NV8"],[[8490,8490],"mapped",[107]],[[8491,8491],"mapped",[229]],[[8492,8492],"mapped",[98]],[[8493,8493],"mapped",[99]],[[8494,8494],"valid",[],"NV8"],[[8495,8496],"mapped",[101]],[[8497,8497],"mapped",[102]],[[8498,8498],"disallowed"],[[8499,8499],"mapped",[109]],[[8500,8500],"mapped",[111]],[[8501,8501],"mapped",[1488]],[[8502,8502],"mapped",[1489]],[[8503,8503],"mapped",[1490]],[[8504,8504],"mapped",[1491]],[[8505,8505],"mapped",[105]],[[8506,8506],"valid",[],"NV8"],[[8507,8507],"mapped",[102,97,120]],[[8508,8508],"mapped",[960]],[[8509,8510],"mapped",[947]],[[8511,8511],"mapped",[960]],[[8512,8512],"mapped",[8721]],[[8513,8516],"valid",[],"NV8"],[[8517,8518],"mapped",[100]],[[8519,8519],"mapped",[101]],[[8520,8520],"mapped",[105]],[[8521,8521],"mapped",[106]],[[8522,8523],"valid",[],"NV8"],[[8524,8524],"valid",[],"NV8"],[[8525,8525],"valid",[],"NV8"],[[8526,8526],"valid"],[[8527,8527],"valid",[],"NV8"],[[8528,8528],"mapped",[49,8260,55]],[[8529,8529],"mapped",[49,8260,57]],[[8530,8530],"mapped",[49,8260,49,48]],[[8531,8531],"mapped",[49,8260,51]],[[8532,8532],"mapped",[50,8260,51]],[[8533,8533],"mapped",[49,8260,53]],[[8534,8534],"mapped",[50,8260,53]],[[8535,8535],"mapped",[51,8260,53]],[[8536,8536],"mapped",[52,8260,53]],[[8537,8537],"mapped",[49,8260,54]],[[8538,8538],"mapped",[53,8260,54]],[[8539,8539],"mapped",[49,8260,56]],[[8540,8540],"mapped",[51,8260,56]],[[8541,8541],"mapped",[53,8260,56]],[[8542,8542],"mapped",[55,8260,56]],[[8543,8543],"mapped",[49,8260]],[[8544,8544],"mapped",[105]],[[8545,8545],"mapped",[105,105]],[[8546,8546],"mapped",[105,105,105]],[[8547,8547],"mapped",[105,118]],[[8548,8548],"mapped",[118]],[[8549,8549],"mapped",[118,105]],[[8550,8550],"mapped",[118,105,105]],[[8551,8551],"mapped",[118,105,105,105]],[[8552,8552],"mapped",[105,120]],[[8553,8553],"mapped",[120]],[[8554,8554],"mapped",[120,105]],[[8555,8555],"mapped",[120,105,105]],[[8556,8556],"mapped",[108]],[[8557,8557],"mapped",[99]],[[8558,8558],"mapped",[100]],[[8559,8559],"mapped",[109]],[[8560,8560],"mapped",[105]],[[8561,8561],"mapped",[105,105]],[[8562,8562],"mapped",[105,105,105]],[[8563,8563],"mapped",[105,118]],[[8564,8564],"mapped",[118]],[[8565,8565],"mapped",[118,105]],[[8566,8566],"mapped",[118,105,105]],[[8567,8567],"mapped",[118,105,105,105]],[[8568,8568],"mapped",[105,120]],[[8569,8569],"mapped",[120]],[[8570,8570],"mapped",[120,105]],[[8571,8571],"mapped",[120,105,105]],[[8572,8572],"mapped",[108]],[[8573,8573],"mapped",[99]],[[8574,8574],"mapped",[100]],[[8575,8575],"mapped",[109]],[[8576,8578],"valid",[],"NV8"],[[8579,8579],"disallowed"],[[8580,8580],"valid"],[[8581,8584],"valid",[],"NV8"],[[8585,8585],"mapped",[48,8260,51]],[[8586,8587],"valid",[],"NV8"],[[8588,8591],"disallowed"],[[8592,8682],"valid",[],"NV8"],[[8683,8691],"valid",[],"NV8"],[[8692,8703],"valid",[],"NV8"],[[8704,8747],"valid",[],"NV8"],[[8748,8748],"mapped",[8747,8747]],[[8749,8749],"mapped",[8747,8747,8747]],[[8750,8750],"valid",[],"NV8"],[[8751,8751],"mapped",[8750,8750]],[[8752,8752],"mapped",[8750,8750,8750]],[[8753,8799],"valid",[],"NV8"],[[8800,8800],"disallowed_STD3_valid"],[[8801,8813],"valid",[],"NV8"],[[8814,8815],"disallowed_STD3_valid"],[[8816,8945],"valid",[],"NV8"],[[8946,8959],"valid",[],"NV8"],[[8960,8960],"valid",[],"NV8"],[[8961,8961],"valid",[],"NV8"],[[8962,9000],"valid",[],"NV8"],[[9001,9001],"mapped",[12296]],[[9002,9002],"mapped",[12297]],[[9003,9082],"valid",[],"NV8"],[[9083,9083],"valid",[],"NV8"],[[9084,9084],"valid",[],"NV8"],[[9085,9114],"valid",[],"NV8"],[[9115,9166],"valid",[],"NV8"],[[9167,9168],"valid",[],"NV8"],[[9169,9179],"valid",[],"NV8"],[[9180,9191],"valid",[],"NV8"],[[9192,9192],"valid",[],"NV8"],[[9193,9203],"valid",[],"NV8"],[[9204,9210],"valid",[],"NV8"],[[9211,9215],"disallowed"],[[9216,9252],"valid",[],"NV8"],[[9253,9254],"valid",[],"NV8"],[[9255,9279],"disallowed"],[[9280,9290],"valid",[],"NV8"],[[9291,9311],"disallowed"],[[9312,9312],"mapped",[49]],[[9313,9313],"mapped",[50]],[[9314,9314],"mapped",[51]],[[9315,9315],"mapped",[52]],[[9316,9316],"mapped",[53]],[[9317,9317],"mapped",[54]],[[9318,9318],"mapped",[55]],[[9319,9319],"mapped",[56]],[[9320,9320],"mapped",[57]],[[9321,9321],"mapped",[49,48]],[[9322,9322],"mapped",[49,49]],[[9323,9323],"mapped",[49,50]],[[9324,9324],"mapped",[49,51]],[[9325,9325],"mapped",[49,52]],[[9326,9326],"mapped",[49,53]],[[9327,9327],"mapped",[49,54]],[[9328,9328],"mapped",[49,55]],[[9329,9329],"mapped",[49,56]],[[9330,9330],"mapped",[49,57]],[[9331,9331],"mapped",[50,48]],[[9332,9332],"disallowed_STD3_mapped",[40,49,41]],[[9333,9333],"disallowed_STD3_mapped",[40,50,41]],[[9334,9334],"disallowed_STD3_mapped",[40,51,41]],[[9335,9335],"disallowed_STD3_mapped",[40,52,41]],[[9336,9336],"disallowed_STD3_mapped",[40,53,41]],[[9337,9337],"disallowed_STD3_mapped",[40,54,41]],[[9338,9338],"disallowed_STD3_mapped",[40,55,41]],[[9339,9339],"disallowed_STD3_mapped",[40,56,41]],[[9340,9340],"disallowed_STD3_mapped",[40,57,41]],[[9341,9341],"disallowed_STD3_mapped",[40,49,48,41]],[[9342,9342],"disallowed_STD3_mapped",[40,49,49,41]],[[9343,9343],"disallowed_STD3_mapped",[40,49,50,41]],[[9344,9344],"disallowed_STD3_mapped",[40,49,51,41]],[[9345,9345],"disallowed_STD3_mapped",[40,49,52,41]],[[9346,9346],"disallowed_STD3_mapped",[40,49,53,41]],[[9347,9347],"disallowed_STD3_mapped",[40,49,54,41]],[[9348,9348],"disallowed_STD3_mapped",[40,49,55,41]],[[9349,9349],"disallowed_STD3_mapped",[40,49,56,41]],[[9350,9350],"disallowed_STD3_mapped",[40,49,57,41]],[[9351,9351],"disallowed_STD3_mapped",[40,50,48,41]],[[9352,9371],"disallowed"],[[9372,9372],"disallowed_STD3_mapped",[40,97,41]],[[9373,9373],"disallowed_STD3_mapped",[40,98,41]],[[9374,9374],"disallowed_STD3_mapped",[40,99,41]],[[9375,9375],"disallowed_STD3_mapped",[40,100,41]],[[9376,9376],"disallowed_STD3_mapped",[40,101,41]],[[9377,9377],"disallowed_STD3_mapped",[40,102,41]],[[9378,9378],"disallowed_STD3_mapped",[40,103,41]],[[9379,9379],"disallowed_STD3_mapped",[40,104,41]],[[9380,9380],"disallowed_STD3_mapped",[40,105,41]],[[9381,9381],"disallowed_STD3_mapped",[40,106,41]],[[9382,9382],"disallowed_STD3_mapped",[40,107,41]],[[9383,9383],"disallowed_STD3_mapped",[40,108,41]],[[9384,9384],"disallowed_STD3_mapped",[40,109,41]],[[9385,9385],"disallowed_STD3_mapped",[40,110,41]],[[9386,9386],"disallowed_STD3_mapped",[40,111,41]],[[9387,9387],"disallowed_STD3_mapped",[40,112,41]],[[9388,9388],"disallowed_STD3_mapped",[40,113,41]],[[9389,9389],"disallowed_STD3_mapped",[40,114,41]],[[9390,9390],"disallowed_STD3_mapped",[40,115,41]],[[9391,9391],"disallowed_STD3_mapped",[40,116,41]],[[9392,9392],"disallowed_STD3_mapped",[40,117,41]],[[9393,9393],"disallowed_STD3_mapped",[40,118,41]],[[9394,9394],"disallowed_STD3_mapped",[40,119,41]],[[9395,9395],"disallowed_STD3_mapped",[40,120,41]],[[9396,9396],"disallowed_STD3_mapped",[40,121,41]],[[9397,9397],"disallowed_STD3_mapped",[40,122,41]],[[9398,9398],"mapped",[97]],[[9399,9399],"mapped",[98]],[[9400,9400],"mapped",[99]],[[9401,9401],"mapped",[100]],[[9402,9402],"mapped",[101]],[[9403,9403],"mapped",[102]],[[9404,9404],"mapped",[103]],[[9405,9405],"mapped",[104]],[[9406,9406],"mapped",[105]],[[9407,9407],"mapped",[106]],[[9408,9408],"mapped",[107]],[[9409,9409],"mapped",[108]],[[9410,9410],"mapped",[109]],[[9411,9411],"mapped",[110]],[[9412,9412],"mapped",[111]],[[9413,9413],"mapped",[112]],[[9414,9414],"mapped",[113]],[[9415,9415],"mapped",[114]],[[9416,9416],"mapped",[115]],[[9417,9417],"mapped",[116]],[[9418,9418],"mapped",[117]],[[9419,9419],"mapped",[118]],[[9420,9420],"mapped",[119]],[[9421,9421],"mapped",[120]],[[9422,9422],"mapped",[121]],[[9423,9423],"mapped",[122]],[[9424,9424],"mapped",[97]],[[9425,9425],"mapped",[98]],[[9426,9426],"mapped",[99]],[[9427,9427],"mapped",[100]],[[9428,9428],"mapped",[101]],[[9429,9429],"mapped",[102]],[[9430,9430],"mapped",[103]],[[9431,9431],"mapped",[104]],[[9432,9432],"mapped",[105]],[[9433,9433],"mapped",[106]],[[9434,9434],"mapped",[107]],[[9435,9435],"mapped",[108]],[[9436,9436],"mapped",[109]],[[9437,9437],"mapped",[110]],[[9438,9438],"mapped",[111]],[[9439,9439],"mapped",[112]],[[9440,9440],"mapped",[113]],[[9441,9441],"mapped",[114]],[[9442,9442],"mapped",[115]],[[9443,9443],"mapped",[116]],[[9444,9444],"mapped",[117]],[[9445,9445],"mapped",[118]],[[9446,9446],"mapped",[119]],[[9447,9447],"mapped",[120]],[[9448,9448],"mapped",[121]],[[9449,9449],"mapped",[122]],[[9450,9450],"mapped",[48]],[[9451,9470],"valid",[],"NV8"],[[9471,9471],"valid",[],"NV8"],[[9472,9621],"valid",[],"NV8"],[[9622,9631],"valid",[],"NV8"],[[9632,9711],"valid",[],"NV8"],[[9712,9719],"valid",[],"NV8"],[[9720,9727],"valid",[],"NV8"],[[9728,9747],"valid",[],"NV8"],[[9748,9749],"valid",[],"NV8"],[[9750,9751],"valid",[],"NV8"],[[9752,9752],"valid",[],"NV8"],[[9753,9753],"valid",[],"NV8"],[[9754,9839],"valid",[],"NV8"],[[9840,9841],"valid",[],"NV8"],[[9842,9853],"valid",[],"NV8"],[[9854,9855],"valid",[],"NV8"],[[9856,9865],"valid",[],"NV8"],[[9866,9873],"valid",[],"NV8"],[[9874,9884],"valid",[],"NV8"],[[9885,9885],"valid",[],"NV8"],[[9886,9887],"valid",[],"NV8"],[[9888,9889],"valid",[],"NV8"],[[9890,9905],"valid",[],"NV8"],[[9906,9906],"valid",[],"NV8"],[[9907,9916],"valid",[],"NV8"],[[9917,9919],"valid",[],"NV8"],[[9920,9923],"valid",[],"NV8"],[[9924,9933],"valid",[],"NV8"],[[9934,9934],"valid",[],"NV8"],[[9935,9953],"valid",[],"NV8"],[[9954,9954],"valid",[],"NV8"],[[9955,9955],"valid",[],"NV8"],[[9956,9959],"valid",[],"NV8"],[[9960,9983],"valid",[],"NV8"],[[9984,9984],"valid",[],"NV8"],[[9985,9988],"valid",[],"NV8"],[[9989,9989],"valid",[],"NV8"],[[9990,9993],"valid",[],"NV8"],[[9994,9995],"valid",[],"NV8"],[[9996,10023],"valid",[],"NV8"],[[10024,10024],"valid",[],"NV8"],[[10025,10059],"valid",[],"NV8"],[[10060,10060],"valid",[],"NV8"],[[10061,10061],"valid",[],"NV8"],[[10062,10062],"valid",[],"NV8"],[[10063,10066],"valid",[],"NV8"],[[10067,10069],"valid",[],"NV8"],[[10070,10070],"valid",[],"NV8"],[[10071,10071],"valid",[],"NV8"],[[10072,10078],"valid",[],"NV8"],[[10079,10080],"valid",[],"NV8"],[[10081,10087],"valid",[],"NV8"],[[10088,10101],"valid",[],"NV8"],[[10102,10132],"valid",[],"NV8"],[[10133,10135],"valid",[],"NV8"],[[10136,10159],"valid",[],"NV8"],[[10160,10160],"valid",[],"NV8"],[[10161,10174],"valid",[],"NV8"],[[10175,10175],"valid",[],"NV8"],[[10176,10182],"valid",[],"NV8"],[[10183,10186],"valid",[],"NV8"],[[10187,10187],"valid",[],"NV8"],[[10188,10188],"valid",[],"NV8"],[[10189,10189],"valid",[],"NV8"],[[10190,10191],"valid",[],"NV8"],[[10192,10219],"valid",[],"NV8"],[[10220,10223],"valid",[],"NV8"],[[10224,10239],"valid",[],"NV8"],[[10240,10495],"valid",[],"NV8"],[[10496,10763],"valid",[],"NV8"],[[10764,10764],"mapped",[8747,8747,8747,8747]],[[10765,10867],"valid",[],"NV8"],[[10868,10868],"disallowed_STD3_mapped",[58,58,61]],[[10869,10869],"disallowed_STD3_mapped",[61,61]],[[10870,10870],"disallowed_STD3_mapped",[61,61,61]],[[10871,10971],"valid",[],"NV8"],[[10972,10972],"mapped",[10973,824]],[[10973,11007],"valid",[],"NV8"],[[11008,11021],"valid",[],"NV8"],[[11022,11027],"valid",[],"NV8"],[[11028,11034],"valid",[],"NV8"],[[11035,11039],"valid",[],"NV8"],[[11040,11043],"valid",[],"NV8"],[[11044,11084],"valid",[],"NV8"],[[11085,11087],"valid",[],"NV8"],[[11088,11092],"valid",[],"NV8"],[[11093,11097],"valid",[],"NV8"],[[11098,11123],"valid",[],"NV8"],[[11124,11125],"disallowed"],[[11126,11157],"valid",[],"NV8"],[[11158,11159],"disallowed"],[[11160,11193],"valid",[],"NV8"],[[11194,11196],"disallowed"],[[11197,11208],"valid",[],"NV8"],[[11209,11209],"disallowed"],[[11210,11217],"valid",[],"NV8"],[[11218,11243],"disallowed"],[[11244,11247],"valid",[],"NV8"],[[11248,11263],"disallowed"],[[11264,11264],"mapped",[11312]],[[11265,11265],"mapped",[11313]],[[11266,11266],"mapped",[11314]],[[11267,11267],"mapped",[11315]],[[11268,11268],"mapped",[11316]],[[11269,11269],"mapped",[11317]],[[11270,11270],"mapped",[11318]],[[11271,11271],"mapped",[11319]],[[11272,11272],"mapped",[11320]],[[11273,11273],"mapped",[11321]],[[11274,11274],"mapped",[11322]],[[11275,11275],"mapped",[11323]],[[11276,11276],"mapped",[11324]],[[11277,11277],"mapped",[11325]],[[11278,11278],"mapped",[11326]],[[11279,11279],"mapped",[11327]],[[11280,11280],"mapped",[11328]],[[11281,11281],"mapped",[11329]],[[11282,11282],"mapped",[11330]],[[11283,11283],"mapped",[11331]],[[11284,11284],"mapped",[11332]],[[11285,11285],"mapped",[11333]],[[11286,11286],"mapped",[11334]],[[11287,11287],"mapped",[11335]],[[11288,11288],"mapped",[11336]],[[11289,11289],"mapped",[11337]],[[11290,11290],"mapped",[11338]],[[11291,11291],"mapped",[11339]],[[11292,11292],"mapped",[11340]],[[11293,11293],"mapped",[11341]],[[11294,11294],"mapped",[11342]],[[11295,11295],"mapped",[11343]],[[11296,11296],"mapped",[11344]],[[11297,11297],"mapped",[11345]],[[11298,11298],"mapped",[11346]],[[11299,11299],"mapped",[11347]],[[11300,11300],"mapped",[11348]],[[11301,11301],"mapped",[11349]],[[11302,11302],"mapped",[11350]],[[11303,11303],"mapped",[11351]],[[11304,11304],"mapped",[11352]],[[11305,11305],"mapped",[11353]],[[11306,11306],"mapped",[11354]],[[11307,11307],"mapped",[11355]],[[11308,11308],"mapped",[11356]],[[11309,11309],"mapped",[11357]],[[11310,11310],"mapped",[11358]],[[11311,11311],"disallowed"],[[11312,11358],"valid"],[[11359,11359],"disallowed"],[[11360,11360],"mapped",[11361]],[[11361,11361],"valid"],[[11362,11362],"mapped",[619]],[[11363,11363],"mapped",[7549]],[[11364,11364],"mapped",[637]],[[11365,11366],"valid"],[[11367,11367],"mapped",[11368]],[[11368,11368],"valid"],[[11369,11369],"mapped",[11370]],[[11370,11370],"valid"],[[11371,11371],"mapped",[11372]],[[11372,11372],"valid"],[[11373,11373],"mapped",[593]],[[11374,11374],"mapped",[625]],[[11375,11375],"mapped",[592]],[[11376,11376],"mapped",[594]],[[11377,11377],"valid"],[[11378,11378],"mapped",[11379]],[[11379,11379],"valid"],[[11380,11380],"valid"],[[11381,11381],"mapped",[11382]],[[11382,11383],"valid"],[[11384,11387],"valid"],[[11388,11388],"mapped",[106]],[[11389,11389],"mapped",[118]],[[11390,11390],"mapped",[575]],[[11391,11391],"mapped",[576]],[[11392,11392],"mapped",[11393]],[[11393,11393],"valid"],[[11394,11394],"mapped",[11395]],[[11395,11395],"valid"],[[11396,11396],"mapped",[11397]],[[11397,11397],"valid"],[[11398,11398],"mapped",[11399]],[[11399,11399],"valid"],[[11400,11400],"mapped",[11401]],[[11401,11401],"valid"],[[11402,11402],"mapped",[11403]],[[11403,11403],"valid"],[[11404,11404],"mapped",[11405]],[[11405,11405],"valid"],[[11406,11406],"mapped",[11407]],[[11407,11407],"valid"],[[11408,11408],"mapped",[11409]],[[11409,11409],"valid"],[[11410,11410],"mapped",[11411]],[[11411,11411],"valid"],[[11412,11412],"mapped",[11413]],[[11413,11413],"valid"],[[11414,11414],"mapped",[11415]],[[11415,11415],"valid"],[[11416,11416],"mapped",[11417]],[[11417,11417],"valid"],[[11418,11418],"mapped",[11419]],[[11419,11419],"valid"],[[11420,11420],"mapped",[11421]],[[11421,11421],"valid"],[[11422,11422],"mapped",[11423]],[[11423,11423],"valid"],[[11424,11424],"mapped",[11425]],[[11425,11425],"valid"],[[11426,11426],"mapped",[11427]],[[11427,11427],"valid"],[[11428,11428],"mapped",[11429]],[[11429,11429],"valid"],[[11430,11430],"mapped",[11431]],[[11431,11431],"valid"],[[11432,11432],"mapped",[11433]],[[11433,11433],"valid"],[[11434,11434],"mapped",[11435]],[[11435,11435],"valid"],[[11436,11436],"mapped",[11437]],[[11437,11437],"valid"],[[11438,11438],"mapped",[11439]],[[11439,11439],"valid"],[[11440,11440],"mapped",[11441]],[[11441,11441],"valid"],[[11442,11442],"mapped",[11443]],[[11443,11443],"valid"],[[11444,11444],"mapped",[11445]],[[11445,11445],"valid"],[[11446,11446],"mapped",[11447]],[[11447,11447],"valid"],[[11448,11448],"mapped",[11449]],[[11449,11449],"valid"],[[11450,11450],"mapped",[11451]],[[11451,11451],"valid"],[[11452,11452],"mapped",[11453]],[[11453,11453],"valid"],[[11454,11454],"mapped",[11455]],[[11455,11455],"valid"],[[11456,11456],"mapped",[11457]],[[11457,11457],"valid"],[[11458,11458],"mapped",[11459]],[[11459,11459],"valid"],[[11460,11460],"mapped",[11461]],[[11461,11461],"valid"],[[11462,11462],"mapped",[11463]],[[11463,11463],"valid"],[[11464,11464],"mapped",[11465]],[[11465,11465],"valid"],[[11466,11466],"mapped",[11467]],[[11467,11467],"valid"],[[11468,11468],"mapped",[11469]],[[11469,11469],"valid"],[[11470,11470],"mapped",[11471]],[[11471,11471],"valid"],[[11472,11472],"mapped",[11473]],[[11473,11473],"valid"],[[11474,11474],"mapped",[11475]],[[11475,11475],"valid"],[[11476,11476],"mapped",[11477]],[[11477,11477],"valid"],[[11478,11478],"mapped",[11479]],[[11479,11479],"valid"],[[11480,11480],"mapped",[11481]],[[11481,11481],"valid"],[[11482,11482],"mapped",[11483]],[[11483,11483],"valid"],[[11484,11484],"mapped",[11485]],[[11485,11485],"valid"],[[11486,11486],"mapped",[11487]],[[11487,11487],"valid"],[[11488,11488],"mapped",[11489]],[[11489,11489],"valid"],[[11490,11490],"mapped",[11491]],[[11491,11492],"valid"],[[11493,11498],"valid",[],"NV8"],[[11499,11499],"mapped",[11500]],[[11500,11500],"valid"],[[11501,11501],"mapped",[11502]],[[11502,11505],"valid"],[[11506,11506],"mapped",[11507]],[[11507,11507],"valid"],[[11508,11512],"disallowed"],[[11513,11519],"valid",[],"NV8"],[[11520,11557],"valid"],[[11558,11558],"disallowed"],[[11559,11559],"valid"],[[11560,11564],"disallowed"],[[11565,11565],"valid"],[[11566,11567],"disallowed"],[[11568,11621],"valid"],[[11622,11623],"valid"],[[11624,11630],"disallowed"],[[11631,11631],"mapped",[11617]],[[11632,11632],"valid",[],"NV8"],[[11633,11646],"disallowed"],[[11647,11647],"valid"],[[11648,11670],"valid"],[[11671,11679],"disallowed"],[[11680,11686],"valid"],[[11687,11687],"disallowed"],[[11688,11694],"valid"],[[11695,11695],"disallowed"],[[11696,11702],"valid"],[[11703,11703],"disallowed"],[[11704,11710],"valid"],[[11711,11711],"disallowed"],[[11712,11718],"valid"],[[11719,11719],"disallowed"],[[11720,11726],"valid"],[[11727,11727],"disallowed"],[[11728,11734],"valid"],[[11735,11735],"disallowed"],[[11736,11742],"valid"],[[11743,11743],"disallowed"],[[11744,11775],"valid"],[[11776,11799],"valid",[],"NV8"],[[11800,11803],"valid",[],"NV8"],[[11804,11805],"valid",[],"NV8"],[[11806,11822],"valid",[],"NV8"],[[11823,11823],"valid"],[[11824,11824],"valid",[],"NV8"],[[11825,11825],"valid",[],"NV8"],[[11826,11835],"valid",[],"NV8"],[[11836,11842],"valid",[],"NV8"],[[11843,11903],"disallowed"],[[11904,11929],"valid",[],"NV8"],[[11930,11930],"disallowed"],[[11931,11934],"valid",[],"NV8"],[[11935,11935],"mapped",[27597]],[[11936,12018],"valid",[],"NV8"],[[12019,12019],"mapped",[40863]],[[12020,12031],"disallowed"],[[12032,12032],"mapped",[19968]],[[12033,12033],"mapped",[20008]],[[12034,12034],"mapped",[20022]],[[12035,12035],"mapped",[20031]],[[12036,12036],"mapped",[20057]],[[12037,12037],"mapped",[20101]],[[12038,12038],"mapped",[20108]],[[12039,12039],"mapped",[20128]],[[12040,12040],"mapped",[20154]],[[12041,12041],"mapped",[20799]],[[12042,12042],"mapped",[20837]],[[12043,12043],"mapped",[20843]],[[12044,12044],"mapped",[20866]],[[12045,12045],"mapped",[20886]],[[12046,12046],"mapped",[20907]],[[12047,12047],"mapped",[20960]],[[12048,12048],"mapped",[20981]],[[12049,12049],"mapped",[20992]],[[12050,12050],"mapped",[21147]],[[12051,12051],"mapped",[21241]],[[12052,12052],"mapped",[21269]],[[12053,12053],"mapped",[21274]],[[12054,12054],"mapped",[21304]],[[12055,12055],"mapped",[21313]],[[12056,12056],"mapped",[21340]],[[12057,12057],"mapped",[21353]],[[12058,12058],"mapped",[21378]],[[12059,12059],"mapped",[21430]],[[12060,12060],"mapped",[21448]],[[12061,12061],"mapped",[21475]],[[12062,12062],"mapped",[22231]],[[12063,12063],"mapped",[22303]],[[12064,12064],"mapped",[22763]],[[12065,12065],"mapped",[22786]],[[12066,12066],"mapped",[22794]],[[12067,12067],"mapped",[22805]],[[12068,12068],"mapped",[22823]],[[12069,12069],"mapped",[22899]],[[12070,12070],"mapped",[23376]],[[12071,12071],"mapped",[23424]],[[12072,12072],"mapped",[23544]],[[12073,12073],"mapped",[23567]],[[12074,12074],"mapped",[23586]],[[12075,12075],"mapped",[23608]],[[12076,12076],"mapped",[23662]],[[12077,12077],"mapped",[23665]],[[12078,12078],"mapped",[24027]],[[12079,12079],"mapped",[24037]],[[12080,12080],"mapped",[24049]],[[12081,12081],"mapped",[24062]],[[12082,12082],"mapped",[24178]],[[12083,12083],"mapped",[24186]],[[12084,12084],"mapped",[24191]],[[12085,12085],"mapped",[24308]],[[12086,12086],"mapped",[24318]],[[12087,12087],"mapped",[24331]],[[12088,12088],"mapped",[24339]],[[12089,12089],"mapped",[24400]],[[12090,12090],"mapped",[24417]],[[12091,12091],"mapped",[24435]],[[12092,12092],"mapped",[24515]],[[12093,12093],"mapped",[25096]],[[12094,12094],"mapped",[25142]],[[12095,12095],"mapped",[25163]],[[12096,12096],"mapped",[25903]],[[12097,12097],"mapped",[25908]],[[12098,12098],"mapped",[25991]],[[12099,12099],"mapped",[26007]],[[12100,12100],"mapped",[26020]],[[12101,12101],"mapped",[26041]],[[12102,12102],"mapped",[26080]],[[12103,12103],"mapped",[26085]],[[12104,12104],"mapped",[26352]],[[12105,12105],"mapped",[26376]],[[12106,12106],"mapped",[26408]],[[12107,12107],"mapped",[27424]],[[12108,12108],"mapped",[27490]],[[12109,12109],"mapped",[27513]],[[12110,12110],"mapped",[27571]],[[12111,12111],"mapped",[27595]],[[12112,12112],"mapped",[27604]],[[12113,12113],"mapped",[27611]],[[12114,12114],"mapped",[27663]],[[12115,12115],"mapped",[27668]],[[12116,12116],"mapped",[27700]],[[12117,12117],"mapped",[28779]],[[12118,12118],"mapped",[29226]],[[12119,12119],"mapped",[29238]],[[12120,12120],"mapped",[29243]],[[12121,12121],"mapped",[29247]],[[12122,12122],"mapped",[29255]],[[12123,12123],"mapped",[29273]],[[12124,12124],"mapped",[29275]],[[12125,12125],"mapped",[29356]],[[12126,12126],"mapped",[29572]],[[12127,12127],"mapped",[29577]],[[12128,12128],"mapped",[29916]],[[12129,12129],"mapped",[29926]],[[12130,12130],"mapped",[29976]],[[12131,12131],"mapped",[29983]],[[12132,12132],"mapped",[29992]],[[12133,12133],"mapped",[30000]],[[12134,12134],"mapped",[30091]],[[12135,12135],"mapped",[30098]],[[12136,12136],"mapped",[30326]],[[12137,12137],"mapped",[30333]],[[12138,12138],"mapped",[30382]],[[12139,12139],"mapped",[30399]],[[12140,12140],"mapped",[30446]],[[12141,12141],"mapped",[30683]],[[12142,12142],"mapped",[30690]],[[12143,12143],"mapped",[30707]],[[12144,12144],"mapped",[31034]],[[12145,12145],"mapped",[31160]],[[12146,12146],"mapped",[31166]],[[12147,12147],"mapped",[31348]],[[12148,12148],"mapped",[31435]],[[12149,12149],"mapped",[31481]],[[12150,12150],"mapped",[31859]],[[12151,12151],"mapped",[31992]],[[12152,12152],"mapped",[32566]],[[12153,12153],"mapped",[32593]],[[12154,12154],"mapped",[32650]],[[12155,12155],"mapped",[32701]],[[12156,12156],"mapped",[32769]],[[12157,12157],"mapped",[32780]],[[12158,12158],"mapped",[32786]],[[12159,12159],"mapped",[32819]],[[12160,12160],"mapped",[32895]],[[12161,12161],"mapped",[32905]],[[12162,12162],"mapped",[33251]],[[12163,12163],"mapped",[33258]],[[12164,12164],"mapped",[33267]],[[12165,12165],"mapped",[33276]],[[12166,12166],"mapped",[33292]],[[12167,12167],"mapped",[33307]],[[12168,12168],"mapped",[33311]],[[12169,12169],"mapped",[33390]],[[12170,12170],"mapped",[33394]],[[12171,12171],"mapped",[33400]],[[12172,12172],"mapped",[34381]],[[12173,12173],"mapped",[34411]],[[12174,12174],"mapped",[34880]],[[12175,12175],"mapped",[34892]],[[12176,12176],"mapped",[34915]],[[12177,12177],"mapped",[35198]],[[12178,12178],"mapped",[35211]],[[12179,12179],"mapped",[35282]],[[12180,12180],"mapped",[35328]],[[12181,12181],"mapped",[35895]],[[12182,12182],"mapped",[35910]],[[12183,12183],"mapped",[35925]],[[12184,12184],"mapped",[35960]],[[12185,12185],"mapped",[35997]],[[12186,12186],"mapped",[36196]],[[12187,12187],"mapped",[36208]],[[12188,12188],"mapped",[36275]],[[12189,12189],"mapped",[36523]],[[12190,12190],"mapped",[36554]],[[12191,12191],"mapped",[36763]],[[12192,12192],"mapped",[36784]],[[12193,12193],"mapped",[36789]],[[12194,12194],"mapped",[37009]],[[12195,12195],"mapped",[37193]],[[12196,12196],"mapped",[37318]],[[12197,12197],"mapped",[37324]],[[12198,12198],"mapped",[37329]],[[12199,12199],"mapped",[38263]],[[12200,12200],"mapped",[38272]],[[12201,12201],"mapped",[38428]],[[12202,12202],"mapped",[38582]],[[12203,12203],"mapped",[38585]],[[12204,12204],"mapped",[38632]],[[12205,12205],"mapped",[38737]],[[12206,12206],"mapped",[38750]],[[12207,12207],"mapped",[38754]],[[12208,12208],"mapped",[38761]],[[12209,12209],"mapped",[38859]],[[12210,12210],"mapped",[38893]],[[12211,12211],"mapped",[38899]],[[12212,12212],"mapped",[38913]],[[12213,12213],"mapped",[39080]],[[12214,12214],"mapped",[39131]],[[12215,12215],"mapped",[39135]],[[12216,12216],"mapped",[39318]],[[12217,12217],"mapped",[39321]],[[12218,12218],"mapped",[39340]],[[12219,12219],"mapped",[39592]],[[12220,12220],"mapped",[39640]],[[12221,12221],"mapped",[39647]],[[12222,12222],"mapped",[39717]],[[12223,12223],"mapped",[39727]],[[12224,12224],"mapped",[39730]],[[12225,12225],"mapped",[39740]],[[12226,12226],"mapped",[39770]],[[12227,12227],"mapped",[40165]],[[12228,12228],"mapped",[40565]],[[12229,12229],"mapped",[40575]],[[12230,12230],"mapped",[40613]],[[12231,12231],"mapped",[40635]],[[12232,12232],"mapped",[40643]],[[12233,12233],"mapped",[40653]],[[12234,12234],"mapped",[40657]],[[12235,12235],"mapped",[40697]],[[12236,12236],"mapped",[40701]],[[12237,12237],"mapped",[40718]],[[12238,12238],"mapped",[40723]],[[12239,12239],"mapped",[40736]],[[12240,12240],"mapped",[40763]],[[12241,12241],"mapped",[40778]],[[12242,12242],"mapped",[40786]],[[12243,12243],"mapped",[40845]],[[12244,12244],"mapped",[40860]],[[12245,12245],"mapped",[40864]],[[12246,12271],"disallowed"],[[12272,12283],"disallowed"],[[12284,12287],"disallowed"],[[12288,12288],"disallowed_STD3_mapped",[32]],[[12289,12289],"valid",[],"NV8"],[[12290,12290],"mapped",[46]],[[12291,12292],"valid",[],"NV8"],[[12293,12295],"valid"],[[12296,12329],"valid",[],"NV8"],[[12330,12333],"valid"],[[12334,12341],"valid",[],"NV8"],[[12342,12342],"mapped",[12306]],[[12343,12343],"valid",[],"NV8"],[[12344,12344],"mapped",[21313]],[[12345,12345],"mapped",[21316]],[[12346,12346],"mapped",[21317]],[[12347,12347],"valid",[],"NV8"],[[12348,12348],"valid"],[[12349,12349],"valid",[],"NV8"],[[12350,12350],"valid",[],"NV8"],[[12351,12351],"valid",[],"NV8"],[[12352,12352],"disallowed"],[[12353,12436],"valid"],[[12437,12438],"valid"],[[12439,12440],"disallowed"],[[12441,12442],"valid"],[[12443,12443],"disallowed_STD3_mapped",[32,12441]],[[12444,12444],"disallowed_STD3_mapped",[32,12442]],[[12445,12446],"valid"],[[12447,12447],"mapped",[12424,12426]],[[12448,12448],"valid",[],"NV8"],[[12449,12542],"valid"],[[12543,12543],"mapped",[12467,12488]],[[12544,12548],"disallowed"],[[12549,12588],"valid"],[[12589,12589],"valid"],[[12590,12592],"disallowed"],[[12593,12593],"mapped",[4352]],[[12594,12594],"mapped",[4353]],[[12595,12595],"mapped",[4522]],[[12596,12596],"mapped",[4354]],[[12597,12597],"mapped",[4524]],[[12598,12598],"mapped",[4525]],[[12599,12599],"mapped",[4355]],[[12600,12600],"mapped",[4356]],[[12601,12601],"mapped",[4357]],[[12602,12602],"mapped",[4528]],[[12603,12603],"mapped",[4529]],[[12604,12604],"mapped",[4530]],[[12605,12605],"mapped",[4531]],[[12606,12606],"mapped",[4532]],[[12607,12607],"mapped",[4533]],[[12608,12608],"mapped",[4378]],[[12609,12609],"mapped",[4358]],[[12610,12610],"mapped",[4359]],[[12611,12611],"mapped",[4360]],[[12612,12612],"mapped",[4385]],[[12613,12613],"mapped",[4361]],[[12614,12614],"mapped",[4362]],[[12615,12615],"mapped",[4363]],[[12616,12616],"mapped",[4364]],[[12617,12617],"mapped",[4365]],[[12618,12618],"mapped",[4366]],[[12619,12619],"mapped",[4367]],[[12620,12620],"mapped",[4368]],[[12621,12621],"mapped",[4369]],[[12622,12622],"mapped",[4370]],[[12623,12623],"mapped",[4449]],[[12624,12624],"mapped",[4450]],[[12625,12625],"mapped",[4451]],[[12626,12626],"mapped",[4452]],[[12627,12627],"mapped",[4453]],[[12628,12628],"mapped",[4454]],[[12629,12629],"mapped",[4455]],[[12630,12630],"mapped",[4456]],[[12631,12631],"mapped",[4457]],[[12632,12632],"mapped",[4458]],[[12633,12633],"mapped",[4459]],[[12634,12634],"mapped",[4460]],[[12635,12635],"mapped",[4461]],[[12636,12636],"mapped",[4462]],[[12637,12637],"mapped",[4463]],[[12638,12638],"mapped",[4464]],[[12639,12639],"mapped",[4465]],[[12640,12640],"mapped",[4466]],[[12641,12641],"mapped",[4467]],[[12642,12642],"mapped",[4468]],[[12643,12643],"mapped",[4469]],[[12644,12644],"disallowed"],[[12645,12645],"mapped",[4372]],[[12646,12646],"mapped",[4373]],[[12647,12647],"mapped",[4551]],[[12648,12648],"mapped",[4552]],[[12649,12649],"mapped",[4556]],[[12650,12650],"mapped",[4558]],[[12651,12651],"mapped",[4563]],[[12652,12652],"mapped",[4567]],[[12653,12653],"mapped",[4569]],[[12654,12654],"mapped",[4380]],[[12655,12655],"mapped",[4573]],[[12656,12656],"mapped",[4575]],[[12657,12657],"mapped",[4381]],[[12658,12658],"mapped",[4382]],[[12659,12659],"mapped",[4384]],[[12660,12660],"mapped",[4386]],[[12661,12661],"mapped",[4387]],[[12662,12662],"mapped",[4391]],[[12663,12663],"mapped",[4393]],[[12664,12664],"mapped",[4395]],[[12665,12665],"mapped",[4396]],[[12666,12666],"mapped",[4397]],[[12667,12667],"mapped",[4398]],[[12668,12668],"mapped",[4399]],[[12669,12669],"mapped",[4402]],[[12670,12670],"mapped",[4406]],[[12671,12671],"mapped",[4416]],[[12672,12672],"mapped",[4423]],[[12673,12673],"mapped",[4428]],[[12674,12674],"mapped",[4593]],[[12675,12675],"mapped",[4594]],[[12676,12676],"mapped",[4439]],[[12677,12677],"mapped",[4440]],[[12678,12678],"mapped",[4441]],[[12679,12679],"mapped",[4484]],[[12680,12680],"mapped",[4485]],[[12681,12681],"mapped",[4488]],[[12682,12682],"mapped",[4497]],[[12683,12683],"mapped",[4498]],[[12684,12684],"mapped",[4500]],[[12685,12685],"mapped",[4510]],[[12686,12686],"mapped",[4513]],[[12687,12687],"disallowed"],[[12688,12689],"valid",[],"NV8"],[[12690,12690],"mapped",[19968]],[[12691,12691],"mapped",[20108]],[[12692,12692],"mapped",[19977]],[[12693,12693],"mapped",[22235]],[[12694,12694],"mapped",[19978]],[[12695,12695],"mapped",[20013]],[[12696,12696],"mapped",[19979]],[[12697,12697],"mapped",[30002]],[[12698,12698],"mapped",[20057]],[[12699,12699],"mapped",[19993]],[[12700,12700],"mapped",[19969]],[[12701,12701],"mapped",[22825]],[[12702,12702],"mapped",[22320]],[[12703,12703],"mapped",[20154]],[[12704,12727],"valid"],[[12728,12730],"valid"],[[12731,12735],"disallowed"],[[12736,12751],"valid",[],"NV8"],[[12752,12771],"valid",[],"NV8"],[[12772,12783],"disallowed"],[[12784,12799],"valid"],[[12800,12800],"disallowed_STD3_mapped",[40,4352,41]],[[12801,12801],"disallowed_STD3_mapped",[40,4354,41]],[[12802,12802],"disallowed_STD3_mapped",[40,4355,41]],[[12803,12803],"disallowed_STD3_mapped",[40,4357,41]],[[12804,12804],"disallowed_STD3_mapped",[40,4358,41]],[[12805,12805],"disallowed_STD3_mapped",[40,4359,41]],[[12806,12806],"disallowed_STD3_mapped",[40,4361,41]],[[12807,12807],"disallowed_STD3_mapped",[40,4363,41]],[[12808,12808],"disallowed_STD3_mapped",[40,4364,41]],[[12809,12809],"disallowed_STD3_mapped",[40,4366,41]],[[12810,12810],"disallowed_STD3_mapped",[40,4367,41]],[[12811,12811],"disallowed_STD3_mapped",[40,4368,41]],[[12812,12812],"disallowed_STD3_mapped",[40,4369,41]],[[12813,12813],"disallowed_STD3_mapped",[40,4370,41]],[[12814,12814],"disallowed_STD3_mapped",[40,44032,41]],[[12815,12815],"disallowed_STD3_mapped",[40,45208,41]],[[12816,12816],"disallowed_STD3_mapped",[40,45796,41]],[[12817,12817],"disallowed_STD3_mapped",[40,46972,41]],[[12818,12818],"disallowed_STD3_mapped",[40,47560,41]],[[12819,12819],"disallowed_STD3_mapped",[40,48148,41]],[[12820,12820],"disallowed_STD3_mapped",[40,49324,41]],[[12821,12821],"disallowed_STD3_mapped",[40,50500,41]],[[12822,12822],"disallowed_STD3_mapped",[40,51088,41]],[[12823,12823],"disallowed_STD3_mapped",[40,52264,41]],[[12824,12824],"disallowed_STD3_mapped",[40,52852,41]],[[12825,12825],"disallowed_STD3_mapped",[40,53440,41]],[[12826,12826],"disallowed_STD3_mapped",[40,54028,41]],[[12827,12827],"disallowed_STD3_mapped",[40,54616,41]],[[12828,12828],"disallowed_STD3_mapped",[40,51452,41]],[[12829,12829],"disallowed_STD3_mapped",[40,50724,51204,41]],[[12830,12830],"disallowed_STD3_mapped",[40,50724,54980,41]],[[12831,12831],"disallowed"],[[12832,12832],"disallowed_STD3_mapped",[40,19968,41]],[[12833,12833],"disallowed_STD3_mapped",[40,20108,41]],[[12834,12834],"disallowed_STD3_mapped",[40,19977,41]],[[12835,12835],"disallowed_STD3_mapped",[40,22235,41]],[[12836,12836],"disallowed_STD3_mapped",[40,20116,41]],[[12837,12837],"disallowed_STD3_mapped",[40,20845,41]],[[12838,12838],"disallowed_STD3_mapped",[40,19971,41]],[[12839,12839],"disallowed_STD3_mapped",[40,20843,41]],[[12840,12840],"disallowed_STD3_mapped",[40,20061,41]],[[12841,12841],"disallowed_STD3_mapped",[40,21313,41]],[[12842,12842],"disallowed_STD3_mapped",[40,26376,41]],[[12843,12843],"disallowed_STD3_mapped",[40,28779,41]],[[12844,12844],"disallowed_STD3_mapped",[40,27700,41]],[[12845,12845],"disallowed_STD3_mapped",[40,26408,41]],[[12846,12846],"disallowed_STD3_mapped",[40,37329,41]],[[12847,12847],"disallowed_STD3_mapped",[40,22303,41]],[[12848,12848],"disallowed_STD3_mapped",[40,26085,41]],[[12849,12849],"disallowed_STD3_mapped",[40,26666,41]],[[12850,12850],"disallowed_STD3_mapped",[40,26377,41]],[[12851,12851],"disallowed_STD3_mapped",[40,31038,41]],[[12852,12852],"disallowed_STD3_mapped",[40,21517,41]],[[12853,12853],"disallowed_STD3_mapped",[40,29305,41]],[[12854,12854],"disallowed_STD3_mapped",[40,36001,41]],[[12855,12855],"disallowed_STD3_mapped",[40,31069,41]],[[12856,12856],"disallowed_STD3_mapped",[40,21172,41]],[[12857,12857],"disallowed_STD3_mapped",[40,20195,41]],[[12858,12858],"disallowed_STD3_mapped",[40,21628,41]],[[12859,12859],"disallowed_STD3_mapped",[40,23398,41]],[[12860,12860],"disallowed_STD3_mapped",[40,30435,41]],[[12861,12861],"disallowed_STD3_mapped",[40,20225,41]],[[12862,12862],"disallowed_STD3_mapped",[40,36039,41]],[[12863,12863],"disallowed_STD3_mapped",[40,21332,41]],[[12864,12864],"disallowed_STD3_mapped",[40,31085,41]],[[12865,12865],"disallowed_STD3_mapped",[40,20241,41]],[[12866,12866],"disallowed_STD3_mapped",[40,33258,41]],[[12867,12867],"disallowed_STD3_mapped",[40,33267,41]],[[12868,12868],"mapped",[21839]],[[12869,12869],"mapped",[24188]],[[12870,12870],"mapped",[25991]],[[12871,12871],"mapped",[31631]],[[12872,12879],"valid",[],"NV8"],[[12880,12880],"mapped",[112,116,101]],[[12881,12881],"mapped",[50,49]],[[12882,12882],"mapped",[50,50]],[[12883,12883],"mapped",[50,51]],[[12884,12884],"mapped",[50,52]],[[12885,12885],"mapped",[50,53]],[[12886,12886],"mapped",[50,54]],[[12887,12887],"mapped",[50,55]],[[12888,12888],"mapped",[50,56]],[[12889,12889],"mapped",[50,57]],[[12890,12890],"mapped",[51,48]],[[12891,12891],"mapped",[51,49]],[[12892,12892],"mapped",[51,50]],[[12893,12893],"mapped",[51,51]],[[12894,12894],"mapped",[51,52]],[[12895,12895],"mapped",[51,53]],[[12896,12896],"mapped",[4352]],[[12897,12897],"mapped",[4354]],[[12898,12898],"mapped",[4355]],[[12899,12899],"mapped",[4357]],[[12900,12900],"mapped",[4358]],[[12901,12901],"mapped",[4359]],[[12902,12902],"mapped",[4361]],[[12903,12903],"mapped",[4363]],[[12904,12904],"mapped",[4364]],[[12905,12905],"mapped",[4366]],[[12906,12906],"mapped",[4367]],[[12907,12907],"mapped",[4368]],[[12908,12908],"mapped",[4369]],[[12909,12909],"mapped",[4370]],[[12910,12910],"mapped",[44032]],[[12911,12911],"mapped",[45208]],[[12912,12912],"mapped",[45796]],[[12913,12913],"mapped",[46972]],[[12914,12914],"mapped",[47560]],[[12915,12915],"mapped",[48148]],[[12916,12916],"mapped",[49324]],[[12917,12917],"mapped",[50500]],[[12918,12918],"mapped",[51088]],[[12919,12919],"mapped",[52264]],[[12920,12920],"mapped",[52852]],[[12921,12921],"mapped",[53440]],[[12922,12922],"mapped",[54028]],[[12923,12923],"mapped",[54616]],[[12924,12924],"mapped",[52280,44256]],[[12925,12925],"mapped",[51452,51032]],[[12926,12926],"mapped",[50864]],[[12927,12927],"valid",[],"NV8"],[[12928,12928],"mapped",[19968]],[[12929,12929],"mapped",[20108]],[[12930,12930],"mapped",[19977]],[[12931,12931],"mapped",[22235]],[[12932,12932],"mapped",[20116]],[[12933,12933],"mapped",[20845]],[[12934,12934],"mapped",[19971]],[[12935,12935],"mapped",[20843]],[[12936,12936],"mapped",[20061]],[[12937,12937],"mapped",[21313]],[[12938,12938],"mapped",[26376]],[[12939,12939],"mapped",[28779]],[[12940,12940],"mapped",[27700]],[[12941,12941],"mapped",[26408]],[[12942,12942],"mapped",[37329]],[[12943,12943],"mapped",[22303]],[[12944,12944],"mapped",[26085]],[[12945,12945],"mapped",[26666]],[[12946,12946],"mapped",[26377]],[[12947,12947],"mapped",[31038]],[[12948,12948],"mapped",[21517]],[[12949,12949],"mapped",[29305]],[[12950,12950],"mapped",[36001]],[[12951,12951],"mapped",[31069]],[[12952,12952],"mapped",[21172]],[[12953,12953],"mapped",[31192]],[[12954,12954],"mapped",[30007]],[[12955,12955],"mapped",[22899]],[[12956,12956],"mapped",[36969]],[[12957,12957],"mapped",[20778]],[[12958,12958],"mapped",[21360]],[[12959,12959],"mapped",[27880]],[[12960,12960],"mapped",[38917]],[[12961,12961],"mapped",[20241]],[[12962,12962],"mapped",[20889]],[[12963,12963],"mapped",[27491]],[[12964,12964],"mapped",[19978]],[[12965,12965],"mapped",[20013]],[[12966,12966],"mapped",[19979]],[[12967,12967],"mapped",[24038]],[[12968,12968],"mapped",[21491]],[[12969,12969],"mapped",[21307]],[[12970,12970],"mapped",[23447]],[[12971,12971],"mapped",[23398]],[[12972,12972],"mapped",[30435]],[[12973,12973],"mapped",[20225]],[[12974,12974],"mapped",[36039]],[[12975,12975],"mapped",[21332]],[[12976,12976],"mapped",[22812]],[[12977,12977],"mapped",[51,54]],[[12978,12978],"mapped",[51,55]],[[12979,12979],"mapped",[51,56]],[[12980,12980],"mapped",[51,57]],[[12981,12981],"mapped",[52,48]],[[12982,12982],"mapped",[52,49]],[[12983,12983],"mapped",[52,50]],[[12984,12984],"mapped",[52,51]],[[12985,12985],"mapped",[52,52]],[[12986,12986],"mapped",[52,53]],[[12987,12987],"mapped",[52,54]],[[12988,12988],"mapped",[52,55]],[[12989,12989],"mapped",[52,56]],[[12990,12990],"mapped",[52,57]],[[12991,12991],"mapped",[53,48]],[[12992,12992],"mapped",[49,26376]],[[12993,12993],"mapped",[50,26376]],[[12994,12994],"mapped",[51,26376]],[[12995,12995],"mapped",[52,26376]],[[12996,12996],"mapped",[53,26376]],[[12997,12997],"mapped",[54,26376]],[[12998,12998],"mapped",[55,26376]],[[12999,12999],"mapped",[56,26376]],[[13000,13000],"mapped",[57,26376]],[[13001,13001],"mapped",[49,48,26376]],[[13002,13002],"mapped",[49,49,26376]],[[13003,13003],"mapped",[49,50,26376]],[[13004,13004],"mapped",[104,103]],[[13005,13005],"mapped",[101,114,103]],[[13006,13006],"mapped",[101,118]],[[13007,13007],"mapped",[108,116,100]],[[13008,13008],"mapped",[12450]],[[13009,13009],"mapped",[12452]],[[13010,13010],"mapped",[12454]],[[13011,13011],"mapped",[12456]],[[13012,13012],"mapped",[12458]],[[13013,13013],"mapped",[12459]],[[13014,13014],"mapped",[12461]],[[13015,13015],"mapped",[12463]],[[13016,13016],"mapped",[12465]],[[13017,13017],"mapped",[12467]],[[13018,13018],"mapped",[12469]],[[13019,13019],"mapped",[12471]],[[13020,13020],"mapped",[12473]],[[13021,13021],"mapped",[12475]],[[13022,13022],"mapped",[12477]],[[13023,13023],"mapped",[12479]],[[13024,13024],"mapped",[12481]],[[13025,13025],"mapped",[12484]],[[13026,13026],"mapped",[12486]],[[13027,13027],"mapped",[12488]],[[13028,13028],"mapped",[12490]],[[13029,13029],"mapped",[12491]],[[13030,13030],"mapped",[12492]],[[13031,13031],"mapped",[12493]],[[13032,13032],"mapped",[12494]],[[13033,13033],"mapped",[12495]],[[13034,13034],"mapped",[12498]],[[13035,13035],"mapped",[12501]],[[13036,13036],"mapped",[12504]],[[13037,13037],"mapped",[12507]],[[13038,13038],"mapped",[12510]],[[13039,13039],"mapped",[12511]],[[13040,13040],"mapped",[12512]],[[13041,13041],"mapped",[12513]],[[13042,13042],"mapped",[12514]],[[13043,13043],"mapped",[12516]],[[13044,13044],"mapped",[12518]],[[13045,13045],"mapped",[12520]],[[13046,13046],"mapped",[12521]],[[13047,13047],"mapped",[12522]],[[13048,13048],"mapped",[12523]],[[13049,13049],"mapped",[12524]],[[13050,13050],"mapped",[12525]],[[13051,13051],"mapped",[12527]],[[13052,13052],"mapped",[12528]],[[13053,13053],"mapped",[12529]],[[13054,13054],"mapped",[12530]],[[13055,13055],"disallowed"],[[13056,13056],"mapped",[12450,12497,12540,12488]],[[13057,13057],"mapped",[12450,12523,12501,12449]],[[13058,13058],"mapped",[12450,12531,12506,12450]],[[13059,13059],"mapped",[12450,12540,12523]],[[13060,13060],"mapped",[12452,12491,12531,12464]],[[13061,13061],"mapped",[12452,12531,12481]],[[13062,13062],"mapped",[12454,12457,12531]],[[13063,13063],"mapped",[12456,12473,12463,12540,12489]],[[13064,13064],"mapped",[12456,12540,12459,12540]],[[13065,13065],"mapped",[12458,12531,12473]],[[13066,13066],"mapped",[12458,12540,12512]],[[13067,13067],"mapped",[12459,12452,12522]],[[13068,13068],"mapped",[12459,12521,12483,12488]],[[13069,13069],"mapped",[12459,12525,12522,12540]],[[13070,13070],"mapped",[12460,12525,12531]],[[13071,13071],"mapped",[12460,12531,12510]],[[13072,13072],"mapped",[12462,12460]],[[13073,13073],"mapped",[12462,12491,12540]],[[13074,13074],"mapped",[12461,12517,12522,12540]],[[13075,13075],"mapped",[12462,12523,12480,12540]],[[13076,13076],"mapped",[12461,12525]],[[13077,13077],"mapped",[12461,12525,12464,12521,12512]],[[13078,13078],"mapped",[12461,12525,12513,12540,12488,12523]],[[13079,13079],"mapped",[12461,12525,12527,12483,12488]],[[13080,13080],"mapped",[12464,12521,12512]],[[13081,13081],"mapped",[12464,12521,12512,12488,12531]],[[13082,13082],"mapped",[12463,12523,12476,12452,12525]],[[13083,13083],"mapped",[12463,12525,12540,12493]],[[13084,13084],"mapped",[12465,12540,12473]],[[13085,13085],"mapped",[12467,12523,12490]],[[13086,13086],"mapped",[12467,12540,12509]],[[13087,13087],"mapped",[12469,12452,12463,12523]],[[13088,13088],"mapped",[12469,12531,12481,12540,12512]],[[13089,13089],"mapped",[12471,12522,12531,12464]],[[13090,13090],"mapped",[12475,12531,12481]],[[13091,13091],"mapped",[12475,12531,12488]],[[13092,13092],"mapped",[12480,12540,12473]],[[13093,13093],"mapped",[12487,12471]],[[13094,13094],"mapped",[12489,12523]],[[13095,13095],"mapped",[12488,12531]],[[13096,13096],"mapped",[12490,12494]],[[13097,13097],"mapped",[12494,12483,12488]],[[13098,13098],"mapped",[12495,12452,12484]],[[13099,13099],"mapped",[12497,12540,12475,12531,12488]],[[13100,13100],"mapped",[12497,12540,12484]],[[13101,13101],"mapped",[12496,12540,12524,12523]],[[13102,13102],"mapped",[12500,12450,12473,12488,12523]],[[13103,13103],"mapped",[12500,12463,12523]],[[13104,13104],"mapped",[12500,12467]],[[13105,13105],"mapped",[12499,12523]],[[13106,13106],"mapped",[12501,12449,12521,12483,12489]],[[13107,13107],"mapped",[12501,12451,12540,12488]],[[13108,13108],"mapped",[12502,12483,12471,12455,12523]],[[13109,13109],"mapped",[12501,12521,12531]],[[13110,13110],"mapped",[12504,12463,12479,12540,12523]],[[13111,13111],"mapped",[12506,12477]],[[13112,13112],"mapped",[12506,12491,12498]],[[13113,13113],"mapped",[12504,12523,12484]],[[13114,13114],"mapped",[12506,12531,12473]],[[13115,13115],"mapped",[12506,12540,12472]],[[13116,13116],"mapped",[12505,12540,12479]],[[13117,13117],"mapped",[12509,12452,12531,12488]],[[13118,13118],"mapped",[12508,12523,12488]],[[13119,13119],"mapped",[12507,12531]],[[13120,13120],"mapped",[12509,12531,12489]],[[13121,13121],"mapped",[12507,12540,12523]],[[13122,13122],"mapped",[12507,12540,12531]],[[13123,13123],"mapped",[12510,12452,12463,12525]],[[13124,13124],"mapped",[12510,12452,12523]],[[13125,13125],"mapped",[12510,12483,12495]],[[13126,13126],"mapped",[12510,12523,12463]],[[13127,13127],"mapped",[12510,12531,12471,12519,12531]],[[13128,13128],"mapped",[12511,12463,12525,12531]],[[13129,13129],"mapped",[12511,12522]],[[13130,13130],"mapped",[12511,12522,12496,12540,12523]],[[13131,13131],"mapped",[12513,12460]],[[13132,13132],"mapped",[12513,12460,12488,12531]],[[13133,13133],"mapped",[12513,12540,12488,12523]],[[13134,13134],"mapped",[12516,12540,12489]],[[13135,13135],"mapped",[12516,12540,12523]],[[13136,13136],"mapped",[12518,12450,12531]],[[13137,13137],"mapped",[12522,12483,12488,12523]],[[13138,13138],"mapped",[12522,12521]],[[13139,13139],"mapped",[12523,12500,12540]],[[13140,13140],"mapped",[12523,12540,12502,12523]],[[13141,13141],"mapped",[12524,12512]],[[13142,13142],"mapped",[12524,12531,12488,12466,12531]],[[13143,13143],"mapped",[12527,12483,12488]],[[13144,13144],"mapped",[48,28857]],[[13145,13145],"mapped",[49,28857]],[[13146,13146],"mapped",[50,28857]],[[13147,13147],"mapped",[51,28857]],[[13148,13148],"mapped",[52,28857]],[[13149,13149],"mapped",[53,28857]],[[13150,13150],"mapped",[54,28857]],[[13151,13151],"mapped",[55,28857]],[[13152,13152],"mapped",[56,28857]],[[13153,13153],"mapped",[57,28857]],[[13154,13154],"mapped",[49,48,28857]],[[13155,13155],"mapped",[49,49,28857]],[[13156,13156],"mapped",[49,50,28857]],[[13157,13157],"mapped",[49,51,28857]],[[13158,13158],"mapped",[49,52,28857]],[[13159,13159],"mapped",[49,53,28857]],[[13160,13160],"mapped",[49,54,28857]],[[13161,13161],"mapped",[49,55,28857]],[[13162,13162],"mapped",[49,56,28857]],[[13163,13163],"mapped",[49,57,28857]],[[13164,13164],"mapped",[50,48,28857]],[[13165,13165],"mapped",[50,49,28857]],[[13166,13166],"mapped",[50,50,28857]],[[13167,13167],"mapped",[50,51,28857]],[[13168,13168],"mapped",[50,52,28857]],[[13169,13169],"mapped",[104,112,97]],[[13170,13170],"mapped",[100,97]],[[13171,13171],"mapped",[97,117]],[[13172,13172],"mapped",[98,97,114]],[[13173,13173],"mapped",[111,118]],[[13174,13174],"mapped",[112,99]],[[13175,13175],"mapped",[100,109]],[[13176,13176],"mapped",[100,109,50]],[[13177,13177],"mapped",[100,109,51]],[[13178,13178],"mapped",[105,117]],[[13179,13179],"mapped",[24179,25104]],[[13180,13180],"mapped",[26157,21644]],[[13181,13181],"mapped",[22823,27491]],[[13182,13182],"mapped",[26126,27835]],[[13183,13183],"mapped",[26666,24335,20250,31038]],[[13184,13184],"mapped",[112,97]],[[13185,13185],"mapped",[110,97]],[[13186,13186],"mapped",[956,97]],[[13187,13187],"mapped",[109,97]],[[13188,13188],"mapped",[107,97]],[[13189,13189],"mapped",[107,98]],[[13190,13190],"mapped",[109,98]],[[13191,13191],"mapped",[103,98]],[[13192,13192],"mapped",[99,97,108]],[[13193,13193],"mapped",[107,99,97,108]],[[13194,13194],"mapped",[112,102]],[[13195,13195],"mapped",[110,102]],[[13196,13196],"mapped",[956,102]],[[13197,13197],"mapped",[956,103]],[[13198,13198],"mapped",[109,103]],[[13199,13199],"mapped",[107,103]],[[13200,13200],"mapped",[104,122]],[[13201,13201],"mapped",[107,104,122]],[[13202,13202],"mapped",[109,104,122]],[[13203,13203],"mapped",[103,104,122]],[[13204,13204],"mapped",[116,104,122]],[[13205,13205],"mapped",[956,108]],[[13206,13206],"mapped",[109,108]],[[13207,13207],"mapped",[100,108]],[[13208,13208],"mapped",[107,108]],[[13209,13209],"mapped",[102,109]],[[13210,13210],"mapped",[110,109]],[[13211,13211],"mapped",[956,109]],[[13212,13212],"mapped",[109,109]],[[13213,13213],"mapped",[99,109]],[[13214,13214],"mapped",[107,109]],[[13215,13215],"mapped",[109,109,50]],[[13216,13216],"mapped",[99,109,50]],[[13217,13217],"mapped",[109,50]],[[13218,13218],"mapped",[107,109,50]],[[13219,13219],"mapped",[109,109,51]],[[13220,13220],"mapped",[99,109,51]],[[13221,13221],"mapped",[109,51]],[[13222,13222],"mapped",[107,109,51]],[[13223,13223],"mapped",[109,8725,115]],[[13224,13224],"mapped",[109,8725,115,50]],[[13225,13225],"mapped",[112,97]],[[13226,13226],"mapped",[107,112,97]],[[13227,13227],"mapped",[109,112,97]],[[13228,13228],"mapped",[103,112,97]],[[13229,13229],"mapped",[114,97,100]],[[13230,13230],"mapped",[114,97,100,8725,115]],[[13231,13231],"mapped",[114,97,100,8725,115,50]],[[13232,13232],"mapped",[112,115]],[[13233,13233],"mapped",[110,115]],[[13234,13234],"mapped",[956,115]],[[13235,13235],"mapped",[109,115]],[[13236,13236],"mapped",[112,118]],[[13237,13237],"mapped",[110,118]],[[13238,13238],"mapped",[956,118]],[[13239,13239],"mapped",[109,118]],[[13240,13240],"mapped",[107,118]],[[13241,13241],"mapped",[109,118]],[[13242,13242],"mapped",[112,119]],[[13243,13243],"mapped",[110,119]],[[13244,13244],"mapped",[956,119]],[[13245,13245],"mapped",[109,119]],[[13246,13246],"mapped",[107,119]],[[13247,13247],"mapped",[109,119]],[[13248,13248],"mapped",[107,969]],[[13249,13249],"mapped",[109,969]],[[13250,13250],"disallowed"],[[13251,13251],"mapped",[98,113]],[[13252,13252],"mapped",[99,99]],[[13253,13253],"mapped",[99,100]],[[13254,13254],"mapped",[99,8725,107,103]],[[13255,13255],"disallowed"],[[13256,13256],"mapped",[100,98]],[[13257,13257],"mapped",[103,121]],[[13258,13258],"mapped",[104,97]],[[13259,13259],"mapped",[104,112]],[[13260,13260],"mapped",[105,110]],[[13261,13261],"mapped",[107,107]],[[13262,13262],"mapped",[107,109]],[[13263,13263],"mapped",[107,116]],[[13264,13264],"mapped",[108,109]],[[13265,13265],"mapped",[108,110]],[[13266,13266],"mapped",[108,111,103]],[[13267,13267],"mapped",[108,120]],[[13268,13268],"mapped",[109,98]],[[13269,13269],"mapped",[109,105,108]],[[13270,13270],"mapped",[109,111,108]],[[13271,13271],"mapped",[112,104]],[[13272,13272],"disallowed"],[[13273,13273],"mapped",[112,112,109]],[[13274,13274],"mapped",[112,114]],[[13275,13275],"mapped",[115,114]],[[13276,13276],"mapped",[115,118]],[[13277,13277],"mapped",[119,98]],[[13278,13278],"mapped",[118,8725,109]],[[13279,13279],"mapped",[97,8725,109]],[[13280,13280],"mapped",[49,26085]],[[13281,13281],"mapped",[50,26085]],[[13282,13282],"mapped",[51,26085]],[[13283,13283],"mapped",[52,26085]],[[13284,13284],"mapped",[53,26085]],[[13285,13285],"mapped",[54,26085]],[[13286,13286],"mapped",[55,26085]],[[13287,13287],"mapped",[56,26085]],[[13288,13288],"mapped",[57,26085]],[[13289,13289],"mapped",[49,48,26085]],[[13290,13290],"mapped",[49,49,26085]],[[13291,13291],"mapped",[49,50,26085]],[[13292,13292],"mapped",[49,51,26085]],[[13293,13293],"mapped",[49,52,26085]],[[13294,13294],"mapped",[49,53,26085]],[[13295,13295],"mapped",[49,54,26085]],[[13296,13296],"mapped",[49,55,26085]],[[13297,13297],"mapped",[49,56,26085]],[[13298,13298],"mapped",[49,57,26085]],[[13299,13299],"mapped",[50,48,26085]],[[13300,13300],"mapped",[50,49,26085]],[[13301,13301],"mapped",[50,50,26085]],[[13302,13302],"mapped",[50,51,26085]],[[13303,13303],"mapped",[50,52,26085]],[[13304,13304],"mapped",[50,53,26085]],[[13305,13305],"mapped",[50,54,26085]],[[13306,13306],"mapped",[50,55,26085]],[[13307,13307],"mapped",[50,56,26085]],[[13308,13308],"mapped",[50,57,26085]],[[13309,13309],"mapped",[51,48,26085]],[[13310,13310],"mapped",[51,49,26085]],[[13311,13311],"mapped",[103,97,108]],[[13312,19893],"valid"],[[19894,19903],"disallowed"],[[19904,19967],"valid",[],"NV8"],[[19968,40869],"valid"],[[40870,40891],"valid"],[[40892,40899],"valid"],[[40900,40907],"valid"],[[40908,40908],"valid"],[[40909,40917],"valid"],[[40918,40959],"disallowed"],[[40960,42124],"valid"],[[42125,42127],"disallowed"],[[42128,42145],"valid",[],"NV8"],[[42146,42147],"valid",[],"NV8"],[[42148,42163],"valid",[],"NV8"],[[42164,42164],"valid",[],"NV8"],[[42165,42176],"valid",[],"NV8"],[[42177,42177],"valid",[],"NV8"],[[42178,42180],"valid",[],"NV8"],[[42181,42181],"valid",[],"NV8"],[[42182,42182],"valid",[],"NV8"],[[42183,42191],"disallowed"],[[42192,42237],"valid"],[[42238,42239],"valid",[],"NV8"],[[42240,42508],"valid"],[[42509,42511],"valid",[],"NV8"],[[42512,42539],"valid"],[[42540,42559],"disallowed"],[[42560,42560],"mapped",[42561]],[[42561,42561],"valid"],[[42562,42562],"mapped",[42563]],[[42563,42563],"valid"],[[42564,42564],"mapped",[42565]],[[42565,42565],"valid"],[[42566,42566],"mapped",[42567]],[[42567,42567],"valid"],[[42568,42568],"mapped",[42569]],[[42569,42569],"valid"],[[42570,42570],"mapped",[42571]],[[42571,42571],"valid"],[[42572,42572],"mapped",[42573]],[[42573,42573],"valid"],[[42574,42574],"mapped",[42575]],[[42575,42575],"valid"],[[42576,42576],"mapped",[42577]],[[42577,42577],"valid"],[[42578,42578],"mapped",[42579]],[[42579,42579],"valid"],[[42580,42580],"mapped",[42581]],[[42581,42581],"valid"],[[42582,42582],"mapped",[42583]],[[42583,42583],"valid"],[[42584,42584],"mapped",[42585]],[[42585,42585],"valid"],[[42586,42586],"mapped",[42587]],[[42587,42587],"valid"],[[42588,42588],"mapped",[42589]],[[42589,42589],"valid"],[[42590,42590],"mapped",[42591]],[[42591,42591],"valid"],[[42592,42592],"mapped",[42593]],[[42593,42593],"valid"],[[42594,42594],"mapped",[42595]],[[42595,42595],"valid"],[[42596,42596],"mapped",[42597]],[[42597,42597],"valid"],[[42598,42598],"mapped",[42599]],[[42599,42599],"valid"],[[42600,42600],"mapped",[42601]],[[42601,42601],"valid"],[[42602,42602],"mapped",[42603]],[[42603,42603],"valid"],[[42604,42604],"mapped",[42605]],[[42605,42607],"valid"],[[42608,42611],"valid",[],"NV8"],[[42612,42619],"valid"],[[42620,42621],"valid"],[[42622,42622],"valid",[],"NV8"],[[42623,42623],"valid"],[[42624,42624],"mapped",[42625]],[[42625,42625],"valid"],[[42626,42626],"mapped",[42627]],[[42627,42627],"valid"],[[42628,42628],"mapped",[42629]],[[42629,42629],"valid"],[[42630,42630],"mapped",[42631]],[[42631,42631],"valid"],[[42632,42632],"mapped",[42633]],[[42633,42633],"valid"],[[42634,42634],"mapped",[42635]],[[42635,42635],"valid"],[[42636,42636],"mapped",[42637]],[[42637,42637],"valid"],[[42638,42638],"mapped",[42639]],[[42639,42639],"valid"],[[42640,42640],"mapped",[42641]],[[42641,42641],"valid"],[[42642,42642],"mapped",[42643]],[[42643,42643],"valid"],[[42644,42644],"mapped",[42645]],[[42645,42645],"valid"],[[42646,42646],"mapped",[42647]],[[42647,42647],"valid"],[[42648,42648],"mapped",[42649]],[[42649,42649],"valid"],[[42650,42650],"mapped",[42651]],[[42651,42651],"valid"],[[42652,42652],"mapped",[1098]],[[42653,42653],"mapped",[1100]],[[42654,42654],"valid"],[[42655,42655],"valid"],[[42656,42725],"valid"],[[42726,42735],"valid",[],"NV8"],[[42736,42737],"valid"],[[42738,42743],"valid",[],"NV8"],[[42744,42751],"disallowed"],[[42752,42774],"valid",[],"NV8"],[[42775,42778],"valid"],[[42779,42783],"valid"],[[42784,42785],"valid",[],"NV8"],[[42786,42786],"mapped",[42787]],[[42787,42787],"valid"],[[42788,42788],"mapped",[42789]],[[42789,42789],"valid"],[[42790,42790],"mapped",[42791]],[[42791,42791],"valid"],[[42792,42792],"mapped",[42793]],[[42793,42793],"valid"],[[42794,42794],"mapped",[42795]],[[42795,42795],"valid"],[[42796,42796],"mapped",[42797]],[[42797,42797],"valid"],[[42798,42798],"mapped",[42799]],[[42799,42801],"valid"],[[42802,42802],"mapped",[42803]],[[42803,42803],"valid"],[[42804,42804],"mapped",[42805]],[[42805,42805],"valid"],[[42806,42806],"mapped",[42807]],[[42807,42807],"valid"],[[42808,42808],"mapped",[42809]],[[42809,42809],"valid"],[[42810,42810],"mapped",[42811]],[[42811,42811],"valid"],[[42812,42812],"mapped",[42813]],[[42813,42813],"valid"],[[42814,42814],"mapped",[42815]],[[42815,42815],"valid"],[[42816,42816],"mapped",[42817]],[[42817,42817],"valid"],[[42818,42818],"mapped",[42819]],[[42819,42819],"valid"],[[42820,42820],"mapped",[42821]],[[42821,42821],"valid"],[[42822,42822],"mapped",[42823]],[[42823,42823],"valid"],[[42824,42824],"mapped",[42825]],[[42825,42825],"valid"],[[42826,42826],"mapped",[42827]],[[42827,42827],"valid"],[[42828,42828],"mapped",[42829]],[[42829,42829],"valid"],[[42830,42830],"mapped",[42831]],[[42831,42831],"valid"],[[42832,42832],"mapped",[42833]],[[42833,42833],"valid"],[[42834,42834],"mapped",[42835]],[[42835,42835],"valid"],[[42836,42836],"mapped",[42837]],[[42837,42837],"valid"],[[42838,42838],"mapped",[42839]],[[42839,42839],"valid"],[[42840,42840],"mapped",[42841]],[[42841,42841],"valid"],[[42842,42842],"mapped",[42843]],[[42843,42843],"valid"],[[42844,42844],"mapped",[42845]],[[42845,42845],"valid"],[[42846,42846],"mapped",[42847]],[[42847,42847],"valid"],[[42848,42848],"mapped",[42849]],[[42849,42849],"valid"],[[42850,42850],"mapped",[42851]],[[42851,42851],"valid"],[[42852,42852],"mapped",[42853]],[[42853,42853],"valid"],[[42854,42854],"mapped",[42855]],[[42855,42855],"valid"],[[42856,42856],"mapped",[42857]],[[42857,42857],"valid"],[[42858,42858],"mapped",[42859]],[[42859,42859],"valid"],[[42860,42860],"mapped",[42861]],[[42861,42861],"valid"],[[42862,42862],"mapped",[42863]],[[42863,42863],"valid"],[[42864,42864],"mapped",[42863]],[[42865,42872],"valid"],[[42873,42873],"mapped",[42874]],[[42874,42874],"valid"],[[42875,42875],"mapped",[42876]],[[42876,42876],"valid"],[[42877,42877],"mapped",[7545]],[[42878,42878],"mapped",[42879]],[[42879,42879],"valid"],[[42880,42880],"mapped",[42881]],[[42881,42881],"valid"],[[42882,42882],"mapped",[42883]],[[42883,42883],"valid"],[[42884,42884],"mapped",[42885]],[[42885,42885],"valid"],[[42886,42886],"mapped",[42887]],[[42887,42888],"valid"],[[42889,42890],"valid",[],"NV8"],[[42891,42891],"mapped",[42892]],[[42892,42892],"valid"],[[42893,42893],"mapped",[613]],[[42894,42894],"valid"],[[42895,42895],"valid"],[[42896,42896],"mapped",[42897]],[[42897,42897],"valid"],[[42898,42898],"mapped",[42899]],[[42899,42899],"valid"],[[42900,42901],"valid"],[[42902,42902],"mapped",[42903]],[[42903,42903],"valid"],[[42904,42904],"mapped",[42905]],[[42905,42905],"valid"],[[42906,42906],"mapped",[42907]],[[42907,42907],"valid"],[[42908,42908],"mapped",[42909]],[[42909,42909],"valid"],[[42910,42910],"mapped",[42911]],[[42911,42911],"valid"],[[42912,42912],"mapped",[42913]],[[42913,42913],"valid"],[[42914,42914],"mapped",[42915]],[[42915,42915],"valid"],[[42916,42916],"mapped",[42917]],[[42917,42917],"valid"],[[42918,42918],"mapped",[42919]],[[42919,42919],"valid"],[[42920,42920],"mapped",[42921]],[[42921,42921],"valid"],[[42922,42922],"mapped",[614]],[[42923,42923],"mapped",[604]],[[42924,42924],"mapped",[609]],[[42925,42925],"mapped",[620]],[[42926,42927],"disallowed"],[[42928,42928],"mapped",[670]],[[42929,42929],"mapped",[647]],[[42930,42930],"mapped",[669]],[[42931,42931],"mapped",[43859]],[[42932,42932],"mapped",[42933]],[[42933,42933],"valid"],[[42934,42934],"mapped",[42935]],[[42935,42935],"valid"],[[42936,42998],"disallowed"],[[42999,42999],"valid"],[[43000,43000],"mapped",[295]],[[43001,43001],"mapped",[339]],[[43002,43002],"valid"],[[43003,43007],"valid"],[[43008,43047],"valid"],[[43048,43051],"valid",[],"NV8"],[[43052,43055],"disallowed"],[[43056,43065],"valid",[],"NV8"],[[43066,43071],"disallowed"],[[43072,43123],"valid"],[[43124,43127],"valid",[],"NV8"],[[43128,43135],"disallowed"],[[43136,43204],"valid"],[[43205,43213],"disallowed"],[[43214,43215],"valid",[],"NV8"],[[43216,43225],"valid"],[[43226,43231],"disallowed"],[[43232,43255],"valid"],[[43256,43258],"valid",[],"NV8"],[[43259,43259],"valid"],[[43260,43260],"valid",[],"NV8"],[[43261,43261],"valid"],[[43262,43263],"disallowed"],[[43264,43309],"valid"],[[43310,43311],"valid",[],"NV8"],[[43312,43347],"valid"],[[43348,43358],"disallowed"],[[43359,43359],"valid",[],"NV8"],[[43360,43388],"valid",[],"NV8"],[[43389,43391],"disallowed"],[[43392,43456],"valid"],[[43457,43469],"valid",[],"NV8"],[[43470,43470],"disallowed"],[[43471,43481],"valid"],[[43482,43485],"disallowed"],[[43486,43487],"valid",[],"NV8"],[[43488,43518],"valid"],[[43519,43519],"disallowed"],[[43520,43574],"valid"],[[43575,43583],"disallowed"],[[43584,43597],"valid"],[[43598,43599],"disallowed"],[[43600,43609],"valid"],[[43610,43611],"disallowed"],[[43612,43615],"valid",[],"NV8"],[[43616,43638],"valid"],[[43639,43641],"valid",[],"NV8"],[[43642,43643],"valid"],[[43644,43647],"valid"],[[43648,43714],"valid"],[[43715,43738],"disallowed"],[[43739,43741],"valid"],[[43742,43743],"valid",[],"NV8"],[[43744,43759],"valid"],[[43760,43761],"valid",[],"NV8"],[[43762,43766],"valid"],[[43767,43776],"disallowed"],[[43777,43782],"valid"],[[43783,43784],"disallowed"],[[43785,43790],"valid"],[[43791,43792],"disallowed"],[[43793,43798],"valid"],[[43799,43807],"disallowed"],[[43808,43814],"valid"],[[43815,43815],"disallowed"],[[43816,43822],"valid"],[[43823,43823],"disallowed"],[[43824,43866],"valid"],[[43867,43867],"valid",[],"NV8"],[[43868,43868],"mapped",[42791]],[[43869,43869],"mapped",[43831]],[[43870,43870],"mapped",[619]],[[43871,43871],"mapped",[43858]],[[43872,43875],"valid"],[[43876,43877],"valid"],[[43878,43887],"disallowed"],[[43888,43888],"mapped",[5024]],[[43889,43889],"mapped",[5025]],[[43890,43890],"mapped",[5026]],[[43891,43891],"mapped",[5027]],[[43892,43892],"mapped",[5028]],[[43893,43893],"mapped",[5029]],[[43894,43894],"mapped",[5030]],[[43895,43895],"mapped",[5031]],[[43896,43896],"mapped",[5032]],[[43897,43897],"mapped",[5033]],[[43898,43898],"mapped",[5034]],[[43899,43899],"mapped",[5035]],[[43900,43900],"mapped",[5036]],[[43901,43901],"mapped",[5037]],[[43902,43902],"mapped",[5038]],[[43903,43903],"mapped",[5039]],[[43904,43904],"mapped",[5040]],[[43905,43905],"mapped",[5041]],[[43906,43906],"mapped",[5042]],[[43907,43907],"mapped",[5043]],[[43908,43908],"mapped",[5044]],[[43909,43909],"mapped",[5045]],[[43910,43910],"mapped",[5046]],[[43911,43911],"mapped",[5047]],[[43912,43912],"mapped",[5048]],[[43913,43913],"mapped",[5049]],[[43914,43914],"mapped",[5050]],[[43915,43915],"mapped",[5051]],[[43916,43916],"mapped",[5052]],[[43917,43917],"mapped",[5053]],[[43918,43918],"mapped",[5054]],[[43919,43919],"mapped",[5055]],[[43920,43920],"mapped",[5056]],[[43921,43921],"mapped",[5057]],[[43922,43922],"mapped",[5058]],[[43923,43923],"mapped",[5059]],[[43924,43924],"mapped",[5060]],[[43925,43925],"mapped",[5061]],[[43926,43926],"mapped",[5062]],[[43927,43927],"mapped",[5063]],[[43928,43928],"mapped",[5064]],[[43929,43929],"mapped",[5065]],[[43930,43930],"mapped",[5066]],[[43931,43931],"mapped",[5067]],[[43932,43932],"mapped",[5068]],[[43933,43933],"mapped",[5069]],[[43934,43934],"mapped",[5070]],[[43935,43935],"mapped",[5071]],[[43936,43936],"mapped",[5072]],[[43937,43937],"mapped",[5073]],[[43938,43938],"mapped",[5074]],[[43939,43939],"mapped",[5075]],[[43940,43940],"mapped",[5076]],[[43941,43941],"mapped",[5077]],[[43942,43942],"mapped",[5078]],[[43943,43943],"mapped",[5079]],[[43944,43944],"mapped",[5080]],[[43945,43945],"mapped",[5081]],[[43946,43946],"mapped",[5082]],[[43947,43947],"mapped",[5083]],[[43948,43948],"mapped",[5084]],[[43949,43949],"mapped",[5085]],[[43950,43950],"mapped",[5086]],[[43951,43951],"mapped",[5087]],[[43952,43952],"mapped",[5088]],[[43953,43953],"mapped",[5089]],[[43954,43954],"mapped",[5090]],[[43955,43955],"mapped",[5091]],[[43956,43956],"mapped",[5092]],[[43957,43957],"mapped",[5093]],[[43958,43958],"mapped",[5094]],[[43959,43959],"mapped",[5095]],[[43960,43960],"mapped",[5096]],[[43961,43961],"mapped",[5097]],[[43962,43962],"mapped",[5098]],[[43963,43963],"mapped",[5099]],[[43964,43964],"mapped",[5100]],[[43965,43965],"mapped",[5101]],[[43966,43966],"mapped",[5102]],[[43967,43967],"mapped",[5103]],[[43968,44010],"valid"],[[44011,44011],"valid",[],"NV8"],[[44012,44013],"valid"],[[44014,44015],"disallowed"],[[44016,44025],"valid"],[[44026,44031],"disallowed"],[[44032,55203],"valid"],[[55204,55215],"disallowed"],[[55216,55238],"valid",[],"NV8"],[[55239,55242],"disallowed"],[[55243,55291],"valid",[],"NV8"],[[55292,55295],"disallowed"],[[55296,57343],"disallowed"],[[57344,63743],"disallowed"],[[63744,63744],"mapped",[35912]],[[63745,63745],"mapped",[26356]],[[63746,63746],"mapped",[36554]],[[63747,63747],"mapped",[36040]],[[63748,63748],"mapped",[28369]],[[63749,63749],"mapped",[20018]],[[63750,63750],"mapped",[21477]],[[63751,63752],"mapped",[40860]],[[63753,63753],"mapped",[22865]],[[63754,63754],"mapped",[37329]],[[63755,63755],"mapped",[21895]],[[63756,63756],"mapped",[22856]],[[63757,63757],"mapped",[25078]],[[63758,63758],"mapped",[30313]],[[63759,63759],"mapped",[32645]],[[63760,63760],"mapped",[34367]],[[63761,63761],"mapped",[34746]],[[63762,63762],"mapped",[35064]],[[63763,63763],"mapped",[37007]],[[63764,63764],"mapped",[27138]],[[63765,63765],"mapped",[27931]],[[63766,63766],"mapped",[28889]],[[63767,63767],"mapped",[29662]],[[63768,63768],"mapped",[33853]],[[63769,63769],"mapped",[37226]],[[63770,63770],"mapped",[39409]],[[63771,63771],"mapped",[20098]],[[63772,63772],"mapped",[21365]],[[63773,63773],"mapped",[27396]],[[63774,63774],"mapped",[29211]],[[63775,63775],"mapped",[34349]],[[63776,63776],"mapped",[40478]],[[63777,63777],"mapped",[23888]],[[63778,63778],"mapped",[28651]],[[63779,63779],"mapped",[34253]],[[63780,63780],"mapped",[35172]],[[63781,63781],"mapped",[25289]],[[63782,63782],"mapped",[33240]],[[63783,63783],"mapped",[34847]],[[63784,63784],"mapped",[24266]],[[63785,63785],"mapped",[26391]],[[63786,63786],"mapped",[28010]],[[63787,63787],"mapped",[29436]],[[63788,63788],"mapped",[37070]],[[63789,63789],"mapped",[20358]],[[63790,63790],"mapped",[20919]],[[63791,63791],"mapped",[21214]],[[63792,63792],"mapped",[25796]],[[63793,63793],"mapped",[27347]],[[63794,63794],"mapped",[29200]],[[63795,63795],"mapped",[30439]],[[63796,63796],"mapped",[32769]],[[63797,63797],"mapped",[34310]],[[63798,63798],"mapped",[34396]],[[63799,63799],"mapped",[36335]],[[63800,63800],"mapped",[38706]],[[63801,63801],"mapped",[39791]],[[63802,63802],"mapped",[40442]],[[63803,63803],"mapped",[30860]],[[63804,63804],"mapped",[31103]],[[63805,63805],"mapped",[32160]],[[63806,63806],"mapped",[33737]],[[63807,63807],"mapped",[37636]],[[63808,63808],"mapped",[40575]],[[63809,63809],"mapped",[35542]],[[63810,63810],"mapped",[22751]],[[63811,63811],"mapped",[24324]],[[63812,63812],"mapped",[31840]],[[63813,63813],"mapped",[32894]],[[63814,63814],"mapped",[29282]],[[63815,63815],"mapped",[30922]],[[63816,63816],"mapped",[36034]],[[63817,63817],"mapped",[38647]],[[63818,63818],"mapped",[22744]],[[63819,63819],"mapped",[23650]],[[63820,63820],"mapped",[27155]],[[63821,63821],"mapped",[28122]],[[63822,63822],"mapped",[28431]],[[63823,63823],"mapped",[32047]],[[63824,63824],"mapped",[32311]],[[63825,63825],"mapped",[38475]],[[63826,63826],"mapped",[21202]],[[63827,63827],"mapped",[32907]],[[63828,63828],"mapped",[20956]],[[63829,63829],"mapped",[20940]],[[63830,63830],"mapped",[31260]],[[63831,63831],"mapped",[32190]],[[63832,63832],"mapped",[33777]],[[63833,63833],"mapped",[38517]],[[63834,63834],"mapped",[35712]],[[63835,63835],"mapped",[25295]],[[63836,63836],"mapped",[27138]],[[63837,63837],"mapped",[35582]],[[63838,63838],"mapped",[20025]],[[63839,63839],"mapped",[23527]],[[63840,63840],"mapped",[24594]],[[63841,63841],"mapped",[29575]],[[63842,63842],"mapped",[30064]],[[63843,63843],"mapped",[21271]],[[63844,63844],"mapped",[30971]],[[63845,63845],"mapped",[20415]],[[63846,63846],"mapped",[24489]],[[63847,63847],"mapped",[19981]],[[63848,63848],"mapped",[27852]],[[63849,63849],"mapped",[25976]],[[63850,63850],"mapped",[32034]],[[63851,63851],"mapped",[21443]],[[63852,63852],"mapped",[22622]],[[63853,63853],"mapped",[30465]],[[63854,63854],"mapped",[33865]],[[63855,63855],"mapped",[35498]],[[63856,63856],"mapped",[27578]],[[63857,63857],"mapped",[36784]],[[63858,63858],"mapped",[27784]],[[63859,63859],"mapped",[25342]],[[63860,63860],"mapped",[33509]],[[63861,63861],"mapped",[25504]],[[63862,63862],"mapped",[30053]],[[63863,63863],"mapped",[20142]],[[63864,63864],"mapped",[20841]],[[63865,63865],"mapped",[20937]],[[63866,63866],"mapped",[26753]],[[63867,63867],"mapped",[31975]],[[63868,63868],"mapped",[33391]],[[63869,63869],"mapped",[35538]],[[63870,63870],"mapped",[37327]],[[63871,63871],"mapped",[21237]],[[63872,63872],"mapped",[21570]],[[63873,63873],"mapped",[22899]],[[63874,63874],"mapped",[24300]],[[63875,63875],"mapped",[26053]],[[63876,63876],"mapped",[28670]],[[63877,63877],"mapped",[31018]],[[63878,63878],"mapped",[38317]],[[63879,63879],"mapped",[39530]],[[63880,63880],"mapped",[40599]],[[63881,63881],"mapped",[40654]],[[63882,63882],"mapped",[21147]],[[63883,63883],"mapped",[26310]],[[63884,63884],"mapped",[27511]],[[63885,63885],"mapped",[36706]],[[63886,63886],"mapped",[24180]],[[63887,63887],"mapped",[24976]],[[63888,63888],"mapped",[25088]],[[63889,63889],"mapped",[25754]],[[63890,63890],"mapped",[28451]],[[63891,63891],"mapped",[29001]],[[63892,63892],"mapped",[29833]],[[63893,63893],"mapped",[31178]],[[63894,63894],"mapped",[32244]],[[63895,63895],"mapped",[32879]],[[63896,63896],"mapped",[36646]],[[63897,63897],"mapped",[34030]],[[63898,63898],"mapped",[36899]],[[63899,63899],"mapped",[37706]],[[63900,63900],"mapped",[21015]],[[63901,63901],"mapped",[21155]],[[63902,63902],"mapped",[21693]],[[63903,63903],"mapped",[28872]],[[63904,63904],"mapped",[35010]],[[63905,63905],"mapped",[35498]],[[63906,63906],"mapped",[24265]],[[63907,63907],"mapped",[24565]],[[63908,63908],"mapped",[25467]],[[63909,63909],"mapped",[27566]],[[63910,63910],"mapped",[31806]],[[63911,63911],"mapped",[29557]],[[63912,63912],"mapped",[20196]],[[63913,63913],"mapped",[22265]],[[63914,63914],"mapped",[23527]],[[63915,63915],"mapped",[23994]],[[63916,63916],"mapped",[24604]],[[63917,63917],"mapped",[29618]],[[63918,63918],"mapped",[29801]],[[63919,63919],"mapped",[32666]],[[63920,63920],"mapped",[32838]],[[63921,63921],"mapped",[37428]],[[63922,63922],"mapped",[38646]],[[63923,63923],"mapped",[38728]],[[63924,63924],"mapped",[38936]],[[63925,63925],"mapped",[20363]],[[63926,63926],"mapped",[31150]],[[63927,63927],"mapped",[37300]],[[63928,63928],"mapped",[38584]],[[63929,63929],"mapped",[24801]],[[63930,63930],"mapped",[20102]],[[63931,63931],"mapped",[20698]],[[63932,63932],"mapped",[23534]],[[63933,63933],"mapped",[23615]],[[63934,63934],"mapped",[26009]],[[63935,63935],"mapped",[27138]],[[63936,63936],"mapped",[29134]],[[63937,63937],"mapped",[30274]],[[63938,63938],"mapped",[34044]],[[63939,63939],"mapped",[36988]],[[63940,63940],"mapped",[40845]],[[63941,63941],"mapped",[26248]],[[63942,63942],"mapped",[38446]],[[63943,63943],"mapped",[21129]],[[63944,63944],"mapped",[26491]],[[63945,63945],"mapped",[26611]],[[63946,63946],"mapped",[27969]],[[63947,63947],"mapped",[28316]],[[63948,63948],"mapped",[29705]],[[63949,63949],"mapped",[30041]],[[63950,63950],"mapped",[30827]],[[63951,63951],"mapped",[32016]],[[63952,63952],"mapped",[39006]],[[63953,63953],"mapped",[20845]],[[63954,63954],"mapped",[25134]],[[63955,63955],"mapped",[38520]],[[63956,63956],"mapped",[20523]],[[63957,63957],"mapped",[23833]],[[63958,63958],"mapped",[28138]],[[63959,63959],"mapped",[36650]],[[63960,63960],"mapped",[24459]],[[63961,63961],"mapped",[24900]],[[63962,63962],"mapped",[26647]],[[63963,63963],"mapped",[29575]],[[63964,63964],"mapped",[38534]],[[63965,63965],"mapped",[21033]],[[63966,63966],"mapped",[21519]],[[63967,63967],"mapped",[23653]],[[63968,63968],"mapped",[26131]],[[63969,63969],"mapped",[26446]],[[63970,63970],"mapped",[26792]],[[63971,63971],"mapped",[27877]],[[63972,63972],"mapped",[29702]],[[63973,63973],"mapped",[30178]],[[63974,63974],"mapped",[32633]],[[63975,63975],"mapped",[35023]],[[63976,63976],"mapped",[35041]],[[63977,63977],"mapped",[37324]],[[63978,63978],"mapped",[38626]],[[63979,63979],"mapped",[21311]],[[63980,63980],"mapped",[28346]],[[63981,63981],"mapped",[21533]],[[63982,63982],"mapped",[29136]],[[63983,63983],"mapped",[29848]],[[63984,63984],"mapped",[34298]],[[63985,63985],"mapped",[38563]],[[63986,63986],"mapped",[40023]],[[63987,63987],"mapped",[40607]],[[63988,63988],"mapped",[26519]],[[63989,63989],"mapped",[28107]],[[63990,63990],"mapped",[33256]],[[63991,63991],"mapped",[31435]],[[63992,63992],"mapped",[31520]],[[63993,63993],"mapped",[31890]],[[63994,63994],"mapped",[29376]],[[63995,63995],"mapped",[28825]],[[63996,63996],"mapped",[35672]],[[63997,63997],"mapped",[20160]],[[63998,63998],"mapped",[33590]],[[63999,63999],"mapped",[21050]],[[64000,64000],"mapped",[20999]],[[64001,64001],"mapped",[24230]],[[64002,64002],"mapped",[25299]],[[64003,64003],"mapped",[31958]],[[64004,64004],"mapped",[23429]],[[64005,64005],"mapped",[27934]],[[64006,64006],"mapped",[26292]],[[64007,64007],"mapped",[36667]],[[64008,64008],"mapped",[34892]],[[64009,64009],"mapped",[38477]],[[64010,64010],"mapped",[35211]],[[64011,64011],"mapped",[24275]],[[64012,64012],"mapped",[20800]],[[64013,64013],"mapped",[21952]],[[64014,64015],"valid"],[[64016,64016],"mapped",[22618]],[[64017,64017],"valid"],[[64018,64018],"mapped",[26228]],[[64019,64020],"valid"],[[64021,64021],"mapped",[20958]],[[64022,64022],"mapped",[29482]],[[64023,64023],"mapped",[30410]],[[64024,64024],"mapped",[31036]],[[64025,64025],"mapped",[31070]],[[64026,64026],"mapped",[31077]],[[64027,64027],"mapped",[31119]],[[64028,64028],"mapped",[38742]],[[64029,64029],"mapped",[31934]],[[64030,64030],"mapped",[32701]],[[64031,64031],"valid"],[[64032,64032],"mapped",[34322]],[[64033,64033],"valid"],[[64034,64034],"mapped",[35576]],[[64035,64036],"valid"],[[64037,64037],"mapped",[36920]],[[64038,64038],"mapped",[37117]],[[64039,64041],"valid"],[[64042,64042],"mapped",[39151]],[[64043,64043],"mapped",[39164]],[[64044,64044],"mapped",[39208]],[[64045,64045],"mapped",[40372]],[[64046,64046],"mapped",[37086]],[[64047,64047],"mapped",[38583]],[[64048,64048],"mapped",[20398]],[[64049,64049],"mapped",[20711]],[[64050,64050],"mapped",[20813]],[[64051,64051],"mapped",[21193]],[[64052,64052],"mapped",[21220]],[[64053,64053],"mapped",[21329]],[[64054,64054],"mapped",[21917]],[[64055,64055],"mapped",[22022]],[[64056,64056],"mapped",[22120]],[[64057,64057],"mapped",[22592]],[[64058,64058],"mapped",[22696]],[[64059,64059],"mapped",[23652]],[[64060,64060],"mapped",[23662]],[[64061,64061],"mapped",[24724]],[[64062,64062],"mapped",[24936]],[[64063,64063],"mapped",[24974]],[[64064,64064],"mapped",[25074]],[[64065,64065],"mapped",[25935]],[[64066,64066],"mapped",[26082]],[[64067,64067],"mapped",[26257]],[[64068,64068],"mapped",[26757]],[[64069,64069],"mapped",[28023]],[[64070,64070],"mapped",[28186]],[[64071,64071],"mapped",[28450]],[[64072,64072],"mapped",[29038]],[[64073,64073],"mapped",[29227]],[[64074,64074],"mapped",[29730]],[[64075,64075],"mapped",[30865]],[[64076,64076],"mapped",[31038]],[[64077,64077],"mapped",[31049]],[[64078,64078],"mapped",[31048]],[[64079,64079],"mapped",[31056]],[[64080,64080],"mapped",[31062]],[[64081,64081],"mapped",[31069]],[[64082,64082],"mapped",[31117]],[[64083,64083],"mapped",[31118]],[[64084,64084],"mapped",[31296]],[[64085,64085],"mapped",[31361]],[[64086,64086],"mapped",[31680]],[[64087,64087],"mapped",[32244]],[[64088,64088],"mapped",[32265]],[[64089,64089],"mapped",[32321]],[[64090,64090],"mapped",[32626]],[[64091,64091],"mapped",[32773]],[[64092,64092],"mapped",[33261]],[[64093,64094],"mapped",[33401]],[[64095,64095],"mapped",[33879]],[[64096,64096],"mapped",[35088]],[[64097,64097],"mapped",[35222]],[[64098,64098],"mapped",[35585]],[[64099,64099],"mapped",[35641]],[[64100,64100],"mapped",[36051]],[[64101,64101],"mapped",[36104]],[[64102,64102],"mapped",[36790]],[[64103,64103],"mapped",[36920]],[[64104,64104],"mapped",[38627]],[[64105,64105],"mapped",[38911]],[[64106,64106],"mapped",[38971]],[[64107,64107],"mapped",[24693]],[[64108,64108],"mapped",[148206]],[[64109,64109],"mapped",[33304]],[[64110,64111],"disallowed"],[[64112,64112],"mapped",[20006]],[[64113,64113],"mapped",[20917]],[[64114,64114],"mapped",[20840]],[[64115,64115],"mapped",[20352]],[[64116,64116],"mapped",[20805]],[[64117,64117],"mapped",[20864]],[[64118,64118],"mapped",[21191]],[[64119,64119],"mapped",[21242]],[[64120,64120],"mapped",[21917]],[[64121,64121],"mapped",[21845]],[[64122,64122],"mapped",[21913]],[[64123,64123],"mapped",[21986]],[[64124,64124],"mapped",[22618]],[[64125,64125],"mapped",[22707]],[[64126,64126],"mapped",[22852]],[[64127,64127],"mapped",[22868]],[[64128,64128],"mapped",[23138]],[[64129,64129],"mapped",[23336]],[[64130,64130],"mapped",[24274]],[[64131,64131],"mapped",[24281]],[[64132,64132],"mapped",[24425]],[[64133,64133],"mapped",[24493]],[[64134,64134],"mapped",[24792]],[[64135,64135],"mapped",[24910]],[[64136,64136],"mapped",[24840]],[[64137,64137],"mapped",[24974]],[[64138,64138],"mapped",[24928]],[[64139,64139],"mapped",[25074]],[[64140,64140],"mapped",[25140]],[[64141,64141],"mapped",[25540]],[[64142,64142],"mapped",[25628]],[[64143,64143],"mapped",[25682]],[[64144,64144],"mapped",[25942]],[[64145,64145],"mapped",[26228]],[[64146,64146],"mapped",[26391]],[[64147,64147],"mapped",[26395]],[[64148,64148],"mapped",[26454]],[[64149,64149],"mapped",[27513]],[[64150,64150],"mapped",[27578]],[[64151,64151],"mapped",[27969]],[[64152,64152],"mapped",[28379]],[[64153,64153],"mapped",[28363]],[[64154,64154],"mapped",[28450]],[[64155,64155],"mapped",[28702]],[[64156,64156],"mapped",[29038]],[[64157,64157],"mapped",[30631]],[[64158,64158],"mapped",[29237]],[[64159,64159],"mapped",[29359]],[[64160,64160],"mapped",[29482]],[[64161,64161],"mapped",[29809]],[[64162,64162],"mapped",[29958]],[[64163,64163],"mapped",[30011]],[[64164,64164],"mapped",[30237]],[[64165,64165],"mapped",[30239]],[[64166,64166],"mapped",[30410]],[[64167,64167],"mapped",[30427]],[[64168,64168],"mapped",[30452]],[[64169,64169],"mapped",[30538]],[[64170,64170],"mapped",[30528]],[[64171,64171],"mapped",[30924]],[[64172,64172],"mapped",[31409]],[[64173,64173],"mapped",[31680]],[[64174,64174],"mapped",[31867]],[[64175,64175],"mapped",[32091]],[[64176,64176],"mapped",[32244]],[[64177,64177],"mapped",[32574]],[[64178,64178],"mapped",[32773]],[[64179,64179],"mapped",[33618]],[[64180,64180],"mapped",[33775]],[[64181,64181],"mapped",[34681]],[[64182,64182],"mapped",[35137]],[[64183,64183],"mapped",[35206]],[[64184,64184],"mapped",[35222]],[[64185,64185],"mapped",[35519]],[[64186,64186],"mapped",[35576]],[[64187,64187],"mapped",[35531]],[[64188,64188],"mapped",[35585]],[[64189,64189],"mapped",[35582]],[[64190,64190],"mapped",[35565]],[[64191,64191],"mapped",[35641]],[[64192,64192],"mapped",[35722]],[[64193,64193],"mapped",[36104]],[[64194,64194],"mapped",[36664]],[[64195,64195],"mapped",[36978]],[[64196,64196],"mapped",[37273]],[[64197,64197],"mapped",[37494]],[[64198,64198],"mapped",[38524]],[[64199,64199],"mapped",[38627]],[[64200,64200],"mapped",[38742]],[[64201,64201],"mapped",[38875]],[[64202,64202],"mapped",[38911]],[[64203,64203],"mapped",[38923]],[[64204,64204],"mapped",[38971]],[[64205,64205],"mapped",[39698]],[[64206,64206],"mapped",[40860]],[[64207,64207],"mapped",[141386]],[[64208,64208],"mapped",[141380]],[[64209,64209],"mapped",[144341]],[[64210,64210],"mapped",[15261]],[[64211,64211],"mapped",[16408]],[[64212,64212],"mapped",[16441]],[[64213,64213],"mapped",[152137]],[[64214,64214],"mapped",[154832]],[[64215,64215],"mapped",[163539]],[[64216,64216],"mapped",[40771]],[[64217,64217],"mapped",[40846]],[[64218,64255],"disallowed"],[[64256,64256],"mapped",[102,102]],[[64257,64257],"mapped",[102,105]],[[64258,64258],"mapped",[102,108]],[[64259,64259],"mapped",[102,102,105]],[[64260,64260],"mapped",[102,102,108]],[[64261,64262],"mapped",[115,116]],[[64263,64274],"disallowed"],[[64275,64275],"mapped",[1396,1398]],[[64276,64276],"mapped",[1396,1381]],[[64277,64277],"mapped",[1396,1387]],[[64278,64278],"mapped",[1406,1398]],[[64279,64279],"mapped",[1396,1389]],[[64280,64284],"disallowed"],[[64285,64285],"mapped",[1497,1460]],[[64286,64286],"valid"],[[64287,64287],"mapped",[1522,1463]],[[64288,64288],"mapped",[1506]],[[64289,64289],"mapped",[1488]],[[64290,64290],"mapped",[1491]],[[64291,64291],"mapped",[1492]],[[64292,64292],"mapped",[1499]],[[64293,64293],"mapped",[1500]],[[64294,64294],"mapped",[1501]],[[64295,64295],"mapped",[1512]],[[64296,64296],"mapped",[1514]],[[64297,64297],"disallowed_STD3_mapped",[43]],[[64298,64298],"mapped",[1513,1473]],[[64299,64299],"mapped",[1513,1474]],[[64300,64300],"mapped",[1513,1468,1473]],[[64301,64301],"mapped",[1513,1468,1474]],[[64302,64302],"mapped",[1488,1463]],[[64303,64303],"mapped",[1488,1464]],[[64304,64304],"mapped",[1488,1468]],[[64305,64305],"mapped",[1489,1468]],[[64306,64306],"mapped",[1490,1468]],[[64307,64307],"mapped",[1491,1468]],[[64308,64308],"mapped",[1492,1468]],[[64309,64309],"mapped",[1493,1468]],[[64310,64310],"mapped",[1494,1468]],[[64311,64311],"disallowed"],[[64312,64312],"mapped",[1496,1468]],[[64313,64313],"mapped",[1497,1468]],[[64314,64314],"mapped",[1498,1468]],[[64315,64315],"mapped",[1499,1468]],[[64316,64316],"mapped",[1500,1468]],[[64317,64317],"disallowed"],[[64318,64318],"mapped",[1502,1468]],[[64319,64319],"disallowed"],[[64320,64320],"mapped",[1504,1468]],[[64321,64321],"mapped",[1505,1468]],[[64322,64322],"disallowed"],[[64323,64323],"mapped",[1507,1468]],[[64324,64324],"mapped",[1508,1468]],[[64325,64325],"disallowed"],[[64326,64326],"mapped",[1510,1468]],[[64327,64327],"mapped",[1511,1468]],[[64328,64328],"mapped",[1512,1468]],[[64329,64329],"mapped",[1513,1468]],[[64330,64330],"mapped",[1514,1468]],[[64331,64331],"mapped",[1493,1465]],[[64332,64332],"mapped",[1489,1471]],[[64333,64333],"mapped",[1499,1471]],[[64334,64334],"mapped",[1508,1471]],[[64335,64335],"mapped",[1488,1500]],[[64336,64337],"mapped",[1649]],[[64338,64341],"mapped",[1659]],[[64342,64345],"mapped",[1662]],[[64346,64349],"mapped",[1664]],[[64350,64353],"mapped",[1658]],[[64354,64357],"mapped",[1663]],[[64358,64361],"mapped",[1657]],[[64362,64365],"mapped",[1700]],[[64366,64369],"mapped",[1702]],[[64370,64373],"mapped",[1668]],[[64374,64377],"mapped",[1667]],[[64378,64381],"mapped",[1670]],[[64382,64385],"mapped",[1671]],[[64386,64387],"mapped",[1677]],[[64388,64389],"mapped",[1676]],[[64390,64391],"mapped",[1678]],[[64392,64393],"mapped",[1672]],[[64394,64395],"mapped",[1688]],[[64396,64397],"mapped",[1681]],[[64398,64401],"mapped",[1705]],[[64402,64405],"mapped",[1711]],[[64406,64409],"mapped",[1715]],[[64410,64413],"mapped",[1713]],[[64414,64415],"mapped",[1722]],[[64416,64419],"mapped",[1723]],[[64420,64421],"mapped",[1728]],[[64422,64425],"mapped",[1729]],[[64426,64429],"mapped",[1726]],[[64430,64431],"mapped",[1746]],[[64432,64433],"mapped",[1747]],[[64434,64449],"valid",[],"NV8"],[[64450,64466],"disallowed"],[[64467,64470],"mapped",[1709]],[[64471,64472],"mapped",[1735]],[[64473,64474],"mapped",[1734]],[[64475,64476],"mapped",[1736]],[[64477,64477],"mapped",[1735,1652]],[[64478,64479],"mapped",[1739]],[[64480,64481],"mapped",[1733]],[[64482,64483],"mapped",[1737]],[[64484,64487],"mapped",[1744]],[[64488,64489],"mapped",[1609]],[[64490,64491],"mapped",[1574,1575]],[[64492,64493],"mapped",[1574,1749]],[[64494,64495],"mapped",[1574,1608]],[[64496,64497],"mapped",[1574,1735]],[[64498,64499],"mapped",[1574,1734]],[[64500,64501],"mapped",[1574,1736]],[[64502,64504],"mapped",[1574,1744]],[[64505,64507],"mapped",[1574,1609]],[[64508,64511],"mapped",[1740]],[[64512,64512],"mapped",[1574,1580]],[[64513,64513],"mapped",[1574,1581]],[[64514,64514],"mapped",[1574,1605]],[[64515,64515],"mapped",[1574,1609]],[[64516,64516],"mapped",[1574,1610]],[[64517,64517],"mapped",[1576,1580]],[[64518,64518],"mapped",[1576,1581]],[[64519,64519],"mapped",[1576,1582]],[[64520,64520],"mapped",[1576,1605]],[[64521,64521],"mapped",[1576,1609]],[[64522,64522],"mapped",[1576,1610]],[[64523,64523],"mapped",[1578,1580]],[[64524,64524],"mapped",[1578,1581]],[[64525,64525],"mapped",[1578,1582]],[[64526,64526],"mapped",[1578,1605]],[[64527,64527],"mapped",[1578,1609]],[[64528,64528],"mapped",[1578,1610]],[[64529,64529],"mapped",[1579,1580]],[[64530,64530],"mapped",[1579,1605]],[[64531,64531],"mapped",[1579,1609]],[[64532,64532],"mapped",[1579,1610]],[[64533,64533],"mapped",[1580,1581]],[[64534,64534],"mapped",[1580,1605]],[[64535,64535],"mapped",[1581,1580]],[[64536,64536],"mapped",[1581,1605]],[[64537,64537],"mapped",[1582,1580]],[[64538,64538],"mapped",[1582,1581]],[[64539,64539],"mapped",[1582,1605]],[[64540,64540],"mapped",[1587,1580]],[[64541,64541],"mapped",[1587,1581]],[[64542,64542],"mapped",[1587,1582]],[[64543,64543],"mapped",[1587,1605]],[[64544,64544],"mapped",[1589,1581]],[[64545,64545],"mapped",[1589,1605]],[[64546,64546],"mapped",[1590,1580]],[[64547,64547],"mapped",[1590,1581]],[[64548,64548],"mapped",[1590,1582]],[[64549,64549],"mapped",[1590,1605]],[[64550,64550],"mapped",[1591,1581]],[[64551,64551],"mapped",[1591,1605]],[[64552,64552],"mapped",[1592,1605]],[[64553,64553],"mapped",[1593,1580]],[[64554,64554],"mapped",[1593,1605]],[[64555,64555],"mapped",[1594,1580]],[[64556,64556],"mapped",[1594,1605]],[[64557,64557],"mapped",[1601,1580]],[[64558,64558],"mapped",[1601,1581]],[[64559,64559],"mapped",[1601,1582]],[[64560,64560],"mapped",[1601,1605]],[[64561,64561],"mapped",[1601,1609]],[[64562,64562],"mapped",[1601,1610]],[[64563,64563],"mapped",[1602,1581]],[[64564,64564],"mapped",[1602,1605]],[[64565,64565],"mapped",[1602,1609]],[[64566,64566],"mapped",[1602,1610]],[[64567,64567],"mapped",[1603,1575]],[[64568,64568],"mapped",[1603,1580]],[[64569,64569],"mapped",[1603,1581]],[[64570,64570],"mapped",[1603,1582]],[[64571,64571],"mapped",[1603,1604]],[[64572,64572],"mapped",[1603,1605]],[[64573,64573],"mapped",[1603,1609]],[[64574,64574],"mapped",[1603,1610]],[[64575,64575],"mapped",[1604,1580]],[[64576,64576],"mapped",[1604,1581]],[[64577,64577],"mapped",[1604,1582]],[[64578,64578],"mapped",[1604,1605]],[[64579,64579],"mapped",[1604,1609]],[[64580,64580],"mapped",[1604,1610]],[[64581,64581],"mapped",[1605,1580]],[[64582,64582],"mapped",[1605,1581]],[[64583,64583],"mapped",[1605,1582]],[[64584,64584],"mapped",[1605,1605]],[[64585,64585],"mapped",[1605,1609]],[[64586,64586],"mapped",[1605,1610]],[[64587,64587],"mapped",[1606,1580]],[[64588,64588],"mapped",[1606,1581]],[[64589,64589],"mapped",[1606,1582]],[[64590,64590],"mapped",[1606,1605]],[[64591,64591],"mapped",[1606,1609]],[[64592,64592],"mapped",[1606,1610]],[[64593,64593],"mapped",[1607,1580]],[[64594,64594],"mapped",[1607,1605]],[[64595,64595],"mapped",[1607,1609]],[[64596,64596],"mapped",[1607,1610]],[[64597,64597],"mapped",[1610,1580]],[[64598,64598],"mapped",[1610,1581]],[[64599,64599],"mapped",[1610,1582]],[[64600,64600],"mapped",[1610,1605]],[[64601,64601],"mapped",[1610,1609]],[[64602,64602],"mapped",[1610,1610]],[[64603,64603],"mapped",[1584,1648]],[[64604,64604],"mapped",[1585,1648]],[[64605,64605],"mapped",[1609,1648]],[[64606,64606],"disallowed_STD3_mapped",[32,1612,1617]],[[64607,64607],"disallowed_STD3_mapped",[32,1613,1617]],[[64608,64608],"disallowed_STD3_mapped",[32,1614,1617]],[[64609,64609],"disallowed_STD3_mapped",[32,1615,1617]],[[64610,64610],"disallowed_STD3_mapped",[32,1616,1617]],[[64611,64611],"disallowed_STD3_mapped",[32,1617,1648]],[[64612,64612],"mapped",[1574,1585]],[[64613,64613],"mapped",[1574,1586]],[[64614,64614],"mapped",[1574,1605]],[[64615,64615],"mapped",[1574,1606]],[[64616,64616],"mapped",[1574,1609]],[[64617,64617],"mapped",[1574,1610]],[[64618,64618],"mapped",[1576,1585]],[[64619,64619],"mapped",[1576,1586]],[[64620,64620],"mapped",[1576,1605]],[[64621,64621],"mapped",[1576,1606]],[[64622,64622],"mapped",[1576,1609]],[[64623,64623],"mapped",[1576,1610]],[[64624,64624],"mapped",[1578,1585]],[[64625,64625],"mapped",[1578,1586]],[[64626,64626],"mapped",[1578,1605]],[[64627,64627],"mapped",[1578,1606]],[[64628,64628],"mapped",[1578,1609]],[[64629,64629],"mapped",[1578,1610]],[[64630,64630],"mapped",[1579,1585]],[[64631,64631],"mapped",[1579,1586]],[[64632,64632],"mapped",[1579,1605]],[[64633,64633],"mapped",[1579,1606]],[[64634,64634],"mapped",[1579,1609]],[[64635,64635],"mapped",[1579,1610]],[[64636,64636],"mapped",[1601,1609]],[[64637,64637],"mapped",[1601,1610]],[[64638,64638],"mapped",[1602,1609]],[[64639,64639],"mapped",[1602,1610]],[[64640,64640],"mapped",[1603,1575]],[[64641,64641],"mapped",[1603,1604]],[[64642,64642],"mapped",[1603,1605]],[[64643,64643],"mapped",[1603,1609]],[[64644,64644],"mapped",[1603,1610]],[[64645,64645],"mapped",[1604,1605]],[[64646,64646],"mapped",[1604,1609]],[[64647,64647],"mapped",[1604,1610]],[[64648,64648],"mapped",[1605,1575]],[[64649,64649],"mapped",[1605,1605]],[[64650,64650],"mapped",[1606,1585]],[[64651,64651],"mapped",[1606,1586]],[[64652,64652],"mapped",[1606,1605]],[[64653,64653],"mapped",[1606,1606]],[[64654,64654],"mapped",[1606,1609]],[[64655,64655],"mapped",[1606,1610]],[[64656,64656],"mapped",[1609,1648]],[[64657,64657],"mapped",[1610,1585]],[[64658,64658],"mapped",[1610,1586]],[[64659,64659],"mapped",[1610,1605]],[[64660,64660],"mapped",[1610,1606]],[[64661,64661],"mapped",[1610,1609]],[[64662,64662],"mapped",[1610,1610]],[[64663,64663],"mapped",[1574,1580]],[[64664,64664],"mapped",[1574,1581]],[[64665,64665],"mapped",[1574,1582]],[[64666,64666],"mapped",[1574,1605]],[[64667,64667],"mapped",[1574,1607]],[[64668,64668],"mapped",[1576,1580]],[[64669,64669],"mapped",[1576,1581]],[[64670,64670],"mapped",[1576,1582]],[[64671,64671],"mapped",[1576,1605]],[[64672,64672],"mapped",[1576,1607]],[[64673,64673],"mapped",[1578,1580]],[[64674,64674],"mapped",[1578,1581]],[[64675,64675],"mapped",[1578,1582]],[[64676,64676],"mapped",[1578,1605]],[[64677,64677],"mapped",[1578,1607]],[[64678,64678],"mapped",[1579,1605]],[[64679,64679],"mapped",[1580,1581]],[[64680,64680],"mapped",[1580,1605]],[[64681,64681],"mapped",[1581,1580]],[[64682,64682],"mapped",[1581,1605]],[[64683,64683],"mapped",[1582,1580]],[[64684,64684],"mapped",[1582,1605]],[[64685,64685],"mapped",[1587,1580]],[[64686,64686],"mapped",[1587,1581]],[[64687,64687],"mapped",[1587,1582]],[[64688,64688],"mapped",[1587,1605]],[[64689,64689],"mapped",[1589,1581]],[[64690,64690],"mapped",[1589,1582]],[[64691,64691],"mapped",[1589,1605]],[[64692,64692],"mapped",[1590,1580]],[[64693,64693],"mapped",[1590,1581]],[[64694,64694],"mapped",[1590,1582]],[[64695,64695],"mapped",[1590,1605]],[[64696,64696],"mapped",[1591,1581]],[[64697,64697],"mapped",[1592,1605]],[[64698,64698],"mapped",[1593,1580]],[[64699,64699],"mapped",[1593,1605]],[[64700,64700],"mapped",[1594,1580]],[[64701,64701],"mapped",[1594,1605]],[[64702,64702],"mapped",[1601,1580]],[[64703,64703],"mapped",[1601,1581]],[[64704,64704],"mapped",[1601,1582]],[[64705,64705],"mapped",[1601,1605]],[[64706,64706],"mapped",[1602,1581]],[[64707,64707],"mapped",[1602,1605]],[[64708,64708],"mapped",[1603,1580]],[[64709,64709],"mapped",[1603,1581]],[[64710,64710],"mapped",[1603,1582]],[[64711,64711],"mapped",[1603,1604]],[[64712,64712],"mapped",[1603,1605]],[[64713,64713],"mapped",[1604,1580]],[[64714,64714],"mapped",[1604,1581]],[[64715,64715],"mapped",[1604,1582]],[[64716,64716],"mapped",[1604,1605]],[[64717,64717],"mapped",[1604,1607]],[[64718,64718],"mapped",[1605,1580]],[[64719,64719],"mapped",[1605,1581]],[[64720,64720],"mapped",[1605,1582]],[[64721,64721],"mapped",[1605,1605]],[[64722,64722],"mapped",[1606,1580]],[[64723,64723],"mapped",[1606,1581]],[[64724,64724],"mapped",[1606,1582]],[[64725,64725],"mapped",[1606,1605]],[[64726,64726],"mapped",[1606,1607]],[[64727,64727],"mapped",[1607,1580]],[[64728,64728],"mapped",[1607,1605]],[[64729,64729],"mapped",[1607,1648]],[[64730,64730],"mapped",[1610,1580]],[[64731,64731],"mapped",[1610,1581]],[[64732,64732],"mapped",[1610,1582]],[[64733,64733],"mapped",[1610,1605]],[[64734,64734],"mapped",[1610,1607]],[[64735,64735],"mapped",[1574,1605]],[[64736,64736],"mapped",[1574,1607]],[[64737,64737],"mapped",[1576,1605]],[[64738,64738],"mapped",[1576,1607]],[[64739,64739],"mapped",[1578,1605]],[[64740,64740],"mapped",[1578,1607]],[[64741,64741],"mapped",[1579,1605]],[[64742,64742],"mapped",[1579,1607]],[[64743,64743],"mapped",[1587,1605]],[[64744,64744],"mapped",[1587,1607]],[[64745,64745],"mapped",[1588,1605]],[[64746,64746],"mapped",[1588,1607]],[[64747,64747],"mapped",[1603,1604]],[[64748,64748],"mapped",[1603,1605]],[[64749,64749],"mapped",[1604,1605]],[[64750,64750],"mapped",[1606,1605]],[[64751,64751],"mapped",[1606,1607]],[[64752,64752],"mapped",[1610,1605]],[[64753,64753],"mapped",[1610,1607]],[[64754,64754],"mapped",[1600,1614,1617]],[[64755,64755],"mapped",[1600,1615,1617]],[[64756,64756],"mapped",[1600,1616,1617]],[[64757,64757],"mapped",[1591,1609]],[[64758,64758],"mapped",[1591,1610]],[[64759,64759],"mapped",[1593,1609]],[[64760,64760],"mapped",[1593,1610]],[[64761,64761],"mapped",[1594,1609]],[[64762,64762],"mapped",[1594,1610]],[[64763,64763],"mapped",[1587,1609]],[[64764,64764],"mapped",[1587,1610]],[[64765,64765],"mapped",[1588,1609]],[[64766,64766],"mapped",[1588,1610]],[[64767,64767],"mapped",[1581,1609]],[[64768,64768],"mapped",[1581,1610]],[[64769,64769],"mapped",[1580,1609]],[[64770,64770],"mapped",[1580,1610]],[[64771,64771],"mapped",[1582,1609]],[[64772,64772],"mapped",[1582,1610]],[[64773,64773],"mapped",[1589,1609]],[[64774,64774],"mapped",[1589,1610]],[[64775,64775],"mapped",[1590,1609]],[[64776,64776],"mapped",[1590,1610]],[[64777,64777],"mapped",[1588,1580]],[[64778,64778],"mapped",[1588,1581]],[[64779,64779],"mapped",[1588,1582]],[[64780,64780],"mapped",[1588,1605]],[[64781,64781],"mapped",[1588,1585]],[[64782,64782],"mapped",[1587,1585]],[[64783,64783],"mapped",[1589,1585]],[[64784,64784],"mapped",[1590,1585]],[[64785,64785],"mapped",[1591,1609]],[[64786,64786],"mapped",[1591,1610]],[[64787,64787],"mapped",[1593,1609]],[[64788,64788],"mapped",[1593,1610]],[[64789,64789],"mapped",[1594,1609]],[[64790,64790],"mapped",[1594,1610]],[[64791,64791],"mapped",[1587,1609]],[[64792,64792],"mapped",[1587,1610]],[[64793,64793],"mapped",[1588,1609]],[[64794,64794],"mapped",[1588,1610]],[[64795,64795],"mapped",[1581,1609]],[[64796,64796],"mapped",[1581,1610]],[[64797,64797],"mapped",[1580,1609]],[[64798,64798],"mapped",[1580,1610]],[[64799,64799],"mapped",[1582,1609]],[[64800,64800],"mapped",[1582,1610]],[[64801,64801],"mapped",[1589,1609]],[[64802,64802],"mapped",[1589,1610]],[[64803,64803],"mapped",[1590,1609]],[[64804,64804],"mapped",[1590,1610]],[[64805,64805],"mapped",[1588,1580]],[[64806,64806],"mapped",[1588,1581]],[[64807,64807],"mapped",[1588,1582]],[[64808,64808],"mapped",[1588,1605]],[[64809,64809],"mapped",[1588,1585]],[[64810,64810],"mapped",[1587,1585]],[[64811,64811],"mapped",[1589,1585]],[[64812,64812],"mapped",[1590,1585]],[[64813,64813],"mapped",[1588,1580]],[[64814,64814],"mapped",[1588,1581]],[[64815,64815],"mapped",[1588,1582]],[[64816,64816],"mapped",[1588,1605]],[[64817,64817],"mapped",[1587,1607]],[[64818,64818],"mapped",[1588,1607]],[[64819,64819],"mapped",[1591,1605]],[[64820,64820],"mapped",[1587,1580]],[[64821,64821],"mapped",[1587,1581]],[[64822,64822],"mapped",[1587,1582]],[[64823,64823],"mapped",[1588,1580]],[[64824,64824],"mapped",[1588,1581]],[[64825,64825],"mapped",[1588,1582]],[[64826,64826],"mapped",[1591,1605]],[[64827,64827],"mapped",[1592,1605]],[[64828,64829],"mapped",[1575,1611]],[[64830,64831],"valid",[],"NV8"],[[64832,64847],"disallowed"],[[64848,64848],"mapped",[1578,1580,1605]],[[64849,64850],"mapped",[1578,1581,1580]],[[64851,64851],"mapped",[1578,1581,1605]],[[64852,64852],"mapped",[1578,1582,1605]],[[64853,64853],"mapped",[1578,1605,1580]],[[64854,64854],"mapped",[1578,1605,1581]],[[64855,64855],"mapped",[1578,1605,1582]],[[64856,64857],"mapped",[1580,1605,1581]],[[64858,64858],"mapped",[1581,1605,1610]],[[64859,64859],"mapped",[1581,1605,1609]],[[64860,64860],"mapped",[1587,1581,1580]],[[64861,64861],"mapped",[1587,1580,1581]],[[64862,64862],"mapped",[1587,1580,1609]],[[64863,64864],"mapped",[1587,1605,1581]],[[64865,64865],"mapped",[1587,1605,1580]],[[64866,64867],"mapped",[1587,1605,1605]],[[64868,64869],"mapped",[1589,1581,1581]],[[64870,64870],"mapped",[1589,1605,1605]],[[64871,64872],"mapped",[1588,1581,1605]],[[64873,64873],"mapped",[1588,1580,1610]],[[64874,64875],"mapped",[1588,1605,1582]],[[64876,64877],"mapped",[1588,1605,1605]],[[64878,64878],"mapped",[1590,1581,1609]],[[64879,64880],"mapped",[1590,1582,1605]],[[64881,64882],"mapped",[1591,1605,1581]],[[64883,64883],"mapped",[1591,1605,1605]],[[64884,64884],"mapped",[1591,1605,1610]],[[64885,64885],"mapped",[1593,1580,1605]],[[64886,64887],"mapped",[1593,1605,1605]],[[64888,64888],"mapped",[1593,1605,1609]],[[64889,64889],"mapped",[1594,1605,1605]],[[64890,64890],"mapped",[1594,1605,1610]],[[64891,64891],"mapped",[1594,1605,1609]],[[64892,64893],"mapped",[1601,1582,1605]],[[64894,64894],"mapped",[1602,1605,1581]],[[64895,64895],"mapped",[1602,1605,1605]],[[64896,64896],"mapped",[1604,1581,1605]],[[64897,64897],"mapped",[1604,1581,1610]],[[64898,64898],"mapped",[1604,1581,1609]],[[64899,64900],"mapped",[1604,1580,1580]],[[64901,64902],"mapped",[1604,1582,1605]],[[64903,64904],"mapped",[1604,1605,1581]],[[64905,64905],"mapped",[1605,1581,1580]],[[64906,64906],"mapped",[1605,1581,1605]],[[64907,64907],"mapped",[1605,1581,1610]],[[64908,64908],"mapped",[1605,1580,1581]],[[64909,64909],"mapped",[1605,1580,1605]],[[64910,64910],"mapped",[1605,1582,1580]],[[64911,64911],"mapped",[1605,1582,1605]],[[64912,64913],"disallowed"],[[64914,64914],"mapped",[1605,1580,1582]],[[64915,64915],"mapped",[1607,1605,1580]],[[64916,64916],"mapped",[1607,1605,1605]],[[64917,64917],"mapped",[1606,1581,1605]],[[64918,64918],"mapped",[1606,1581,1609]],[[64919,64920],"mapped",[1606,1580,1605]],[[64921,64921],"mapped",[1606,1580,1609]],[[64922,64922],"mapped",[1606,1605,1610]],[[64923,64923],"mapped",[1606,1605,1609]],[[64924,64925],"mapped",[1610,1605,1605]],[[64926,64926],"mapped",[1576,1582,1610]],[[64927,64927],"mapped",[1578,1580,1610]],[[64928,64928],"mapped",[1578,1580,1609]],[[64929,64929],"mapped",[1578,1582,1610]],[[64930,64930],"mapped",[1578,1582,1609]],[[64931,64931],"mapped",[1578,1605,1610]],[[64932,64932],"mapped",[1578,1605,1609]],[[64933,64933],"mapped",[1580,1605,1610]],[[64934,64934],"mapped",[1580,1581,1609]],[[64935,64935],"mapped",[1580,1605,1609]],[[64936,64936],"mapped",[1587,1582,1609]],[[64937,64937],"mapped",[1589,1581,1610]],[[64938,64938],"mapped",[1588,1581,1610]],[[64939,64939],"mapped",[1590,1581,1610]],[[64940,64940],"mapped",[1604,1580,1610]],[[64941,64941],"mapped",[1604,1605,1610]],[[64942,64942],"mapped",[1610,1581,1610]],[[64943,64943],"mapped",[1610,1580,1610]],[[64944,64944],"mapped",[1610,1605,1610]],[[64945,64945],"mapped",[1605,1605,1610]],[[64946,64946],"mapped",[1602,1605,1610]],[[64947,64947],"mapped",[1606,1581,1610]],[[64948,64948],"mapped",[1602,1605,1581]],[[64949,64949],"mapped",[1604,1581,1605]],[[64950,64950],"mapped",[1593,1605,1610]],[[64951,64951],"mapped",[1603,1605,1610]],[[64952,64952],"mapped",[1606,1580,1581]],[[64953,64953],"mapped",[1605,1582,1610]],[[64954,64954],"mapped",[1604,1580,1605]],[[64955,64955],"mapped",[1603,1605,1605]],[[64956,64956],"mapped",[1604,1580,1605]],[[64957,64957],"mapped",[1606,1580,1581]],[[64958,64958],"mapped",[1580,1581,1610]],[[64959,64959],"mapped",[1581,1580,1610]],[[64960,64960],"mapped",[1605,1580,1610]],[[64961,64961],"mapped",[1601,1605,1610]],[[64962,64962],"mapped",[1576,1581,1610]],[[64963,64963],"mapped",[1603,1605,1605]],[[64964,64964],"mapped",[1593,1580,1605]],[[64965,64965],"mapped",[1589,1605,1605]],[[64966,64966],"mapped",[1587,1582,1610]],[[64967,64967],"mapped",[1606,1580,1610]],[[64968,64975],"disallowed"],[[64976,65007],"disallowed"],[[65008,65008],"mapped",[1589,1604,1746]],[[65009,65009],"mapped",[1602,1604,1746]],[[65010,65010],"mapped",[1575,1604,1604,1607]],[[65011,65011],"mapped",[1575,1603,1576,1585]],[[65012,65012],"mapped",[1605,1581,1605,1583]],[[65013,65013],"mapped",[1589,1604,1593,1605]],[[65014,65014],"mapped",[1585,1587,1608,1604]],[[65015,65015],"mapped",[1593,1604,1610,1607]],[[65016,65016],"mapped",[1608,1587,1604,1605]],[[65017,65017],"mapped",[1589,1604,1609]],[[65018,65018],"disallowed_STD3_mapped",[1589,1604,1609,32,1575,1604,1604,1607,32,1593,1604,1610,1607,32,1608,1587,1604,1605]],[[65019,65019],"disallowed_STD3_mapped",[1580,1604,32,1580,1604,1575,1604,1607]],[[65020,65020],"mapped",[1585,1740,1575,1604]],[[65021,65021],"valid",[],"NV8"],[[65022,65023],"disallowed"],[[65024,65039],"ignored"],[[65040,65040],"disallowed_STD3_mapped",[44]],[[65041,65041],"mapped",[12289]],[[65042,65042],"disallowed"],[[65043,65043],"disallowed_STD3_mapped",[58]],[[65044,65044],"disallowed_STD3_mapped",[59]],[[65045,65045],"disallowed_STD3_mapped",[33]],[[65046,65046],"disallowed_STD3_mapped",[63]],[[65047,65047],"mapped",[12310]],[[65048,65048],"mapped",[12311]],[[65049,65049],"disallowed"],[[65050,65055],"disallowed"],[[65056,65059],"valid"],[[65060,65062],"valid"],[[65063,65069],"valid"],[[65070,65071],"valid"],[[65072,65072],"disallowed"],[[65073,65073],"mapped",[8212]],[[65074,65074],"mapped",[8211]],[[65075,65076],"disallowed_STD3_mapped",[95]],[[65077,65077],"disallowed_STD3_mapped",[40]],[[65078,65078],"disallowed_STD3_mapped",[41]],[[65079,65079],"disallowed_STD3_mapped",[123]],[[65080,65080],"disallowed_STD3_mapped",[125]],[[65081,65081],"mapped",[12308]],[[65082,65082],"mapped",[12309]],[[65083,65083],"mapped",[12304]],[[65084,65084],"mapped",[12305]],[[65085,65085],"mapped",[12298]],[[65086,65086],"mapped",[12299]],[[65087,65087],"mapped",[12296]],[[65088,65088],"mapped",[12297]],[[65089,65089],"mapped",[12300]],[[65090,65090],"mapped",[12301]],[[65091,65091],"mapped",[12302]],[[65092,65092],"mapped",[12303]],[[65093,65094],"valid",[],"NV8"],[[65095,65095],"disallowed_STD3_mapped",[91]],[[65096,65096],"disallowed_STD3_mapped",[93]],[[65097,65100],"disallowed_STD3_mapped",[32,773]],[[65101,65103],"disallowed_STD3_mapped",[95]],[[65104,65104],"disallowed_STD3_mapped",[44]],[[65105,65105],"mapped",[12289]],[[65106,65106],"disallowed"],[[65107,65107],"disallowed"],[[65108,65108],"disallowed_STD3_mapped",[59]],[[65109,65109],"disallowed_STD3_mapped",[58]],[[65110,65110],"disallowed_STD3_mapped",[63]],[[65111,65111],"disallowed_STD3_mapped",[33]],[[65112,65112],"mapped",[8212]],[[65113,65113],"disallowed_STD3_mapped",[40]],[[65114,65114],"disallowed_STD3_mapped",[41]],[[65115,65115],"disallowed_STD3_mapped",[123]],[[65116,65116],"disallowed_STD3_mapped",[125]],[[65117,65117],"mapped",[12308]],[[65118,65118],"mapped",[12309]],[[65119,65119],"disallowed_STD3_mapped",[35]],[[65120,65120],"disallowed_STD3_mapped",[38]],[[65121,65121],"disallowed_STD3_mapped",[42]],[[65122,65122],"disallowed_STD3_mapped",[43]],[[65123,65123],"mapped",[45]],[[65124,65124],"disallowed_STD3_mapped",[60]],[[65125,65125],"disallowed_STD3_mapped",[62]],[[65126,65126],"disallowed_STD3_mapped",[61]],[[65127,65127],"disallowed"],[[65128,65128],"disallowed_STD3_mapped",[92]],[[65129,65129],"disallowed_STD3_mapped",[36]],[[65130,65130],"disallowed_STD3_mapped",[37]],[[65131,65131],"disallowed_STD3_mapped",[64]],[[65132,65135],"disallowed"],[[65136,65136],"disallowed_STD3_mapped",[32,1611]],[[65137,65137],"mapped",[1600,1611]],[[65138,65138],"disallowed_STD3_mapped",[32,1612]],[[65139,65139],"valid"],[[65140,65140],"disallowed_STD3_mapped",[32,1613]],[[65141,65141],"disallowed"],[[65142,65142],"disallowed_STD3_mapped",[32,1614]],[[65143,65143],"mapped",[1600,1614]],[[65144,65144],"disallowed_STD3_mapped",[32,1615]],[[65145,65145],"mapped",[1600,1615]],[[65146,65146],"disallowed_STD3_mapped",[32,1616]],[[65147,65147],"mapped",[1600,1616]],[[65148,65148],"disallowed_STD3_mapped",[32,1617]],[[65149,65149],"mapped",[1600,1617]],[[65150,65150],"disallowed_STD3_mapped",[32,1618]],[[65151,65151],"mapped",[1600,1618]],[[65152,65152],"mapped",[1569]],[[65153,65154],"mapped",[1570]],[[65155,65156],"mapped",[1571]],[[65157,65158],"mapped",[1572]],[[65159,65160],"mapped",[1573]],[[65161,65164],"mapped",[1574]],[[65165,65166],"mapped",[1575]],[[65167,65170],"mapped",[1576]],[[65171,65172],"mapped",[1577]],[[65173,65176],"mapped",[1578]],[[65177,65180],"mapped",[1579]],[[65181,65184],"mapped",[1580]],[[65185,65188],"mapped",[1581]],[[65189,65192],"mapped",[1582]],[[65193,65194],"mapped",[1583]],[[65195,65196],"mapped",[1584]],[[65197,65198],"mapped",[1585]],[[65199,65200],"mapped",[1586]],[[65201,65204],"mapped",[1587]],[[65205,65208],"mapped",[1588]],[[65209,65212],"mapped",[1589]],[[65213,65216],"mapped",[1590]],[[65217,65220],"mapped",[1591]],[[65221,65224],"mapped",[1592]],[[65225,65228],"mapped",[1593]],[[65229,65232],"mapped",[1594]],[[65233,65236],"mapped",[1601]],[[65237,65240],"mapped",[1602]],[[65241,65244],"mapped",[1603]],[[65245,65248],"mapped",[1604]],[[65249,65252],"mapped",[1605]],[[65253,65256],"mapped",[1606]],[[65257,65260],"mapped",[1607]],[[65261,65262],"mapped",[1608]],[[65263,65264],"mapped",[1609]],[[65265,65268],"mapped",[1610]],[[65269,65270],"mapped",[1604,1570]],[[65271,65272],"mapped",[1604,1571]],[[65273,65274],"mapped",[1604,1573]],[[65275,65276],"mapped",[1604,1575]],[[65277,65278],"disallowed"],[[65279,65279],"ignored"],[[65280,65280],"disallowed"],[[65281,65281],"disallowed_STD3_mapped",[33]],[[65282,65282],"disallowed_STD3_mapped",[34]],[[65283,65283],"disallowed_STD3_mapped",[35]],[[65284,65284],"disallowed_STD3_mapped",[36]],[[65285,65285],"disallowed_STD3_mapped",[37]],[[65286,65286],"disallowed_STD3_mapped",[38]],[[65287,65287],"disallowed_STD3_mapped",[39]],[[65288,65288],"disallowed_STD3_mapped",[40]],[[65289,65289],"disallowed_STD3_mapped",[41]],[[65290,65290],"disallowed_STD3_mapped",[42]],[[65291,65291],"disallowed_STD3_mapped",[43]],[[65292,65292],"disallowed_STD3_mapped",[44]],[[65293,65293],"mapped",[45]],[[65294,65294],"mapped",[46]],[[65295,65295],"disallowed_STD3_mapped",[47]],[[65296,65296],"mapped",[48]],[[65297,65297],"mapped",[49]],[[65298,65298],"mapped",[50]],[[65299,65299],"mapped",[51]],[[65300,65300],"mapped",[52]],[[65301,65301],"mapped",[53]],[[65302,65302],"mapped",[54]],[[65303,65303],"mapped",[55]],[[65304,65304],"mapped",[56]],[[65305,65305],"mapped",[57]],[[65306,65306],"disallowed_STD3_mapped",[58]],[[65307,65307],"disallowed_STD3_mapped",[59]],[[65308,65308],"disallowed_STD3_mapped",[60]],[[65309,65309],"disallowed_STD3_mapped",[61]],[[65310,65310],"disallowed_STD3_mapped",[62]],[[65311,65311],"disallowed_STD3_mapped",[63]],[[65312,65312],"disallowed_STD3_mapped",[64]],[[65313,65313],"mapped",[97]],[[65314,65314],"mapped",[98]],[[65315,65315],"mapped",[99]],[[65316,65316],"mapped",[100]],[[65317,65317],"mapped",[101]],[[65318,65318],"mapped",[102]],[[65319,65319],"mapped",[103]],[[65320,65320],"mapped",[104]],[[65321,65321],"mapped",[105]],[[65322,65322],"mapped",[106]],[[65323,65323],"mapped",[107]],[[65324,65324],"mapped",[108]],[[65325,65325],"mapped",[109]],[[65326,65326],"mapped",[110]],[[65327,65327],"mapped",[111]],[[65328,65328],"mapped",[112]],[[65329,65329],"mapped",[113]],[[65330,65330],"mapped",[114]],[[65331,65331],"mapped",[115]],[[65332,65332],"mapped",[116]],[[65333,65333],"mapped",[117]],[[65334,65334],"mapped",[118]],[[65335,65335],"mapped",[119]],[[65336,65336],"mapped",[120]],[[65337,65337],"mapped",[121]],[[65338,65338],"mapped",[122]],[[65339,65339],"disallowed_STD3_mapped",[91]],[[65340,65340],"disallowed_STD3_mapped",[92]],[[65341,65341],"disallowed_STD3_mapped",[93]],[[65342,65342],"disallowed_STD3_mapped",[94]],[[65343,65343],"disallowed_STD3_mapped",[95]],[[65344,65344],"disallowed_STD3_mapped",[96]],[[65345,65345],"mapped",[97]],[[65346,65346],"mapped",[98]],[[65347,65347],"mapped",[99]],[[65348,65348],"mapped",[100]],[[65349,65349],"mapped",[101]],[[65350,65350],"mapped",[102]],[[65351,65351],"mapped",[103]],[[65352,65352],"mapped",[104]],[[65353,65353],"mapped",[105]],[[65354,65354],"mapped",[106]],[[65355,65355],"mapped",[107]],[[65356,65356],"mapped",[108]],[[65357,65357],"mapped",[109]],[[65358,65358],"mapped",[110]],[[65359,65359],"mapped",[111]],[[65360,65360],"mapped",[112]],[[65361,65361],"mapped",[113]],[[65362,65362],"mapped",[114]],[[65363,65363],"mapped",[115]],[[65364,65364],"mapped",[116]],[[65365,65365],"mapped",[117]],[[65366,65366],"mapped",[118]],[[65367,65367],"mapped",[119]],[[65368,65368],"mapped",[120]],[[65369,65369],"mapped",[121]],[[65370,65370],"mapped",[122]],[[65371,65371],"disallowed_STD3_mapped",[123]],[[65372,65372],"disallowed_STD3_mapped",[124]],[[65373,65373],"disallowed_STD3_mapped",[125]],[[65374,65374],"disallowed_STD3_mapped",[126]],[[65375,65375],"mapped",[10629]],[[65376,65376],"mapped",[10630]],[[65377,65377],"mapped",[46]],[[65378,65378],"mapped",[12300]],[[65379,65379],"mapped",[12301]],[[65380,65380],"mapped",[12289]],[[65381,65381],"mapped",[12539]],[[65382,65382],"mapped",[12530]],[[65383,65383],"mapped",[12449]],[[65384,65384],"mapped",[12451]],[[65385,65385],"mapped",[12453]],[[65386,65386],"mapped",[12455]],[[65387,65387],"mapped",[12457]],[[65388,65388],"mapped",[12515]],[[65389,65389],"mapped",[12517]],[[65390,65390],"mapped",[12519]],[[65391,65391],"mapped",[12483]],[[65392,65392],"mapped",[12540]],[[65393,65393],"mapped",[12450]],[[65394,65394],"mapped",[12452]],[[65395,65395],"mapped",[12454]],[[65396,65396],"mapped",[12456]],[[65397,65397],"mapped",[12458]],[[65398,65398],"mapped",[12459]],[[65399,65399],"mapped",[12461]],[[65400,65400],"mapped",[12463]],[[65401,65401],"mapped",[12465]],[[65402,65402],"mapped",[12467]],[[65403,65403],"mapped",[12469]],[[65404,65404],"mapped",[12471]],[[65405,65405],"mapped",[12473]],[[65406,65406],"mapped",[12475]],[[65407,65407],"mapped",[12477]],[[65408,65408],"mapped",[12479]],[[65409,65409],"mapped",[12481]],[[65410,65410],"mapped",[12484]],[[65411,65411],"mapped",[12486]],[[65412,65412],"mapped",[12488]],[[65413,65413],"mapped",[12490]],[[65414,65414],"mapped",[12491]],[[65415,65415],"mapped",[12492]],[[65416,65416],"mapped",[12493]],[[65417,65417],"mapped",[12494]],[[65418,65418],"mapped",[12495]],[[65419,65419],"mapped",[12498]],[[65420,65420],"mapped",[12501]],[[65421,65421],"mapped",[12504]],[[65422,65422],"mapped",[12507]],[[65423,65423],"mapped",[12510]],[[65424,65424],"mapped",[12511]],[[65425,65425],"mapped",[12512]],[[65426,65426],"mapped",[12513]],[[65427,65427],"mapped",[12514]],[[65428,65428],"mapped",[12516]],[[65429,65429],"mapped",[12518]],[[65430,65430],"mapped",[12520]],[[65431,65431],"mapped",[12521]],[[65432,65432],"mapped",[12522]],[[65433,65433],"mapped",[12523]],[[65434,65434],"mapped",[12524]],[[65435,65435],"mapped",[12525]],[[65436,65436],"mapped",[12527]],[[65437,65437],"mapped",[12531]],[[65438,65438],"mapped",[12441]],[[65439,65439],"mapped",[12442]],[[65440,65440],"disallowed"],[[65441,65441],"mapped",[4352]],[[65442,65442],"mapped",[4353]],[[65443,65443],"mapped",[4522]],[[65444,65444],"mapped",[4354]],[[65445,65445],"mapped",[4524]],[[65446,65446],"mapped",[4525]],[[65447,65447],"mapped",[4355]],[[65448,65448],"mapped",[4356]],[[65449,65449],"mapped",[4357]],[[65450,65450],"mapped",[4528]],[[65451,65451],"mapped",[4529]],[[65452,65452],"mapped",[4530]],[[65453,65453],"mapped",[4531]],[[65454,65454],"mapped",[4532]],[[65455,65455],"mapped",[4533]],[[65456,65456],"mapped",[4378]],[[65457,65457],"mapped",[4358]],[[65458,65458],"mapped",[4359]],[[65459,65459],"mapped",[4360]],[[65460,65460],"mapped",[4385]],[[65461,65461],"mapped",[4361]],[[65462,65462],"mapped",[4362]],[[65463,65463],"mapped",[4363]],[[65464,65464],"mapped",[4364]],[[65465,65465],"mapped",[4365]],[[65466,65466],"mapped",[4366]],[[65467,65467],"mapped",[4367]],[[65468,65468],"mapped",[4368]],[[65469,65469],"mapped",[4369]],[[65470,65470],"mapped",[4370]],[[65471,65473],"disallowed"],[[65474,65474],"mapped",[4449]],[[65475,65475],"mapped",[4450]],[[65476,65476],"mapped",[4451]],[[65477,65477],"mapped",[4452]],[[65478,65478],"mapped",[4453]],[[65479,65479],"mapped",[4454]],[[65480,65481],"disallowed"],[[65482,65482],"mapped",[4455]],[[65483,65483],"mapped",[4456]],[[65484,65484],"mapped",[4457]],[[65485,65485],"mapped",[4458]],[[65486,65486],"mapped",[4459]],[[65487,65487],"mapped",[4460]],[[65488,65489],"disallowed"],[[65490,65490],"mapped",[4461]],[[65491,65491],"mapped",[4462]],[[65492,65492],"mapped",[4463]],[[65493,65493],"mapped",[4464]],[[65494,65494],"mapped",[4465]],[[65495,65495],"mapped",[4466]],[[65496,65497],"disallowed"],[[65498,65498],"mapped",[4467]],[[65499,65499],"mapped",[4468]],[[65500,65500],"mapped",[4469]],[[65501,65503],"disallowed"],[[65504,65504],"mapped",[162]],[[65505,65505],"mapped",[163]],[[65506,65506],"mapped",[172]],[[65507,65507],"disallowed_STD3_mapped",[32,772]],[[65508,65508],"mapped",[166]],[[65509,65509],"mapped",[165]],[[65510,65510],"mapped",[8361]],[[65511,65511],"disallowed"],[[65512,65512],"mapped",[9474]],[[65513,65513],"mapped",[8592]],[[65514,65514],"mapped",[8593]],[[65515,65515],"mapped",[8594]],[[65516,65516],"mapped",[8595]],[[65517,65517],"mapped",[9632]],[[65518,65518],"mapped",[9675]],[[65519,65528],"disallowed"],[[65529,65531],"disallowed"],[[65532,65532],"disallowed"],[[65533,65533],"disallowed"],[[65534,65535],"disallowed"],[[65536,65547],"valid"],[[65548,65548],"disallowed"],[[65549,65574],"valid"],[[65575,65575],"disallowed"],[[65576,65594],"valid"],[[65595,65595],"disallowed"],[[65596,65597],"valid"],[[65598,65598],"disallowed"],[[65599,65613],"valid"],[[65614,65615],"disallowed"],[[65616,65629],"valid"],[[65630,65663],"disallowed"],[[65664,65786],"valid"],[[65787,65791],"disallowed"],[[65792,65794],"valid",[],"NV8"],[[65795,65798],"disallowed"],[[65799,65843],"valid",[],"NV8"],[[65844,65846],"disallowed"],[[65847,65855],"valid",[],"NV8"],[[65856,65930],"valid",[],"NV8"],[[65931,65932],"valid",[],"NV8"],[[65933,65935],"disallowed"],[[65936,65947],"valid",[],"NV8"],[[65948,65951],"disallowed"],[[65952,65952],"valid",[],"NV8"],[[65953,65999],"disallowed"],[[66000,66044],"valid",[],"NV8"],[[66045,66045],"valid"],[[66046,66175],"disallowed"],[[66176,66204],"valid"],[[66205,66207],"disallowed"],[[66208,66256],"valid"],[[66257,66271],"disallowed"],[[66272,66272],"valid"],[[66273,66299],"valid",[],"NV8"],[[66300,66303],"disallowed"],[[66304,66334],"valid"],[[66335,66335],"valid"],[[66336,66339],"valid",[],"NV8"],[[66340,66351],"disallowed"],[[66352,66368],"valid"],[[66369,66369],"valid",[],"NV8"],[[66370,66377],"valid"],[[66378,66378],"valid",[],"NV8"],[[66379,66383],"disallowed"],[[66384,66426],"valid"],[[66427,66431],"disallowed"],[[66432,66461],"valid"],[[66462,66462],"disallowed"],[[66463,66463],"valid",[],"NV8"],[[66464,66499],"valid"],[[66500,66503],"disallowed"],[[66504,66511],"valid"],[[66512,66517],"valid",[],"NV8"],[[66518,66559],"disallowed"],[[66560,66560],"mapped",[66600]],[[66561,66561],"mapped",[66601]],[[66562,66562],"mapped",[66602]],[[66563,66563],"mapped",[66603]],[[66564,66564],"mapped",[66604]],[[66565,66565],"mapped",[66605]],[[66566,66566],"mapped",[66606]],[[66567,66567],"mapped",[66607]],[[66568,66568],"mapped",[66608]],[[66569,66569],"mapped",[66609]],[[66570,66570],"mapped",[66610]],[[66571,66571],"mapped",[66611]],[[66572,66572],"mapped",[66612]],[[66573,66573],"mapped",[66613]],[[66574,66574],"mapped",[66614]],[[66575,66575],"mapped",[66615]],[[66576,66576],"mapped",[66616]],[[66577,66577],"mapped",[66617]],[[66578,66578],"mapped",[66618]],[[66579,66579],"mapped",[66619]],[[66580,66580],"mapped",[66620]],[[66581,66581],"mapped",[66621]],[[66582,66582],"mapped",[66622]],[[66583,66583],"mapped",[66623]],[[66584,66584],"mapped",[66624]],[[66585,66585],"mapped",[66625]],[[66586,66586],"mapped",[66626]],[[66587,66587],"mapped",[66627]],[[66588,66588],"mapped",[66628]],[[66589,66589],"mapped",[66629]],[[66590,66590],"mapped",[66630]],[[66591,66591],"mapped",[66631]],[[66592,66592],"mapped",[66632]],[[66593,66593],"mapped",[66633]],[[66594,66594],"mapped",[66634]],[[66595,66595],"mapped",[66635]],[[66596,66596],"mapped",[66636]],[[66597,66597],"mapped",[66637]],[[66598,66598],"mapped",[66638]],[[66599,66599],"mapped",[66639]],[[66600,66637],"valid"],[[66638,66717],"valid"],[[66718,66719],"disallowed"],[[66720,66729],"valid"],[[66730,66815],"disallowed"],[[66816,66855],"valid"],[[66856,66863],"disallowed"],[[66864,66915],"valid"],[[66916,66926],"disallowed"],[[66927,66927],"valid",[],"NV8"],[[66928,67071],"disallowed"],[[67072,67382],"valid"],[[67383,67391],"disallowed"],[[67392,67413],"valid"],[[67414,67423],"disallowed"],[[67424,67431],"valid"],[[67432,67583],"disallowed"],[[67584,67589],"valid"],[[67590,67591],"disallowed"],[[67592,67592],"valid"],[[67593,67593],"disallowed"],[[67594,67637],"valid"],[[67638,67638],"disallowed"],[[67639,67640],"valid"],[[67641,67643],"disallowed"],[[67644,67644],"valid"],[[67645,67646],"disallowed"],[[67647,67647],"valid"],[[67648,67669],"valid"],[[67670,67670],"disallowed"],[[67671,67679],"valid",[],"NV8"],[[67680,67702],"valid"],[[67703,67711],"valid",[],"NV8"],[[67712,67742],"valid"],[[67743,67750],"disallowed"],[[67751,67759],"valid",[],"NV8"],[[67760,67807],"disallowed"],[[67808,67826],"valid"],[[67827,67827],"disallowed"],[[67828,67829],"valid"],[[67830,67834],"disallowed"],[[67835,67839],"valid",[],"NV8"],[[67840,67861],"valid"],[[67862,67865],"valid",[],"NV8"],[[67866,67867],"valid",[],"NV8"],[[67868,67870],"disallowed"],[[67871,67871],"valid",[],"NV8"],[[67872,67897],"valid"],[[67898,67902],"disallowed"],[[67903,67903],"valid",[],"NV8"],[[67904,67967],"disallowed"],[[67968,68023],"valid"],[[68024,68027],"disallowed"],[[68028,68029],"valid",[],"NV8"],[[68030,68031],"valid"],[[68032,68047],"valid",[],"NV8"],[[68048,68049],"disallowed"],[[68050,68095],"valid",[],"NV8"],[[68096,68099],"valid"],[[68100,68100],"disallowed"],[[68101,68102],"valid"],[[68103,68107],"disallowed"],[[68108,68115],"valid"],[[68116,68116],"disallowed"],[[68117,68119],"valid"],[[68120,68120],"disallowed"],[[68121,68147],"valid"],[[68148,68151],"disallowed"],[[68152,68154],"valid"],[[68155,68158],"disallowed"],[[68159,68159],"valid"],[[68160,68167],"valid",[],"NV8"],[[68168,68175],"disallowed"],[[68176,68184],"valid",[],"NV8"],[[68185,68191],"disallowed"],[[68192,68220],"valid"],[[68221,68223],"valid",[],"NV8"],[[68224,68252],"valid"],[[68253,68255],"valid",[],"NV8"],[[68256,68287],"disallowed"],[[68288,68295],"valid"],[[68296,68296],"valid",[],"NV8"],[[68297,68326],"valid"],[[68327,68330],"disallowed"],[[68331,68342],"valid",[],"NV8"],[[68343,68351],"disallowed"],[[68352,68405],"valid"],[[68406,68408],"disallowed"],[[68409,68415],"valid",[],"NV8"],[[68416,68437],"valid"],[[68438,68439],"disallowed"],[[68440,68447],"valid",[],"NV8"],[[68448,68466],"valid"],[[68467,68471],"disallowed"],[[68472,68479],"valid",[],"NV8"],[[68480,68497],"valid"],[[68498,68504],"disallowed"],[[68505,68508],"valid",[],"NV8"],[[68509,68520],"disallowed"],[[68521,68527],"valid",[],"NV8"],[[68528,68607],"disallowed"],[[68608,68680],"valid"],[[68681,68735],"disallowed"],[[68736,68736],"mapped",[68800]],[[68737,68737],"mapped",[68801]],[[68738,68738],"mapped",[68802]],[[68739,68739],"mapped",[68803]],[[68740,68740],"mapped",[68804]],[[68741,68741],"mapped",[68805]],[[68742,68742],"mapped",[68806]],[[68743,68743],"mapped",[68807]],[[68744,68744],"mapped",[68808]],[[68745,68745],"mapped",[68809]],[[68746,68746],"mapped",[68810]],[[68747,68747],"mapped",[68811]],[[68748,68748],"mapped",[68812]],[[68749,68749],"mapped",[68813]],[[68750,68750],"mapped",[68814]],[[68751,68751],"mapped",[68815]],[[68752,68752],"mapped",[68816]],[[68753,68753],"mapped",[68817]],[[68754,68754],"mapped",[68818]],[[68755,68755],"mapped",[68819]],[[68756,68756],"mapped",[68820]],[[68757,68757],"mapped",[68821]],[[68758,68758],"mapped",[68822]],[[68759,68759],"mapped",[68823]],[[68760,68760],"mapped",[68824]],[[68761,68761],"mapped",[68825]],[[68762,68762],"mapped",[68826]],[[68763,68763],"mapped",[68827]],[[68764,68764],"mapped",[68828]],[[68765,68765],"mapped",[68829]],[[68766,68766],"mapped",[68830]],[[68767,68767],"mapped",[68831]],[[68768,68768],"mapped",[68832]],[[68769,68769],"mapped",[68833]],[[68770,68770],"mapped",[68834]],[[68771,68771],"mapped",[68835]],[[68772,68772],"mapped",[68836]],[[68773,68773],"mapped",[68837]],[[68774,68774],"mapped",[68838]],[[68775,68775],"mapped",[68839]],[[68776,68776],"mapped",[68840]],[[68777,68777],"mapped",[68841]],[[68778,68778],"mapped",[68842]],[[68779,68779],"mapped",[68843]],[[68780,68780],"mapped",[68844]],[[68781,68781],"mapped",[68845]],[[68782,68782],"mapped",[68846]],[[68783,68783],"mapped",[68847]],[[68784,68784],"mapped",[68848]],[[68785,68785],"mapped",[68849]],[[68786,68786],"mapped",[68850]],[[68787,68799],"disallowed"],[[68800,68850],"valid"],[[68851,68857],"disallowed"],[[68858,68863],"valid",[],"NV8"],[[68864,69215],"disallowed"],[[69216,69246],"valid",[],"NV8"],[[69247,69631],"disallowed"],[[69632,69702],"valid"],[[69703,69709],"valid",[],"NV8"],[[69710,69713],"disallowed"],[[69714,69733],"valid",[],"NV8"],[[69734,69743],"valid"],[[69744,69758],"disallowed"],[[69759,69759],"valid"],[[69760,69818],"valid"],[[69819,69820],"valid",[],"NV8"],[[69821,69821],"disallowed"],[[69822,69825],"valid",[],"NV8"],[[69826,69839],"disallowed"],[[69840,69864],"valid"],[[69865,69871],"disallowed"],[[69872,69881],"valid"],[[69882,69887],"disallowed"],[[69888,69940],"valid"],[[69941,69941],"disallowed"],[[69942,69951],"valid"],[[69952,69955],"valid",[],"NV8"],[[69956,69967],"disallowed"],[[69968,70003],"valid"],[[70004,70005],"valid",[],"NV8"],[[70006,70006],"valid"],[[70007,70015],"disallowed"],[[70016,70084],"valid"],[[70085,70088],"valid",[],"NV8"],[[70089,70089],"valid",[],"NV8"],[[70090,70092],"valid"],[[70093,70093],"valid",[],"NV8"],[[70094,70095],"disallowed"],[[70096,70105],"valid"],[[70106,70106],"valid"],[[70107,70107],"valid",[],"NV8"],[[70108,70108],"valid"],[[70109,70111],"valid",[],"NV8"],[[70112,70112],"disallowed"],[[70113,70132],"valid",[],"NV8"],[[70133,70143],"disallowed"],[[70144,70161],"valid"],[[70162,70162],"disallowed"],[[70163,70199],"valid"],[[70200,70205],"valid",[],"NV8"],[[70206,70271],"disallowed"],[[70272,70278],"valid"],[[70279,70279],"disallowed"],[[70280,70280],"valid"],[[70281,70281],"disallowed"],[[70282,70285],"valid"],[[70286,70286],"disallowed"],[[70287,70301],"valid"],[[70302,70302],"disallowed"],[[70303,70312],"valid"],[[70313,70313],"valid",[],"NV8"],[[70314,70319],"disallowed"],[[70320,70378],"valid"],[[70379,70383],"disallowed"],[[70384,70393],"valid"],[[70394,70399],"disallowed"],[[70400,70400],"valid"],[[70401,70403],"valid"],[[70404,70404],"disallowed"],[[70405,70412],"valid"],[[70413,70414],"disallowed"],[[70415,70416],"valid"],[[70417,70418],"disallowed"],[[70419,70440],"valid"],[[70441,70441],"disallowed"],[[70442,70448],"valid"],[[70449,70449],"disallowed"],[[70450,70451],"valid"],[[70452,70452],"disallowed"],[[70453,70457],"valid"],[[70458,70459],"disallowed"],[[70460,70468],"valid"],[[70469,70470],"disallowed"],[[70471,70472],"valid"],[[70473,70474],"disallowed"],[[70475,70477],"valid"],[[70478,70479],"disallowed"],[[70480,70480],"valid"],[[70481,70486],"disallowed"],[[70487,70487],"valid"],[[70488,70492],"disallowed"],[[70493,70499],"valid"],[[70500,70501],"disallowed"],[[70502,70508],"valid"],[[70509,70511],"disallowed"],[[70512,70516],"valid"],[[70517,70783],"disallowed"],[[70784,70853],"valid"],[[70854,70854],"valid",[],"NV8"],[[70855,70855],"valid"],[[70856,70863],"disallowed"],[[70864,70873],"valid"],[[70874,71039],"disallowed"],[[71040,71093],"valid"],[[71094,71095],"disallowed"],[[71096,71104],"valid"],[[71105,71113],"valid",[],"NV8"],[[71114,71127],"valid",[],"NV8"],[[71128,71133],"valid"],[[71134,71167],"disallowed"],[[71168,71232],"valid"],[[71233,71235],"valid",[],"NV8"],[[71236,71236],"valid"],[[71237,71247],"disallowed"],[[71248,71257],"valid"],[[71258,71295],"disallowed"],[[71296,71351],"valid"],[[71352,71359],"disallowed"],[[71360,71369],"valid"],[[71370,71423],"disallowed"],[[71424,71449],"valid"],[[71450,71452],"disallowed"],[[71453,71467],"valid"],[[71468,71471],"disallowed"],[[71472,71481],"valid"],[[71482,71487],"valid",[],"NV8"],[[71488,71839],"disallowed"],[[71840,71840],"mapped",[71872]],[[71841,71841],"mapped",[71873]],[[71842,71842],"mapped",[71874]],[[71843,71843],"mapped",[71875]],[[71844,71844],"mapped",[71876]],[[71845,71845],"mapped",[71877]],[[71846,71846],"mapped",[71878]],[[71847,71847],"mapped",[71879]],[[71848,71848],"mapped",[71880]],[[71849,71849],"mapped",[71881]],[[71850,71850],"mapped",[71882]],[[71851,71851],"mapped",[71883]],[[71852,71852],"mapped",[71884]],[[71853,71853],"mapped",[71885]],[[71854,71854],"mapped",[71886]],[[71855,71855],"mapped",[71887]],[[71856,71856],"mapped",[71888]],[[71857,71857],"mapped",[71889]],[[71858,71858],"mapped",[71890]],[[71859,71859],"mapped",[71891]],[[71860,71860],"mapped",[71892]],[[71861,71861],"mapped",[71893]],[[71862,71862],"mapped",[71894]],[[71863,71863],"mapped",[71895]],[[71864,71864],"mapped",[71896]],[[71865,71865],"mapped",[71897]],[[71866,71866],"mapped",[71898]],[[71867,71867],"mapped",[71899]],[[71868,71868],"mapped",[71900]],[[71869,71869],"mapped",[71901]],[[71870,71870],"mapped",[71902]],[[71871,71871],"mapped",[71903]],[[71872,71913],"valid"],[[71914,71922],"valid",[],"NV8"],[[71923,71934],"disallowed"],[[71935,71935],"valid"],[[71936,72383],"disallowed"],[[72384,72440],"valid"],[[72441,73727],"disallowed"],[[73728,74606],"valid"],[[74607,74648],"valid"],[[74649,74649],"valid"],[[74650,74751],"disallowed"],[[74752,74850],"valid",[],"NV8"],[[74851,74862],"valid",[],"NV8"],[[74863,74863],"disallowed"],[[74864,74867],"valid",[],"NV8"],[[74868,74868],"valid",[],"NV8"],[[74869,74879],"disallowed"],[[74880,75075],"valid"],[[75076,77823],"disallowed"],[[77824,78894],"valid"],[[78895,82943],"disallowed"],[[82944,83526],"valid"],[[83527,92159],"disallowed"],[[92160,92728],"valid"],[[92729,92735],"disallowed"],[[92736,92766],"valid"],[[92767,92767],"disallowed"],[[92768,92777],"valid"],[[92778,92781],"disallowed"],[[92782,92783],"valid",[],"NV8"],[[92784,92879],"disallowed"],[[92880,92909],"valid"],[[92910,92911],"disallowed"],[[92912,92916],"valid"],[[92917,92917],"valid",[],"NV8"],[[92918,92927],"disallowed"],[[92928,92982],"valid"],[[92983,92991],"valid",[],"NV8"],[[92992,92995],"valid"],[[92996,92997],"valid",[],"NV8"],[[92998,93007],"disallowed"],[[93008,93017],"valid"],[[93018,93018],"disallowed"],[[93019,93025],"valid",[],"NV8"],[[93026,93026],"disallowed"],[[93027,93047],"valid"],[[93048,93052],"disallowed"],[[93053,93071],"valid"],[[93072,93951],"disallowed"],[[93952,94020],"valid"],[[94021,94031],"disallowed"],[[94032,94078],"valid"],[[94079,94094],"disallowed"],[[94095,94111],"valid"],[[94112,110591],"disallowed"],[[110592,110593],"valid"],[[110594,113663],"disallowed"],[[113664,113770],"valid"],[[113771,113775],"disallowed"],[[113776,113788],"valid"],[[113789,113791],"disallowed"],[[113792,113800],"valid"],[[113801,113807],"disallowed"],[[113808,113817],"valid"],[[113818,113819],"disallowed"],[[113820,113820],"valid",[],"NV8"],[[113821,113822],"valid"],[[113823,113823],"valid",[],"NV8"],[[113824,113827],"ignored"],[[113828,118783],"disallowed"],[[118784,119029],"valid",[],"NV8"],[[119030,119039],"disallowed"],[[119040,119078],"valid",[],"NV8"],[[119079,119080],"disallowed"],[[119081,119081],"valid",[],"NV8"],[[119082,119133],"valid",[],"NV8"],[[119134,119134],"mapped",[119127,119141]],[[119135,119135],"mapped",[119128,119141]],[[119136,119136],"mapped",[119128,119141,119150]],[[119137,119137],"mapped",[119128,119141,119151]],[[119138,119138],"mapped",[119128,119141,119152]],[[119139,119139],"mapped",[119128,119141,119153]],[[119140,119140],"mapped",[119128,119141,119154]],[[119141,119154],"valid",[],"NV8"],[[119155,119162],"disallowed"],[[119163,119226],"valid",[],"NV8"],[[119227,119227],"mapped",[119225,119141]],[[119228,119228],"mapped",[119226,119141]],[[119229,119229],"mapped",[119225,119141,119150]],[[119230,119230],"mapped",[119226,119141,119150]],[[119231,119231],"mapped",[119225,119141,119151]],[[119232,119232],"mapped",[119226,119141,119151]],[[119233,119261],"valid",[],"NV8"],[[119262,119272],"valid",[],"NV8"],[[119273,119295],"disallowed"],[[119296,119365],"valid",[],"NV8"],[[119366,119551],"disallowed"],[[119552,119638],"valid",[],"NV8"],[[119639,119647],"disallowed"],[[119648,119665],"valid",[],"NV8"],[[119666,119807],"disallowed"],[[119808,119808],"mapped",[97]],[[119809,119809],"mapped",[98]],[[119810,119810],"mapped",[99]],[[119811,119811],"mapped",[100]],[[119812,119812],"mapped",[101]],[[119813,119813],"mapped",[102]],[[119814,119814],"mapped",[103]],[[119815,119815],"mapped",[104]],[[119816,119816],"mapped",[105]],[[119817,119817],"mapped",[106]],[[119818,119818],"mapped",[107]],[[119819,119819],"mapped",[108]],[[119820,119820],"mapped",[109]],[[119821,119821],"mapped",[110]],[[119822,119822],"mapped",[111]],[[119823,119823],"mapped",[112]],[[119824,119824],"mapped",[113]],[[119825,119825],"mapped",[114]],[[119826,119826],"mapped",[115]],[[119827,119827],"mapped",[116]],[[119828,119828],"mapped",[117]],[[119829,119829],"mapped",[118]],[[119830,119830],"mapped",[119]],[[119831,119831],"mapped",[120]],[[119832,119832],"mapped",[121]],[[119833,119833],"mapped",[122]],[[119834,119834],"mapped",[97]],[[119835,119835],"mapped",[98]],[[119836,119836],"mapped",[99]],[[119837,119837],"mapped",[100]],[[119838,119838],"mapped",[101]],[[119839,119839],"mapped",[102]],[[119840,119840],"mapped",[103]],[[119841,119841],"mapped",[104]],[[119842,119842],"mapped",[105]],[[119843,119843],"mapped",[106]],[[119844,119844],"mapped",[107]],[[119845,119845],"mapped",[108]],[[119846,119846],"mapped",[109]],[[119847,119847],"mapped",[110]],[[119848,119848],"mapped",[111]],[[119849,119849],"mapped",[112]],[[119850,119850],"mapped",[113]],[[119851,119851],"mapped",[114]],[[119852,119852],"mapped",[115]],[[119853,119853],"mapped",[116]],[[119854,119854],"mapped",[117]],[[119855,119855],"mapped",[118]],[[119856,119856],"mapped",[119]],[[119857,119857],"mapped",[120]],[[119858,119858],"mapped",[121]],[[119859,119859],"mapped",[122]],[[119860,119860],"mapped",[97]],[[119861,119861],"mapped",[98]],[[119862,119862],"mapped",[99]],[[119863,119863],"mapped",[100]],[[119864,119864],"mapped",[101]],[[119865,119865],"mapped",[102]],[[119866,119866],"mapped",[103]],[[119867,119867],"mapped",[104]],[[119868,119868],"mapped",[105]],[[119869,119869],"mapped",[106]],[[119870,119870],"mapped",[107]],[[119871,119871],"mapped",[108]],[[119872,119872],"mapped",[109]],[[119873,119873],"mapped",[110]],[[119874,119874],"mapped",[111]],[[119875,119875],"mapped",[112]],[[119876,119876],"mapped",[113]],[[119877,119877],"mapped",[114]],[[119878,119878],"mapped",[115]],[[119879,119879],"mapped",[116]],[[119880,119880],"mapped",[117]],[[119881,119881],"mapped",[118]],[[119882,119882],"mapped",[119]],[[119883,119883],"mapped",[120]],[[119884,119884],"mapped",[121]],[[119885,119885],"mapped",[122]],[[119886,119886],"mapped",[97]],[[119887,119887],"mapped",[98]],[[119888,119888],"mapped",[99]],[[119889,119889],"mapped",[100]],[[119890,119890],"mapped",[101]],[[119891,119891],"mapped",[102]],[[119892,119892],"mapped",[103]],[[119893,119893],"disallowed"],[[119894,119894],"mapped",[105]],[[119895,119895],"mapped",[106]],[[119896,119896],"mapped",[107]],[[119897,119897],"mapped",[108]],[[119898,119898],"mapped",[109]],[[119899,119899],"mapped",[110]],[[119900,119900],"mapped",[111]],[[119901,119901],"mapped",[112]],[[119902,119902],"mapped",[113]],[[119903,119903],"mapped",[114]],[[119904,119904],"mapped",[115]],[[119905,119905],"mapped",[116]],[[119906,119906],"mapped",[117]],[[119907,119907],"mapped",[118]],[[119908,119908],"mapped",[119]],[[119909,119909],"mapped",[120]],[[119910,119910],"mapped",[121]],[[119911,119911],"mapped",[122]],[[119912,119912],"mapped",[97]],[[119913,119913],"mapped",[98]],[[119914,119914],"mapped",[99]],[[119915,119915],"mapped",[100]],[[119916,119916],"mapped",[101]],[[119917,119917],"mapped",[102]],[[119918,119918],"mapped",[103]],[[119919,119919],"mapped",[104]],[[119920,119920],"mapped",[105]],[[119921,119921],"mapped",[106]],[[119922,119922],"mapped",[107]],[[119923,119923],"mapped",[108]],[[119924,119924],"mapped",[109]],[[119925,119925],"mapped",[110]],[[119926,119926],"mapped",[111]],[[119927,119927],"mapped",[112]],[[119928,119928],"mapped",[113]],[[119929,119929],"mapped",[114]],[[119930,119930],"mapped",[115]],[[119931,119931],"mapped",[116]],[[119932,119932],"mapped",[117]],[[119933,119933],"mapped",[118]],[[119934,119934],"mapped",[119]],[[119935,119935],"mapped",[120]],[[119936,119936],"mapped",[121]],[[119937,119937],"mapped",[122]],[[119938,119938],"mapped",[97]],[[119939,119939],"mapped",[98]],[[119940,119940],"mapped",[99]],[[119941,119941],"mapped",[100]],[[119942,119942],"mapped",[101]],[[119943,119943],"mapped",[102]],[[119944,119944],"mapped",[103]],[[119945,119945],"mapped",[104]],[[119946,119946],"mapped",[105]],[[119947,119947],"mapped",[106]],[[119948,119948],"mapped",[107]],[[119949,119949],"mapped",[108]],[[119950,119950],"mapped",[109]],[[119951,119951],"mapped",[110]],[[119952,119952],"mapped",[111]],[[119953,119953],"mapped",[112]],[[119954,119954],"mapped",[113]],[[119955,119955],"mapped",[114]],[[119956,119956],"mapped",[115]],[[119957,119957],"mapped",[116]],[[119958,119958],"mapped",[117]],[[119959,119959],"mapped",[118]],[[119960,119960],"mapped",[119]],[[119961,119961],"mapped",[120]],[[119962,119962],"mapped",[121]],[[119963,119963],"mapped",[122]],[[119964,119964],"mapped",[97]],[[119965,119965],"disallowed"],[[119966,119966],"mapped",[99]],[[119967,119967],"mapped",[100]],[[119968,119969],"disallowed"],[[119970,119970],"mapped",[103]],[[119971,119972],"disallowed"],[[119973,119973],"mapped",[106]],[[119974,119974],"mapped",[107]],[[119975,119976],"disallowed"],[[119977,119977],"mapped",[110]],[[119978,119978],"mapped",[111]],[[119979,119979],"mapped",[112]],[[119980,119980],"mapped",[113]],[[119981,119981],"disallowed"],[[119982,119982],"mapped",[115]],[[119983,119983],"mapped",[116]],[[119984,119984],"mapped",[117]],[[119985,119985],"mapped",[118]],[[119986,119986],"mapped",[119]],[[119987,119987],"mapped",[120]],[[119988,119988],"mapped",[121]],[[119989,119989],"mapped",[122]],[[119990,119990],"mapped",[97]],[[119991,119991],"mapped",[98]],[[119992,119992],"mapped",[99]],[[119993,119993],"mapped",[100]],[[119994,119994],"disallowed"],[[119995,119995],"mapped",[102]],[[119996,119996],"disallowed"],[[119997,119997],"mapped",[104]],[[119998,119998],"mapped",[105]],[[119999,119999],"mapped",[106]],[[120000,120000],"mapped",[107]],[[120001,120001],"mapped",[108]],[[120002,120002],"mapped",[109]],[[120003,120003],"mapped",[110]],[[120004,120004],"disallowed"],[[120005,120005],"mapped",[112]],[[120006,120006],"mapped",[113]],[[120007,120007],"mapped",[114]],[[120008,120008],"mapped",[115]],[[120009,120009],"mapped",[116]],[[120010,120010],"mapped",[117]],[[120011,120011],"mapped",[118]],[[120012,120012],"mapped",[119]],[[120013,120013],"mapped",[120]],[[120014,120014],"mapped",[121]],[[120015,120015],"mapped",[122]],[[120016,120016],"mapped",[97]],[[120017,120017],"mapped",[98]],[[120018,120018],"mapped",[99]],[[120019,120019],"mapped",[100]],[[120020,120020],"mapped",[101]],[[120021,120021],"mapped",[102]],[[120022,120022],"mapped",[103]],[[120023,120023],"mapped",[104]],[[120024,120024],"mapped",[105]],[[120025,120025],"mapped",[106]],[[120026,120026],"mapped",[107]],[[120027,120027],"mapped",[108]],[[120028,120028],"mapped",[109]],[[120029,120029],"mapped",[110]],[[120030,120030],"mapped",[111]],[[120031,120031],"mapped",[112]],[[120032,120032],"mapped",[113]],[[120033,120033],"mapped",[114]],[[120034,120034],"mapped",[115]],[[120035,120035],"mapped",[116]],[[120036,120036],"mapped",[117]],[[120037,120037],"mapped",[118]],[[120038,120038],"mapped",[119]],[[120039,120039],"mapped",[120]],[[120040,120040],"mapped",[121]],[[120041,120041],"mapped",[122]],[[120042,120042],"mapped",[97]],[[120043,120043],"mapped",[98]],[[120044,120044],"mapped",[99]],[[120045,120045],"mapped",[100]],[[120046,120046],"mapped",[101]],[[120047,120047],"mapped",[102]],[[120048,120048],"mapped",[103]],[[120049,120049],"mapped",[104]],[[120050,120050],"mapped",[105]],[[120051,120051],"mapped",[106]],[[120052,120052],"mapped",[107]],[[120053,120053],"mapped",[108]],[[120054,120054],"mapped",[109]],[[120055,120055],"mapped",[110]],[[120056,120056],"mapped",[111]],[[120057,120057],"mapped",[112]],[[120058,120058],"mapped",[113]],[[120059,120059],"mapped",[114]],[[120060,120060],"mapped",[115]],[[120061,120061],"mapped",[116]],[[120062,120062],"mapped",[117]],[[120063,120063],"mapped",[118]],[[120064,120064],"mapped",[119]],[[120065,120065],"mapped",[120]],[[120066,120066],"mapped",[121]],[[120067,120067],"mapped",[122]],[[120068,120068],"mapped",[97]],[[120069,120069],"mapped",[98]],[[120070,120070],"disallowed"],[[120071,120071],"mapped",[100]],[[120072,120072],"mapped",[101]],[[120073,120073],"mapped",[102]],[[120074,120074],"mapped",[103]],[[120075,120076],"disallowed"],[[120077,120077],"mapped",[106]],[[120078,120078],"mapped",[107]],[[120079,120079],"mapped",[108]],[[120080,120080],"mapped",[109]],[[120081,120081],"mapped",[110]],[[120082,120082],"mapped",[111]],[[120083,120083],"mapped",[112]],[[120084,120084],"mapped",[113]],[[120085,120085],"disallowed"],[[120086,120086],"mapped",[115]],[[120087,120087],"mapped",[116]],[[120088,120088],"mapped",[117]],[[120089,120089],"mapped",[118]],[[120090,120090],"mapped",[119]],[[120091,120091],"mapped",[120]],[[120092,120092],"mapped",[121]],[[120093,120093],"disallowed"],[[120094,120094],"mapped",[97]],[[120095,120095],"mapped",[98]],[[120096,120096],"mapped",[99]],[[120097,120097],"mapped",[100]],[[120098,120098],"mapped",[101]],[[120099,120099],"mapped",[102]],[[120100,120100],"mapped",[103]],[[120101,120101],"mapped",[104]],[[120102,120102],"mapped",[105]],[[120103,120103],"mapped",[106]],[[120104,120104],"mapped",[107]],[[120105,120105],"mapped",[108]],[[120106,120106],"mapped",[109]],[[120107,120107],"mapped",[110]],[[120108,120108],"mapped",[111]],[[120109,120109],"mapped",[112]],[[120110,120110],"mapped",[113]],[[120111,120111],"mapped",[114]],[[120112,120112],"mapped",[115]],[[120113,120113],"mapped",[116]],[[120114,120114],"mapped",[117]],[[120115,120115],"mapped",[118]],[[120116,120116],"mapped",[119]],[[120117,120117],"mapped",[120]],[[120118,120118],"mapped",[121]],[[120119,120119],"mapped",[122]],[[120120,120120],"mapped",[97]],[[120121,120121],"mapped",[98]],[[120122,120122],"disallowed"],[[120123,120123],"mapped",[100]],[[120124,120124],"mapped",[101]],[[120125,120125],"mapped",[102]],[[120126,120126],"mapped",[103]],[[120127,120127],"disallowed"],[[120128,120128],"mapped",[105]],[[120129,120129],"mapped",[106]],[[120130,120130],"mapped",[107]],[[120131,120131],"mapped",[108]],[[120132,120132],"mapped",[109]],[[120133,120133],"disallowed"],[[120134,120134],"mapped",[111]],[[120135,120137],"disallowed"],[[120138,120138],"mapped",[115]],[[120139,120139],"mapped",[116]],[[120140,120140],"mapped",[117]],[[120141,120141],"mapped",[118]],[[120142,120142],"mapped",[119]],[[120143,120143],"mapped",[120]],[[120144,120144],"mapped",[121]],[[120145,120145],"disallowed"],[[120146,120146],"mapped",[97]],[[120147,120147],"mapped",[98]],[[120148,120148],"mapped",[99]],[[120149,120149],"mapped",[100]],[[120150,120150],"mapped",[101]],[[120151,120151],"mapped",[102]],[[120152,120152],"mapped",[103]],[[120153,120153],"mapped",[104]],[[120154,120154],"mapped",[105]],[[120155,120155],"mapped",[106]],[[120156,120156],"mapped",[107]],[[120157,120157],"mapped",[108]],[[120158,120158],"mapped",[109]],[[120159,120159],"mapped",[110]],[[120160,120160],"mapped",[111]],[[120161,120161],"mapped",[112]],[[120162,120162],"mapped",[113]],[[120163,120163],"mapped",[114]],[[120164,120164],"mapped",[115]],[[120165,120165],"mapped",[116]],[[120166,120166],"mapped",[117]],[[120167,120167],"mapped",[118]],[[120168,120168],"mapped",[119]],[[120169,120169],"mapped",[120]],[[120170,120170],"mapped",[121]],[[120171,120171],"mapped",[122]],[[120172,120172],"mapped",[97]],[[120173,120173],"mapped",[98]],[[120174,120174],"mapped",[99]],[[120175,120175],"mapped",[100]],[[120176,120176],"mapped",[101]],[[120177,120177],"mapped",[102]],[[120178,120178],"mapped",[103]],[[120179,120179],"mapped",[104]],[[120180,120180],"mapped",[105]],[[120181,120181],"mapped",[106]],[[120182,120182],"mapped",[107]],[[120183,120183],"mapped",[108]],[[120184,120184],"mapped",[109]],[[120185,120185],"mapped",[110]],[[120186,120186],"mapped",[111]],[[120187,120187],"mapped",[112]],[[120188,120188],"mapped",[113]],[[120189,120189],"mapped",[114]],[[120190,120190],"mapped",[115]],[[120191,120191],"mapped",[116]],[[120192,120192],"mapped",[117]],[[120193,120193],"mapped",[118]],[[120194,120194],"mapped",[119]],[[120195,120195],"mapped",[120]],[[120196,120196],"mapped",[121]],[[120197,120197],"mapped",[122]],[[120198,120198],"mapped",[97]],[[120199,120199],"mapped",[98]],[[120200,120200],"mapped",[99]],[[120201,120201],"mapped",[100]],[[120202,120202],"mapped",[101]],[[120203,120203],"mapped",[102]],[[120204,120204],"mapped",[103]],[[120205,120205],"mapped",[104]],[[120206,120206],"mapped",[105]],[[120207,120207],"mapped",[106]],[[120208,120208],"mapped",[107]],[[120209,120209],"mapped",[108]],[[120210,120210],"mapped",[109]],[[120211,120211],"mapped",[110]],[[120212,120212],"mapped",[111]],[[120213,120213],"mapped",[112]],[[120214,120214],"mapped",[113]],[[120215,120215],"mapped",[114]],[[120216,120216],"mapped",[115]],[[120217,120217],"mapped",[116]],[[120218,120218],"mapped",[117]],[[120219,120219],"mapped",[118]],[[120220,120220],"mapped",[119]],[[120221,120221],"mapped",[120]],[[120222,120222],"mapped",[121]],[[120223,120223],"mapped",[122]],[[120224,120224],"mapped",[97]],[[120225,120225],"mapped",[98]],[[120226,120226],"mapped",[99]],[[120227,120227],"mapped",[100]],[[120228,120228],"mapped",[101]],[[120229,120229],"mapped",[102]],[[120230,120230],"mapped",[103]],[[120231,120231],"mapped",[104]],[[120232,120232],"mapped",[105]],[[120233,120233],"mapped",[106]],[[120234,120234],"mapped",[107]],[[120235,120235],"mapped",[108]],[[120236,120236],"mapped",[109]],[[120237,120237],"mapped",[110]],[[120238,120238],"mapped",[111]],[[120239,120239],"mapped",[112]],[[120240,120240],"mapped",[113]],[[120241,120241],"mapped",[114]],[[120242,120242],"mapped",[115]],[[120243,120243],"mapped",[116]],[[120244,120244],"mapped",[117]],[[120245,120245],"mapped",[118]],[[120246,120246],"mapped",[119]],[[120247,120247],"mapped",[120]],[[120248,120248],"mapped",[121]],[[120249,120249],"mapped",[122]],[[120250,120250],"mapped",[97]],[[120251,120251],"mapped",[98]],[[120252,120252],"mapped",[99]],[[120253,120253],"mapped",[100]],[[120254,120254],"mapped",[101]],[[120255,120255],"mapped",[102]],[[120256,120256],"mapped",[103]],[[120257,120257],"mapped",[104]],[[120258,120258],"mapped",[105]],[[120259,120259],"mapped",[106]],[[120260,120260],"mapped",[107]],[[120261,120261],"mapped",[108]],[[120262,120262],"mapped",[109]],[[120263,120263],"mapped",[110]],[[120264,120264],"mapped",[111]],[[120265,120265],"mapped",[112]],[[120266,120266],"mapped",[113]],[[120267,120267],"mapped",[114]],[[120268,120268],"mapped",[115]],[[120269,120269],"mapped",[116]],[[120270,120270],"mapped",[117]],[[120271,120271],"mapped",[118]],[[120272,120272],"mapped",[119]],[[120273,120273],"mapped",[120]],[[120274,120274],"mapped",[121]],[[120275,120275],"mapped",[122]],[[120276,120276],"mapped",[97]],[[120277,120277],"mapped",[98]],[[120278,120278],"mapped",[99]],[[120279,120279],"mapped",[100]],[[120280,120280],"mapped",[101]],[[120281,120281],"mapped",[102]],[[120282,120282],"mapped",[103]],[[120283,120283],"mapped",[104]],[[120284,120284],"mapped",[105]],[[120285,120285],"mapped",[106]],[[120286,120286],"mapped",[107]],[[120287,120287],"mapped",[108]],[[120288,120288],"mapped",[109]],[[120289,120289],"mapped",[110]],[[120290,120290],"mapped",[111]],[[120291,120291],"mapped",[112]],[[120292,120292],"mapped",[113]],[[120293,120293],"mapped",[114]],[[120294,120294],"mapped",[115]],[[120295,120295],"mapped",[116]],[[120296,120296],"mapped",[117]],[[120297,120297],"mapped",[118]],[[120298,120298],"mapped",[119]],[[120299,120299],"mapped",[120]],[[120300,120300],"mapped",[121]],[[120301,120301],"mapped",[122]],[[120302,120302],"mapped",[97]],[[120303,120303],"mapped",[98]],[[120304,120304],"mapped",[99]],[[120305,120305],"mapped",[100]],[[120306,120306],"mapped",[101]],[[120307,120307],"mapped",[102]],[[120308,120308],"mapped",[103]],[[120309,120309],"mapped",[104]],[[120310,120310],"mapped",[105]],[[120311,120311],"mapped",[106]],[[120312,120312],"mapped",[107]],[[120313,120313],"mapped",[108]],[[120314,120314],"mapped",[109]],[[120315,120315],"mapped",[110]],[[120316,120316],"mapped",[111]],[[120317,120317],"mapped",[112]],[[120318,120318],"mapped",[113]],[[120319,120319],"mapped",[114]],[[120320,120320],"mapped",[115]],[[120321,120321],"mapped",[116]],[[120322,120322],"mapped",[117]],[[120323,120323],"mapped",[118]],[[120324,120324],"mapped",[119]],[[120325,120325],"mapped",[120]],[[120326,120326],"mapped",[121]],[[120327,120327],"mapped",[122]],[[120328,120328],"mapped",[97]],[[120329,120329],"mapped",[98]],[[120330,120330],"mapped",[99]],[[120331,120331],"mapped",[100]],[[120332,120332],"mapped",[101]],[[120333,120333],"mapped",[102]],[[120334,120334],"mapped",[103]],[[120335,120335],"mapped",[104]],[[120336,120336],"mapped",[105]],[[120337,120337],"mapped",[106]],[[120338,120338],"mapped",[107]],[[120339,120339],"mapped",[108]],[[120340,120340],"mapped",[109]],[[120341,120341],"mapped",[110]],[[120342,120342],"mapped",[111]],[[120343,120343],"mapped",[112]],[[120344,120344],"mapped",[113]],[[120345,120345],"mapped",[114]],[[120346,120346],"mapped",[115]],[[120347,120347],"mapped",[116]],[[120348,120348],"mapped",[117]],[[120349,120349],"mapped",[118]],[[120350,120350],"mapped",[119]],[[120351,120351],"mapped",[120]],[[120352,120352],"mapped",[121]],[[120353,120353],"mapped",[122]],[[120354,120354],"mapped",[97]],[[120355,120355],"mapped",[98]],[[120356,120356],"mapped",[99]],[[120357,120357],"mapped",[100]],[[120358,120358],"mapped",[101]],[[120359,120359],"mapped",[102]],[[120360,120360],"mapped",[103]],[[120361,120361],"mapped",[104]],[[120362,120362],"mapped",[105]],[[120363,120363],"mapped",[106]],[[120364,120364],"mapped",[107]],[[120365,120365],"mapped",[108]],[[120366,120366],"mapped",[109]],[[120367,120367],"mapped",[110]],[[120368,120368],"mapped",[111]],[[120369,120369],"mapped",[112]],[[120370,120370],"mapped",[113]],[[120371,120371],"mapped",[114]],[[120372,120372],"mapped",[115]],[[120373,120373],"mapped",[116]],[[120374,120374],"mapped",[117]],[[120375,120375],"mapped",[118]],[[120376,120376],"mapped",[119]],[[120377,120377],"mapped",[120]],[[120378,120378],"mapped",[121]],[[120379,120379],"mapped",[122]],[[120380,120380],"mapped",[97]],[[120381,120381],"mapped",[98]],[[120382,120382],"mapped",[99]],[[120383,120383],"mapped",[100]],[[120384,120384],"mapped",[101]],[[120385,120385],"mapped",[102]],[[120386,120386],"mapped",[103]],[[120387,120387],"mapped",[104]],[[120388,120388],"mapped",[105]],[[120389,120389],"mapped",[106]],[[120390,120390],"mapped",[107]],[[120391,120391],"mapped",[108]],[[120392,120392],"mapped",[109]],[[120393,120393],"mapped",[110]],[[120394,120394],"mapped",[111]],[[120395,120395],"mapped",[112]],[[120396,120396],"mapped",[113]],[[120397,120397],"mapped",[114]],[[120398,120398],"mapped",[115]],[[120399,120399],"mapped",[116]],[[120400,120400],"mapped",[117]],[[120401,120401],"mapped",[118]],[[120402,120402],"mapped",[119]],[[120403,120403],"mapped",[120]],[[120404,120404],"mapped",[121]],[[120405,120405],"mapped",[122]],[[120406,120406],"mapped",[97]],[[120407,120407],"mapped",[98]],[[120408,120408],"mapped",[99]],[[120409,120409],"mapped",[100]],[[120410,120410],"mapped",[101]],[[120411,120411],"mapped",[102]],[[120412,120412],"mapped",[103]],[[120413,120413],"mapped",[104]],[[120414,120414],"mapped",[105]],[[120415,120415],"mapped",[106]],[[120416,120416],"mapped",[107]],[[120417,120417],"mapped",[108]],[[120418,120418],"mapped",[109]],[[120419,120419],"mapped",[110]],[[120420,120420],"mapped",[111]],[[120421,120421],"mapped",[112]],[[120422,120422],"mapped",[113]],[[120423,120423],"mapped",[114]],[[120424,120424],"mapped",[115]],[[120425,120425],"mapped",[116]],[[120426,120426],"mapped",[117]],[[120427,120427],"mapped",[118]],[[120428,120428],"mapped",[119]],[[120429,120429],"mapped",[120]],[[120430,120430],"mapped",[121]],[[120431,120431],"mapped",[122]],[[120432,120432],"mapped",[97]],[[120433,120433],"mapped",[98]],[[120434,120434],"mapped",[99]],[[120435,120435],"mapped",[100]],[[120436,120436],"mapped",[101]],[[120437,120437],"mapped",[102]],[[120438,120438],"mapped",[103]],[[120439,120439],"mapped",[104]],[[120440,120440],"mapped",[105]],[[120441,120441],"mapped",[106]],[[120442,120442],"mapped",[107]],[[120443,120443],"mapped",[108]],[[120444,120444],"mapped",[109]],[[120445,120445],"mapped",[110]],[[120446,120446],"mapped",[111]],[[120447,120447],"mapped",[112]],[[120448,120448],"mapped",[113]],[[120449,120449],"mapped",[114]],[[120450,120450],"mapped",[115]],[[120451,120451],"mapped",[116]],[[120452,120452],"mapped",[117]],[[120453,120453],"mapped",[118]],[[120454,120454],"mapped",[119]],[[120455,120455],"mapped",[120]],[[120456,120456],"mapped",[121]],[[120457,120457],"mapped",[122]],[[120458,120458],"mapped",[97]],[[120459,120459],"mapped",[98]],[[120460,120460],"mapped",[99]],[[120461,120461],"mapped",[100]],[[120462,120462],"mapped",[101]],[[120463,120463],"mapped",[102]],[[120464,120464],"mapped",[103]],[[120465,120465],"mapped",[104]],[[120466,120466],"mapped",[105]],[[120467,120467],"mapped",[106]],[[120468,120468],"mapped",[107]],[[120469,120469],"mapped",[108]],[[120470,120470],"mapped",[109]],[[120471,120471],"mapped",[110]],[[120472,120472],"mapped",[111]],[[120473,120473],"mapped",[112]],[[120474,120474],"mapped",[113]],[[120475,120475],"mapped",[114]],[[120476,120476],"mapped",[115]],[[120477,120477],"mapped",[116]],[[120478,120478],"mapped",[117]],[[120479,120479],"mapped",[118]],[[120480,120480],"mapped",[119]],[[120481,120481],"mapped",[120]],[[120482,120482],"mapped",[121]],[[120483,120483],"mapped",[122]],[[120484,120484],"mapped",[305]],[[120485,120485],"mapped",[567]],[[120486,120487],"disallowed"],[[120488,120488],"mapped",[945]],[[120489,120489],"mapped",[946]],[[120490,120490],"mapped",[947]],[[120491,120491],"mapped",[948]],[[120492,120492],"mapped",[949]],[[120493,120493],"mapped",[950]],[[120494,120494],"mapped",[951]],[[120495,120495],"mapped",[952]],[[120496,120496],"mapped",[953]],[[120497,120497],"mapped",[954]],[[120498,120498],"mapped",[955]],[[120499,120499],"mapped",[956]],[[120500,120500],"mapped",[957]],[[120501,120501],"mapped",[958]],[[120502,120502],"mapped",[959]],[[120503,120503],"mapped",[960]],[[120504,120504],"mapped",[961]],[[120505,120505],"mapped",[952]],[[120506,120506],"mapped",[963]],[[120507,120507],"mapped",[964]],[[120508,120508],"mapped",[965]],[[120509,120509],"mapped",[966]],[[120510,120510],"mapped",[967]],[[120511,120511],"mapped",[968]],[[120512,120512],"mapped",[969]],[[120513,120513],"mapped",[8711]],[[120514,120514],"mapped",[945]],[[120515,120515],"mapped",[946]],[[120516,120516],"mapped",[947]],[[120517,120517],"mapped",[948]],[[120518,120518],"mapped",[949]],[[120519,120519],"mapped",[950]],[[120520,120520],"mapped",[951]],[[120521,120521],"mapped",[952]],[[120522,120522],"mapped",[953]],[[120523,120523],"mapped",[954]],[[120524,120524],"mapped",[955]],[[120525,120525],"mapped",[956]],[[120526,120526],"mapped",[957]],[[120527,120527],"mapped",[958]],[[120528,120528],"mapped",[959]],[[120529,120529],"mapped",[960]],[[120530,120530],"mapped",[961]],[[120531,120532],"mapped",[963]],[[120533,120533],"mapped",[964]],[[120534,120534],"mapped",[965]],[[120535,120535],"mapped",[966]],[[120536,120536],"mapped",[967]],[[120537,120537],"mapped",[968]],[[120538,120538],"mapped",[969]],[[120539,120539],"mapped",[8706]],[[120540,120540],"mapped",[949]],[[120541,120541],"mapped",[952]],[[120542,120542],"mapped",[954]],[[120543,120543],"mapped",[966]],[[120544,120544],"mapped",[961]],[[120545,120545],"mapped",[960]],[[120546,120546],"mapped",[945]],[[120547,120547],"mapped",[946]],[[120548,120548],"mapped",[947]],[[120549,120549],"mapped",[948]],[[120550,120550],"mapped",[949]],[[120551,120551],"mapped",[950]],[[120552,120552],"mapped",[951]],[[120553,120553],"mapped",[952]],[[120554,120554],"mapped",[953]],[[120555,120555],"mapped",[954]],[[120556,120556],"mapped",[955]],[[120557,120557],"mapped",[956]],[[120558,120558],"mapped",[957]],[[120559,120559],"mapped",[958]],[[120560,120560],"mapped",[959]],[[120561,120561],"mapped",[960]],[[120562,120562],"mapped",[961]],[[120563,120563],"mapped",[952]],[[120564,120564],"mapped",[963]],[[120565,120565],"mapped",[964]],[[120566,120566],"mapped",[965]],[[120567,120567],"mapped",[966]],[[120568,120568],"mapped",[967]],[[120569,120569],"mapped",[968]],[[120570,120570],"mapped",[969]],[[120571,120571],"mapped",[8711]],[[120572,120572],"mapped",[945]],[[120573,120573],"mapped",[946]],[[120574,120574],"mapped",[947]],[[120575,120575],"mapped",[948]],[[120576,120576],"mapped",[949]],[[120577,120577],"mapped",[950]],[[120578,120578],"mapped",[951]],[[120579,120579],"mapped",[952]],[[120580,120580],"mapped",[953]],[[120581,120581],"mapped",[954]],[[120582,120582],"mapped",[955]],[[120583,120583],"mapped",[956]],[[120584,120584],"mapped",[957]],[[120585,120585],"mapped",[958]],[[120586,120586],"mapped",[959]],[[120587,120587],"mapped",[960]],[[120588,120588],"mapped",[961]],[[120589,120590],"mapped",[963]],[[120591,120591],"mapped",[964]],[[120592,120592],"mapped",[965]],[[120593,120593],"mapped",[966]],[[120594,120594],"mapped",[967]],[[120595,120595],"mapped",[968]],[[120596,120596],"mapped",[969]],[[120597,120597],"mapped",[8706]],[[120598,120598],"mapped",[949]],[[120599,120599],"mapped",[952]],[[120600,120600],"mapped",[954]],[[120601,120601],"mapped",[966]],[[120602,120602],"mapped",[961]],[[120603,120603],"mapped",[960]],[[120604,120604],"mapped",[945]],[[120605,120605],"mapped",[946]],[[120606,120606],"mapped",[947]],[[120607,120607],"mapped",[948]],[[120608,120608],"mapped",[949]],[[120609,120609],"mapped",[950]],[[120610,120610],"mapped",[951]],[[120611,120611],"mapped",[952]],[[120612,120612],"mapped",[953]],[[120613,120613],"mapped",[954]],[[120614,120614],"mapped",[955]],[[120615,120615],"mapped",[956]],[[120616,120616],"mapped",[957]],[[120617,120617],"mapped",[958]],[[120618,120618],"mapped",[959]],[[120619,120619],"mapped",[960]],[[120620,120620],"mapped",[961]],[[120621,120621],"mapped",[952]],[[120622,120622],"mapped",[963]],[[120623,120623],"mapped",[964]],[[120624,120624],"mapped",[965]],[[120625,120625],"mapped",[966]],[[120626,120626],"mapped",[967]],[[120627,120627],"mapped",[968]],[[120628,120628],"mapped",[969]],[[120629,120629],"mapped",[8711]],[[120630,120630],"mapped",[945]],[[120631,120631],"mapped",[946]],[[120632,120632],"mapped",[947]],[[120633,120633],"mapped",[948]],[[120634,120634],"mapped",[949]],[[120635,120635],"mapped",[950]],[[120636,120636],"mapped",[951]],[[120637,120637],"mapped",[952]],[[120638,120638],"mapped",[953]],[[120639,120639],"mapped",[954]],[[120640,120640],"mapped",[955]],[[120641,120641],"mapped",[956]],[[120642,120642],"mapped",[957]],[[120643,120643],"mapped",[958]],[[120644,120644],"mapped",[959]],[[120645,120645],"mapped",[960]],[[120646,120646],"mapped",[961]],[[120647,120648],"mapped",[963]],[[120649,120649],"mapped",[964]],[[120650,120650],"mapped",[965]],[[120651,120651],"mapped",[966]],[[120652,120652],"mapped",[967]],[[120653,120653],"mapped",[968]],[[120654,120654],"mapped",[969]],[[120655,120655],"mapped",[8706]],[[120656,120656],"mapped",[949]],[[120657,120657],"mapped",[952]],[[120658,120658],"mapped",[954]],[[120659,120659],"mapped",[966]],[[120660,120660],"mapped",[961]],[[120661,120661],"mapped",[960]],[[120662,120662],"mapped",[945]],[[120663,120663],"mapped",[946]],[[120664,120664],"mapped",[947]],[[120665,120665],"mapped",[948]],[[120666,120666],"mapped",[949]],[[120667,120667],"mapped",[950]],[[120668,120668],"mapped",[951]],[[120669,120669],"mapped",[952]],[[120670,120670],"mapped",[953]],[[120671,120671],"mapped",[954]],[[120672,120672],"mapped",[955]],[[120673,120673],"mapped",[956]],[[120674,120674],"mapped",[957]],[[120675,120675],"mapped",[958]],[[120676,120676],"mapped",[959]],[[120677,120677],"mapped",[960]],[[120678,120678],"mapped",[961]],[[120679,120679],"mapped",[952]],[[120680,120680],"mapped",[963]],[[120681,120681],"mapped",[964]],[[120682,120682],"mapped",[965]],[[120683,120683],"mapped",[966]],[[120684,120684],"mapped",[967]],[[120685,120685],"mapped",[968]],[[120686,120686],"mapped",[969]],[[120687,120687],"mapped",[8711]],[[120688,120688],"mapped",[945]],[[120689,120689],"mapped",[946]],[[120690,120690],"mapped",[947]],[[120691,120691],"mapped",[948]],[[120692,120692],"mapped",[949]],[[120693,120693],"mapped",[950]],[[120694,120694],"mapped",[951]],[[120695,120695],"mapped",[952]],[[120696,120696],"mapped",[953]],[[120697,120697],"mapped",[954]],[[120698,120698],"mapped",[955]],[[120699,120699],"mapped",[956]],[[120700,120700],"mapped",[957]],[[120701,120701],"mapped",[958]],[[120702,120702],"mapped",[959]],[[120703,120703],"mapped",[960]],[[120704,120704],"mapped",[961]],[[120705,120706],"mapped",[963]],[[120707,120707],"mapped",[964]],[[120708,120708],"mapped",[965]],[[120709,120709],"mapped",[966]],[[120710,120710],"mapped",[967]],[[120711,120711],"mapped",[968]],[[120712,120712],"mapped",[969]],[[120713,120713],"mapped",[8706]],[[120714,120714],"mapped",[949]],[[120715,120715],"mapped",[952]],[[120716,120716],"mapped",[954]],[[120717,120717],"mapped",[966]],[[120718,120718],"mapped",[961]],[[120719,120719],"mapped",[960]],[[120720,120720],"mapped",[945]],[[120721,120721],"mapped",[946]],[[120722,120722],"mapped",[947]],[[120723,120723],"mapped",[948]],[[120724,120724],"mapped",[949]],[[120725,120725],"mapped",[950]],[[120726,120726],"mapped",[951]],[[120727,120727],"mapped",[952]],[[120728,120728],"mapped",[953]],[[120729,120729],"mapped",[954]],[[120730,120730],"mapped",[955]],[[120731,120731],"mapped",[956]],[[120732,120732],"mapped",[957]],[[120733,120733],"mapped",[958]],[[120734,120734],"mapped",[959]],[[120735,120735],"mapped",[960]],[[120736,120736],"mapped",[961]],[[120737,120737],"mapped",[952]],[[120738,120738],"mapped",[963]],[[120739,120739],"mapped",[964]],[[120740,120740],"mapped",[965]],[[120741,120741],"mapped",[966]],[[120742,120742],"mapped",[967]],[[120743,120743],"mapped",[968]],[[120744,120744],"mapped",[969]],[[120745,120745],"mapped",[8711]],[[120746,120746],"mapped",[945]],[[120747,120747],"mapped",[946]],[[120748,120748],"mapped",[947]],[[120749,120749],"mapped",[948]],[[120750,120750],"mapped",[949]],[[120751,120751],"mapped",[950]],[[120752,120752],"mapped",[951]],[[120753,120753],"mapped",[952]],[[120754,120754],"mapped",[953]],[[120755,120755],"mapped",[954]],[[120756,120756],"mapped",[955]],[[120757,120757],"mapped",[956]],[[120758,120758],"mapped",[957]],[[120759,120759],"mapped",[958]],[[120760,120760],"mapped",[959]],[[120761,120761],"mapped",[960]],[[120762,120762],"mapped",[961]],[[120763,120764],"mapped",[963]],[[120765,120765],"mapped",[964]],[[120766,120766],"mapped",[965]],[[120767,120767],"mapped",[966]],[[120768,120768],"mapped",[967]],[[120769,120769],"mapped",[968]],[[120770,120770],"mapped",[969]],[[120771,120771],"mapped",[8706]],[[120772,120772],"mapped",[949]],[[120773,120773],"mapped",[952]],[[120774,120774],"mapped",[954]],[[120775,120775],"mapped",[966]],[[120776,120776],"mapped",[961]],[[120777,120777],"mapped",[960]],[[120778,120779],"mapped",[989]],[[120780,120781],"disallowed"],[[120782,120782],"mapped",[48]],[[120783,120783],"mapped",[49]],[[120784,120784],"mapped",[50]],[[120785,120785],"mapped",[51]],[[120786,120786],"mapped",[52]],[[120787,120787],"mapped",[53]],[[120788,120788],"mapped",[54]],[[120789,120789],"mapped",[55]],[[120790,120790],"mapped",[56]],[[120791,120791],"mapped",[57]],[[120792,120792],"mapped",[48]],[[120793,120793],"mapped",[49]],[[120794,120794],"mapped",[50]],[[120795,120795],"mapped",[51]],[[120796,120796],"mapped",[52]],[[120797,120797],"mapped",[53]],[[120798,120798],"mapped",[54]],[[120799,120799],"mapped",[55]],[[120800,120800],"mapped",[56]],[[120801,120801],"mapped",[57]],[[120802,120802],"mapped",[48]],[[120803,120803],"mapped",[49]],[[120804,120804],"mapped",[50]],[[120805,120805],"mapped",[51]],[[120806,120806],"mapped",[52]],[[120807,120807],"mapped",[53]],[[120808,120808],"mapped",[54]],[[120809,120809],"mapped",[55]],[[120810,120810],"mapped",[56]],[[120811,120811],"mapped",[57]],[[120812,120812],"mapped",[48]],[[120813,120813],"mapped",[49]],[[120814,120814],"mapped",[50]],[[120815,120815],"mapped",[51]],[[120816,120816],"mapped",[52]],[[120817,120817],"mapped",[53]],[[120818,120818],"mapped",[54]],[[120819,120819],"mapped",[55]],[[120820,120820],"mapped",[56]],[[120821,120821],"mapped",[57]],[[120822,120822],"mapped",[48]],[[120823,120823],"mapped",[49]],[[120824,120824],"mapped",[50]],[[120825,120825],"mapped",[51]],[[120826,120826],"mapped",[52]],[[120827,120827],"mapped",[53]],[[120828,120828],"mapped",[54]],[[120829,120829],"mapped",[55]],[[120830,120830],"mapped",[56]],[[120831,120831],"mapped",[57]],[[120832,121343],"valid",[],"NV8"],[[121344,121398],"valid"],[[121399,121402],"valid",[],"NV8"],[[121403,121452],"valid"],[[121453,121460],"valid",[],"NV8"],[[121461,121461],"valid"],[[121462,121475],"valid",[],"NV8"],[[121476,121476],"valid"],[[121477,121483],"valid",[],"NV8"],[[121484,121498],"disallowed"],[[121499,121503],"valid"],[[121504,121504],"disallowed"],[[121505,121519],"valid"],[[121520,124927],"disallowed"],[[124928,125124],"valid"],[[125125,125126],"disallowed"],[[125127,125135],"valid",[],"NV8"],[[125136,125142],"valid"],[[125143,126463],"disallowed"],[[126464,126464],"mapped",[1575]],[[126465,126465],"mapped",[1576]],[[126466,126466],"mapped",[1580]],[[126467,126467],"mapped",[1583]],[[126468,126468],"disallowed"],[[126469,126469],"mapped",[1608]],[[126470,126470],"mapped",[1586]],[[126471,126471],"mapped",[1581]],[[126472,126472],"mapped",[1591]],[[126473,126473],"mapped",[1610]],[[126474,126474],"mapped",[1603]],[[126475,126475],"mapped",[1604]],[[126476,126476],"mapped",[1605]],[[126477,126477],"mapped",[1606]],[[126478,126478],"mapped",[1587]],[[126479,126479],"mapped",[1593]],[[126480,126480],"mapped",[1601]],[[126481,126481],"mapped",[1589]],[[126482,126482],"mapped",[1602]],[[126483,126483],"mapped",[1585]],[[126484,126484],"mapped",[1588]],[[126485,126485],"mapped",[1578]],[[126486,126486],"mapped",[1579]],[[126487,126487],"mapped",[1582]],[[126488,126488],"mapped",[1584]],[[126489,126489],"mapped",[1590]],[[126490,126490],"mapped",[1592]],[[126491,126491],"mapped",[1594]],[[126492,126492],"mapped",[1646]],[[126493,126493],"mapped",[1722]],[[126494,126494],"mapped",[1697]],[[126495,126495],"mapped",[1647]],[[126496,126496],"disallowed"],[[126497,126497],"mapped",[1576]],[[126498,126498],"mapped",[1580]],[[126499,126499],"disallowed"],[[126500,126500],"mapped",[1607]],[[126501,126502],"disallowed"],[[126503,126503],"mapped",[1581]],[[126504,126504],"disallowed"],[[126505,126505],"mapped",[1610]],[[126506,126506],"mapped",[1603]],[[126507,126507],"mapped",[1604]],[[126508,126508],"mapped",[1605]],[[126509,126509],"mapped",[1606]],[[126510,126510],"mapped",[1587]],[[126511,126511],"mapped",[1593]],[[126512,126512],"mapped",[1601]],[[126513,126513],"mapped",[1589]],[[126514,126514],"mapped",[1602]],[[126515,126515],"disallowed"],[[126516,126516],"mapped",[1588]],[[126517,126517],"mapped",[1578]],[[126518,126518],"mapped",[1579]],[[126519,126519],"mapped",[1582]],[[126520,126520],"disallowed"],[[126521,126521],"mapped",[1590]],[[126522,126522],"disallowed"],[[126523,126523],"mapped",[1594]],[[126524,126529],"disallowed"],[[126530,126530],"mapped",[1580]],[[126531,126534],"disallowed"],[[126535,126535],"mapped",[1581]],[[126536,126536],"disallowed"],[[126537,126537],"mapped",[1610]],[[126538,126538],"disallowed"],[[126539,126539],"mapped",[1604]],[[126540,126540],"disallowed"],[[126541,126541],"mapped",[1606]],[[126542,126542],"mapped",[1587]],[[126543,126543],"mapped",[1593]],[[126544,126544],"disallowed"],[[126545,126545],"mapped",[1589]],[[126546,126546],"mapped",[1602]],[[126547,126547],"disallowed"],[[126548,126548],"mapped",[1588]],[[126549,126550],"disallowed"],[[126551,126551],"mapped",[1582]],[[126552,126552],"disallowed"],[[126553,126553],"mapped",[1590]],[[126554,126554],"disallowed"],[[126555,126555],"mapped",[1594]],[[126556,126556],"disallowed"],[[126557,126557],"mapped",[1722]],[[126558,126558],"disallowed"],[[126559,126559],"mapped",[1647]],[[126560,126560],"disallowed"],[[126561,126561],"mapped",[1576]],[[126562,126562],"mapped",[1580]],[[126563,126563],"disallowed"],[[126564,126564],"mapped",[1607]],[[126565,126566],"disallowed"],[[126567,126567],"mapped",[1581]],[[126568,126568],"mapped",[1591]],[[126569,126569],"mapped",[1610]],[[126570,126570],"mapped",[1603]],[[126571,126571],"disallowed"],[[126572,126572],"mapped",[1605]],[[126573,126573],"mapped",[1606]],[[126574,126574],"mapped",[1587]],[[126575,126575],"mapped",[1593]],[[126576,126576],"mapped",[1601]],[[126577,126577],"mapped",[1589]],[[126578,126578],"mapped",[1602]],[[126579,126579],"disallowed"],[[126580,126580],"mapped",[1588]],[[126581,126581],"mapped",[1578]],[[126582,126582],"mapped",[1579]],[[126583,126583],"mapped",[1582]],[[126584,126584],"disallowed"],[[126585,126585],"mapped",[1590]],[[126586,126586],"mapped",[1592]],[[126587,126587],"mapped",[1594]],[[126588,126588],"mapped",[1646]],[[126589,126589],"disallowed"],[[126590,126590],"mapped",[1697]],[[126591,126591],"disallowed"],[[126592,126592],"mapped",[1575]],[[126593,126593],"mapped",[1576]],[[126594,126594],"mapped",[1580]],[[126595,126595],"mapped",[1583]],[[126596,126596],"mapped",[1607]],[[126597,126597],"mapped",[1608]],[[126598,126598],"mapped",[1586]],[[126599,126599],"mapped",[1581]],[[126600,126600],"mapped",[1591]],[[126601,126601],"mapped",[1610]],[[126602,126602],"disallowed"],[[126603,126603],"mapped",[1604]],[[126604,126604],"mapped",[1605]],[[126605,126605],"mapped",[1606]],[[126606,126606],"mapped",[1587]],[[126607,126607],"mapped",[1593]],[[126608,126608],"mapped",[1601]],[[126609,126609],"mapped",[1589]],[[126610,126610],"mapped",[1602]],[[126611,126611],"mapped",[1585]],[[126612,126612],"mapped",[1588]],[[126613,126613],"mapped",[1578]],[[126614,126614],"mapped",[1579]],[[126615,126615],"mapped",[1582]],[[126616,126616],"mapped",[1584]],[[126617,126617],"mapped",[1590]],[[126618,126618],"mapped",[1592]],[[126619,126619],"mapped",[1594]],[[126620,126624],"disallowed"],[[126625,126625],"mapped",[1576]],[[126626,126626],"mapped",[1580]],[[126627,126627],"mapped",[1583]],[[126628,126628],"disallowed"],[[126629,126629],"mapped",[1608]],[[126630,126630],"mapped",[1586]],[[126631,126631],"mapped",[1581]],[[126632,126632],"mapped",[1591]],[[126633,126633],"mapped",[1610]],[[126634,126634],"disallowed"],[[126635,126635],"mapped",[1604]],[[126636,126636],"mapped",[1605]],[[126637,126637],"mapped",[1606]],[[126638,126638],"mapped",[1587]],[[126639,126639],"mapped",[1593]],[[126640,126640],"mapped",[1601]],[[126641,126641],"mapped",[1589]],[[126642,126642],"mapped",[1602]],[[126643,126643],"mapped",[1585]],[[126644,126644],"mapped",[1588]],[[126645,126645],"mapped",[1578]],[[126646,126646],"mapped",[1579]],[[126647,126647],"mapped",[1582]],[[126648,126648],"mapped",[1584]],[[126649,126649],"mapped",[1590]],[[126650,126650],"mapped",[1592]],[[126651,126651],"mapped",[1594]],[[126652,126703],"disallowed"],[[126704,126705],"valid",[],"NV8"],[[126706,126975],"disallowed"],[[126976,127019],"valid",[],"NV8"],[[127020,127023],"disallowed"],[[127024,127123],"valid",[],"NV8"],[[127124,127135],"disallowed"],[[127136,127150],"valid",[],"NV8"],[[127151,127152],"disallowed"],[[127153,127166],"valid",[],"NV8"],[[127167,127167],"valid",[],"NV8"],[[127168,127168],"disallowed"],[[127169,127183],"valid",[],"NV8"],[[127184,127184],"disallowed"],[[127185,127199],"valid",[],"NV8"],[[127200,127221],"valid",[],"NV8"],[[127222,127231],"disallowed"],[[127232,127232],"disallowed"],[[127233,127233],"disallowed_STD3_mapped",[48,44]],[[127234,127234],"disallowed_STD3_mapped",[49,44]],[[127235,127235],"disallowed_STD3_mapped",[50,44]],[[127236,127236],"disallowed_STD3_mapped",[51,44]],[[127237,127237],"disallowed_STD3_mapped",[52,44]],[[127238,127238],"disallowed_STD3_mapped",[53,44]],[[127239,127239],"disallowed_STD3_mapped",[54,44]],[[127240,127240],"disallowed_STD3_mapped",[55,44]],[[127241,127241],"disallowed_STD3_mapped",[56,44]],[[127242,127242],"disallowed_STD3_mapped",[57,44]],[[127243,127244],"valid",[],"NV8"],[[127245,127247],"disallowed"],[[127248,127248],"disallowed_STD3_mapped",[40,97,41]],[[127249,127249],"disallowed_STD3_mapped",[40,98,41]],[[127250,127250],"disallowed_STD3_mapped",[40,99,41]],[[127251,127251],"disallowed_STD3_mapped",[40,100,41]],[[127252,127252],"disallowed_STD3_mapped",[40,101,41]],[[127253,127253],"disallowed_STD3_mapped",[40,102,41]],[[127254,127254],"disallowed_STD3_mapped",[40,103,41]],[[127255,127255],"disallowed_STD3_mapped",[40,104,41]],[[127256,127256],"disallowed_STD3_mapped",[40,105,41]],[[127257,127257],"disallowed_STD3_mapped",[40,106,41]],[[127258,127258],"disallowed_STD3_mapped",[40,107,41]],[[127259,127259],"disallowed_STD3_mapped",[40,108,41]],[[127260,127260],"disallowed_STD3_mapped",[40,109,41]],[[127261,127261],"disallowed_STD3_mapped",[40,110,41]],[[127262,127262],"disallowed_STD3_mapped",[40,111,41]],[[127263,127263],"disallowed_STD3_mapped",[40,112,41]],[[127264,127264],"disallowed_STD3_mapped",[40,113,41]],[[127265,127265],"disallowed_STD3_mapped",[40,114,41]],[[127266,127266],"disallowed_STD3_mapped",[40,115,41]],[[127267,127267],"disallowed_STD3_mapped",[40,116,41]],[[127268,127268],"disallowed_STD3_mapped",[40,117,41]],[[127269,127269],"disallowed_STD3_mapped",[40,118,41]],[[127270,127270],"disallowed_STD3_mapped",[40,119,41]],[[127271,127271],"disallowed_STD3_mapped",[40,120,41]],[[127272,127272],"disallowed_STD3_mapped",[40,121,41]],[[127273,127273],"disallowed_STD3_mapped",[40,122,41]],[[127274,127274],"mapped",[12308,115,12309]],[[127275,127275],"mapped",[99]],[[127276,127276],"mapped",[114]],[[127277,127277],"mapped",[99,100]],[[127278,127278],"mapped",[119,122]],[[127279,127279],"disallowed"],[[127280,127280],"mapped",[97]],[[127281,127281],"mapped",[98]],[[127282,127282],"mapped",[99]],[[127283,127283],"mapped",[100]],[[127284,127284],"mapped",[101]],[[127285,127285],"mapped",[102]],[[127286,127286],"mapped",[103]],[[127287,127287],"mapped",[104]],[[127288,127288],"mapped",[105]],[[127289,127289],"mapped",[106]],[[127290,127290],"mapped",[107]],[[127291,127291],"mapped",[108]],[[127292,127292],"mapped",[109]],[[127293,127293],"mapped",[110]],[[127294,127294],"mapped",[111]],[[127295,127295],"mapped",[112]],[[127296,127296],"mapped",[113]],[[127297,127297],"mapped",[114]],[[127298,127298],"mapped",[115]],[[127299,127299],"mapped",[116]],[[127300,127300],"mapped",[117]],[[127301,127301],"mapped",[118]],[[127302,127302],"mapped",[119]],[[127303,127303],"mapped",[120]],[[127304,127304],"mapped",[121]],[[127305,127305],"mapped",[122]],[[127306,127306],"mapped",[104,118]],[[127307,127307],"mapped",[109,118]],[[127308,127308],"mapped",[115,100]],[[127309,127309],"mapped",[115,115]],[[127310,127310],"mapped",[112,112,118]],[[127311,127311],"mapped",[119,99]],[[127312,127318],"valid",[],"NV8"],[[127319,127319],"valid",[],"NV8"],[[127320,127326],"valid",[],"NV8"],[[127327,127327],"valid",[],"NV8"],[[127328,127337],"valid",[],"NV8"],[[127338,127338],"mapped",[109,99]],[[127339,127339],"mapped",[109,100]],[[127340,127343],"disallowed"],[[127344,127352],"valid",[],"NV8"],[[127353,127353],"valid",[],"NV8"],[[127354,127354],"valid",[],"NV8"],[[127355,127356],"valid",[],"NV8"],[[127357,127358],"valid",[],"NV8"],[[127359,127359],"valid",[],"NV8"],[[127360,127369],"valid",[],"NV8"],[[127370,127373],"valid",[],"NV8"],[[127374,127375],"valid",[],"NV8"],[[127376,127376],"mapped",[100,106]],[[127377,127386],"valid",[],"NV8"],[[127387,127461],"disallowed"],[[127462,127487],"valid",[],"NV8"],[[127488,127488],"mapped",[12411,12363]],[[127489,127489],"mapped",[12467,12467]],[[127490,127490],"mapped",[12469]],[[127491,127503],"disallowed"],[[127504,127504],"mapped",[25163]],[[127505,127505],"mapped",[23383]],[[127506,127506],"mapped",[21452]],[[127507,127507],"mapped",[12487]],[[127508,127508],"mapped",[20108]],[[127509,127509],"mapped",[22810]],[[127510,127510],"mapped",[35299]],[[127511,127511],"mapped",[22825]],[[127512,127512],"mapped",[20132]],[[127513,127513],"mapped",[26144]],[[127514,127514],"mapped",[28961]],[[127515,127515],"mapped",[26009]],[[127516,127516],"mapped",[21069]],[[127517,127517],"mapped",[24460]],[[127518,127518],"mapped",[20877]],[[127519,127519],"mapped",[26032]],[[127520,127520],"mapped",[21021]],[[127521,127521],"mapped",[32066]],[[127522,127522],"mapped",[29983]],[[127523,127523],"mapped",[36009]],[[127524,127524],"mapped",[22768]],[[127525,127525],"mapped",[21561]],[[127526,127526],"mapped",[28436]],[[127527,127527],"mapped",[25237]],[[127528,127528],"mapped",[25429]],[[127529,127529],"mapped",[19968]],[[127530,127530],"mapped",[19977]],[[127531,127531],"mapped",[36938]],[[127532,127532],"mapped",[24038]],[[127533,127533],"mapped",[20013]],[[127534,127534],"mapped",[21491]],[[127535,127535],"mapped",[25351]],[[127536,127536],"mapped",[36208]],[[127537,127537],"mapped",[25171]],[[127538,127538],"mapped",[31105]],[[127539,127539],"mapped",[31354]],[[127540,127540],"mapped",[21512]],[[127541,127541],"mapped",[28288]],[[127542,127542],"mapped",[26377]],[[127543,127543],"mapped",[26376]],[[127544,127544],"mapped",[30003]],[[127545,127545],"mapped",[21106]],[[127546,127546],"mapped",[21942]],[[127547,127551],"disallowed"],[[127552,127552],"mapped",[12308,26412,12309]],[[127553,127553],"mapped",[12308,19977,12309]],[[127554,127554],"mapped",[12308,20108,12309]],[[127555,127555],"mapped",[12308,23433,12309]],[[127556,127556],"mapped",[12308,28857,12309]],[[127557,127557],"mapped",[12308,25171,12309]],[[127558,127558],"mapped",[12308,30423,12309]],[[127559,127559],"mapped",[12308,21213,12309]],[[127560,127560],"mapped",[12308,25943,12309]],[[127561,127567],"disallowed"],[[127568,127568],"mapped",[24471]],[[127569,127569],"mapped",[21487]],[[127570,127743],"disallowed"],[[127744,127776],"valid",[],"NV8"],[[127777,127788],"valid",[],"NV8"],[[127789,127791],"valid",[],"NV8"],[[127792,127797],"valid",[],"NV8"],[[127798,127798],"valid",[],"NV8"],[[127799,127868],"valid",[],"NV8"],[[127869,127869],"valid",[],"NV8"],[[127870,127871],"valid",[],"NV8"],[[127872,127891],"valid",[],"NV8"],[[127892,127903],"valid",[],"NV8"],[[127904,127940],"valid",[],"NV8"],[[127941,127941],"valid",[],"NV8"],[[127942,127946],"valid",[],"NV8"],[[127947,127950],"valid",[],"NV8"],[[127951,127955],"valid",[],"NV8"],[[127956,127967],"valid",[],"NV8"],[[127968,127984],"valid",[],"NV8"],[[127985,127991],"valid",[],"NV8"],[[127992,127999],"valid",[],"NV8"],[[128000,128062],"valid",[],"NV8"],[[128063,128063],"valid",[],"NV8"],[[128064,128064],"valid",[],"NV8"],[[128065,128065],"valid",[],"NV8"],[[128066,128247],"valid",[],"NV8"],[[128248,128248],"valid",[],"NV8"],[[128249,128252],"valid",[],"NV8"],[[128253,128254],"valid",[],"NV8"],[[128255,128255],"valid",[],"NV8"],[[128256,128317],"valid",[],"NV8"],[[128318,128319],"valid",[],"NV8"],[[128320,128323],"valid",[],"NV8"],[[128324,128330],"valid",[],"NV8"],[[128331,128335],"valid",[],"NV8"],[[128336,128359],"valid",[],"NV8"],[[128360,128377],"valid",[],"NV8"],[[128378,128378],"disallowed"],[[128379,128419],"valid",[],"NV8"],[[128420,128420],"disallowed"],[[128421,128506],"valid",[],"NV8"],[[128507,128511],"valid",[],"NV8"],[[128512,128512],"valid",[],"NV8"],[[128513,128528],"valid",[],"NV8"],[[128529,128529],"valid",[],"NV8"],[[128530,128532],"valid",[],"NV8"],[[128533,128533],"valid",[],"NV8"],[[128534,128534],"valid",[],"NV8"],[[128535,128535],"valid",[],"NV8"],[[128536,128536],"valid",[],"NV8"],[[128537,128537],"valid",[],"NV8"],[[128538,128538],"valid",[],"NV8"],[[128539,128539],"valid",[],"NV8"],[[128540,128542],"valid",[],"NV8"],[[128543,128543],"valid",[],"NV8"],[[128544,128549],"valid",[],"NV8"],[[128550,128551],"valid",[],"NV8"],[[128552,128555],"valid",[],"NV8"],[[128556,128556],"valid",[],"NV8"],[[128557,128557],"valid",[],"NV8"],[[128558,128559],"valid",[],"NV8"],[[128560,128563],"valid",[],"NV8"],[[128564,128564],"valid",[],"NV8"],[[128565,128576],"valid",[],"NV8"],[[128577,128578],"valid",[],"NV8"],[[128579,128580],"valid",[],"NV8"],[[128581,128591],"valid",[],"NV8"],[[128592,128639],"valid",[],"NV8"],[[128640,128709],"valid",[],"NV8"],[[128710,128719],"valid",[],"NV8"],[[128720,128720],"valid",[],"NV8"],[[128721,128735],"disallowed"],[[128736,128748],"valid",[],"NV8"],[[128749,128751],"disallowed"],[[128752,128755],"valid",[],"NV8"],[[128756,128767],"disallowed"],[[128768,128883],"valid",[],"NV8"],[[128884,128895],"disallowed"],[[128896,128980],"valid",[],"NV8"],[[128981,129023],"disallowed"],[[129024,129035],"valid",[],"NV8"],[[129036,129039],"disallowed"],[[129040,129095],"valid",[],"NV8"],[[129096,129103],"disallowed"],[[129104,129113],"valid",[],"NV8"],[[129114,129119],"disallowed"],[[129120,129159],"valid",[],"NV8"],[[129160,129167],"disallowed"],[[129168,129197],"valid",[],"NV8"],[[129198,129295],"disallowed"],[[129296,129304],"valid",[],"NV8"],[[129305,129407],"disallowed"],[[129408,129412],"valid",[],"NV8"],[[129413,129471],"disallowed"],[[129472,129472],"valid",[],"NV8"],[[129473,131069],"disallowed"],[[131070,131071],"disallowed"],[[131072,173782],"valid"],[[173783,173823],"disallowed"],[[173824,177972],"valid"],[[177973,177983],"disallowed"],[[177984,178205],"valid"],[[178206,178207],"disallowed"],[[178208,183969],"valid"],[[183970,194559],"disallowed"],[[194560,194560],"mapped",[20029]],[[194561,194561],"mapped",[20024]],[[194562,194562],"mapped",[20033]],[[194563,194563],"mapped",[131362]],[[194564,194564],"mapped",[20320]],[[194565,194565],"mapped",[20398]],[[194566,194566],"mapped",[20411]],[[194567,194567],"mapped",[20482]],[[194568,194568],"mapped",[20602]],[[194569,194569],"mapped",[20633]],[[194570,194570],"mapped",[20711]],[[194571,194571],"mapped",[20687]],[[194572,194572],"mapped",[13470]],[[194573,194573],"mapped",[132666]],[[194574,194574],"mapped",[20813]],[[194575,194575],"mapped",[20820]],[[194576,194576],"mapped",[20836]],[[194577,194577],"mapped",[20855]],[[194578,194578],"mapped",[132380]],[[194579,194579],"mapped",[13497]],[[194580,194580],"mapped",[20839]],[[194581,194581],"mapped",[20877]],[[194582,194582],"mapped",[132427]],[[194583,194583],"mapped",[20887]],[[194584,194584],"mapped",[20900]],[[194585,194585],"mapped",[20172]],[[194586,194586],"mapped",[20908]],[[194587,194587],"mapped",[20917]],[[194588,194588],"mapped",[168415]],[[194589,194589],"mapped",[20981]],[[194590,194590],"mapped",[20995]],[[194591,194591],"mapped",[13535]],[[194592,194592],"mapped",[21051]],[[194593,194593],"mapped",[21062]],[[194594,194594],"mapped",[21106]],[[194595,194595],"mapped",[21111]],[[194596,194596],"mapped",[13589]],[[194597,194597],"mapped",[21191]],[[194598,194598],"mapped",[21193]],[[194599,194599],"mapped",[21220]],[[194600,194600],"mapped",[21242]],[[194601,194601],"mapped",[21253]],[[194602,194602],"mapped",[21254]],[[194603,194603],"mapped",[21271]],[[194604,194604],"mapped",[21321]],[[194605,194605],"mapped",[21329]],[[194606,194606],"mapped",[21338]],[[194607,194607],"mapped",[21363]],[[194608,194608],"mapped",[21373]],[[194609,194611],"mapped",[21375]],[[194612,194612],"mapped",[133676]],[[194613,194613],"mapped",[28784]],[[194614,194614],"mapped",[21450]],[[194615,194615],"mapped",[21471]],[[194616,194616],"mapped",[133987]],[[194617,194617],"mapped",[21483]],[[194618,194618],"mapped",[21489]],[[194619,194619],"mapped",[21510]],[[194620,194620],"mapped",[21662]],[[194621,194621],"mapped",[21560]],[[194622,194622],"mapped",[21576]],[[194623,194623],"mapped",[21608]],[[194624,194624],"mapped",[21666]],[[194625,194625],"mapped",[21750]],[[194626,194626],"mapped",[21776]],[[194627,194627],"mapped",[21843]],[[194628,194628],"mapped",[21859]],[[194629,194630],"mapped",[21892]],[[194631,194631],"mapped",[21913]],[[194632,194632],"mapped",[21931]],[[194633,194633],"mapped",[21939]],[[194634,194634],"mapped",[21954]],[[194635,194635],"mapped",[22294]],[[194636,194636],"mapped",[22022]],[[194637,194637],"mapped",[22295]],[[194638,194638],"mapped",[22097]],[[194639,194639],"mapped",[22132]],[[194640,194640],"mapped",[20999]],[[194641,194641],"mapped",[22766]],[[194642,194642],"mapped",[22478]],[[194643,194643],"mapped",[22516]],[[194644,194644],"mapped",[22541]],[[194645,194645],"mapped",[22411]],[[194646,194646],"mapped",[22578]],[[194647,194647],"mapped",[22577]],[[194648,194648],"mapped",[22700]],[[194649,194649],"mapped",[136420]],[[194650,194650],"mapped",[22770]],[[194651,194651],"mapped",[22775]],[[194652,194652],"mapped",[22790]],[[194653,194653],"mapped",[22810]],[[194654,194654],"mapped",[22818]],[[194655,194655],"mapped",[22882]],[[194656,194656],"mapped",[136872]],[[194657,194657],"mapped",[136938]],[[194658,194658],"mapped",[23020]],[[194659,194659],"mapped",[23067]],[[194660,194660],"mapped",[23079]],[[194661,194661],"mapped",[23000]],[[194662,194662],"mapped",[23142]],[[194663,194663],"mapped",[14062]],[[194664,194664],"disallowed"],[[194665,194665],"mapped",[23304]],[[194666,194667],"mapped",[23358]],[[194668,194668],"mapped",[137672]],[[194669,194669],"mapped",[23491]],[[194670,194670],"mapped",[23512]],[[194671,194671],"mapped",[23527]],[[194672,194672],"mapped",[23539]],[[194673,194673],"mapped",[138008]],[[194674,194674],"mapped",[23551]],[[194675,194675],"mapped",[23558]],[[194676,194676],"disallowed"],[[194677,194677],"mapped",[23586]],[[194678,194678],"mapped",[14209]],[[194679,194679],"mapped",[23648]],[[194680,194680],"mapped",[23662]],[[194681,194681],"mapped",[23744]],[[194682,194682],"mapped",[23693]],[[194683,194683],"mapped",[138724]],[[194684,194684],"mapped",[23875]],[[194685,194685],"mapped",[138726]],[[194686,194686],"mapped",[23918]],[[194687,194687],"mapped",[23915]],[[194688,194688],"mapped",[23932]],[[194689,194689],"mapped",[24033]],[[194690,194690],"mapped",[24034]],[[194691,194691],"mapped",[14383]],[[194692,194692],"mapped",[24061]],[[194693,194693],"mapped",[24104]],[[194694,194694],"mapped",[24125]],[[194695,194695],"mapped",[24169]],[[194696,194696],"mapped",[14434]],[[194697,194697],"mapped",[139651]],[[194698,194698],"mapped",[14460]],[[194699,194699],"mapped",[24240]],[[194700,194700],"mapped",[24243]],[[194701,194701],"mapped",[24246]],[[194702,194702],"mapped",[24266]],[[194703,194703],"mapped",[172946]],[[194704,194704],"mapped",[24318]],[[194705,194706],"mapped",[140081]],[[194707,194707],"mapped",[33281]],[[194708,194709],"mapped",[24354]],[[194710,194710],"mapped",[14535]],[[194711,194711],"mapped",[144056]],[[194712,194712],"mapped",[156122]],[[194713,194713],"mapped",[24418]],[[194714,194714],"mapped",[24427]],[[194715,194715],"mapped",[14563]],[[194716,194716],"mapped",[24474]],[[194717,194717],"mapped",[24525]],[[194718,194718],"mapped",[24535]],[[194719,194719],"mapped",[24569]],[[194720,194720],"mapped",[24705]],[[194721,194721],"mapped",[14650]],[[194722,194722],"mapped",[14620]],[[194723,194723],"mapped",[24724]],[[194724,194724],"mapped",[141012]],[[194725,194725],"mapped",[24775]],[[194726,194726],"mapped",[24904]],[[194727,194727],"mapped",[24908]],[[194728,194728],"mapped",[24910]],[[194729,194729],"mapped",[24908]],[[194730,194730],"mapped",[24954]],[[194731,194731],"mapped",[24974]],[[194732,194732],"mapped",[25010]],[[194733,194733],"mapped",[24996]],[[194734,194734],"mapped",[25007]],[[194735,194735],"mapped",[25054]],[[194736,194736],"mapped",[25074]],[[194737,194737],"mapped",[25078]],[[194738,194738],"mapped",[25104]],[[194739,194739],"mapped",[25115]],[[194740,194740],"mapped",[25181]],[[194741,194741],"mapped",[25265]],[[194742,194742],"mapped",[25300]],[[194743,194743],"mapped",[25424]],[[194744,194744],"mapped",[142092]],[[194745,194745],"mapped",[25405]],[[194746,194746],"mapped",[25340]],[[194747,194747],"mapped",[25448]],[[194748,194748],"mapped",[25475]],[[194749,194749],"mapped",[25572]],[[194750,194750],"mapped",[142321]],[[194751,194751],"mapped",[25634]],[[194752,194752],"mapped",[25541]],[[194753,194753],"mapped",[25513]],[[194754,194754],"mapped",[14894]],[[194755,194755],"mapped",[25705]],[[194756,194756],"mapped",[25726]],[[194757,194757],"mapped",[25757]],[[194758,194758],"mapped",[25719]],[[194759,194759],"mapped",[14956]],[[194760,194760],"mapped",[25935]],[[194761,194761],"mapped",[25964]],[[194762,194762],"mapped",[143370]],[[194763,194763],"mapped",[26083]],[[194764,194764],"mapped",[26360]],[[194765,194765],"mapped",[26185]],[[194766,194766],"mapped",[15129]],[[194767,194767],"mapped",[26257]],[[194768,194768],"mapped",[15112]],[[194769,194769],"mapped",[15076]],[[194770,194770],"mapped",[20882]],[[194771,194771],"mapped",[20885]],[[194772,194772],"mapped",[26368]],[[194773,194773],"mapped",[26268]],[[194774,194774],"mapped",[32941]],[[194775,194775],"mapped",[17369]],[[194776,194776],"mapped",[26391]],[[194777,194777],"mapped",[26395]],[[194778,194778],"mapped",[26401]],[[194779,194779],"mapped",[26462]],[[194780,194780],"mapped",[26451]],[[194781,194781],"mapped",[144323]],[[194782,194782],"mapped",[15177]],[[194783,194783],"mapped",[26618]],[[194784,194784],"mapped",[26501]],[[194785,194785],"mapped",[26706]],[[194786,194786],"mapped",[26757]],[[194787,194787],"mapped",[144493]],[[194788,194788],"mapped",[26766]],[[194789,194789],"mapped",[26655]],[[194790,194790],"mapped",[26900]],[[194791,194791],"mapped",[15261]],[[194792,194792],"mapped",[26946]],[[194793,194793],"mapped",[27043]],[[194794,194794],"mapped",[27114]],[[194795,194795],"mapped",[27304]],[[194796,194796],"mapped",[145059]],[[194797,194797],"mapped",[27355]],[[194798,194798],"mapped",[15384]],[[194799,194799],"mapped",[27425]],[[194800,194800],"mapped",[145575]],[[194801,194801],"mapped",[27476]],[[194802,194802],"mapped",[15438]],[[194803,194803],"mapped",[27506]],[[194804,194804],"mapped",[27551]],[[194805,194805],"mapped",[27578]],[[194806,194806],"mapped",[27579]],[[194807,194807],"mapped",[146061]],[[194808,194808],"mapped",[138507]],[[194809,194809],"mapped",[146170]],[[194810,194810],"mapped",[27726]],[[194811,194811],"mapped",[146620]],[[194812,194812],"mapped",[27839]],[[194813,194813],"mapped",[27853]],[[194814,194814],"mapped",[27751]],[[194815,194815],"mapped",[27926]],[[194816,194816],"mapped",[27966]],[[194817,194817],"mapped",[28023]],[[194818,194818],"mapped",[27969]],[[194819,194819],"mapped",[28009]],[[194820,194820],"mapped",[28024]],[[194821,194821],"mapped",[28037]],[[194822,194822],"mapped",[146718]],[[194823,194823],"mapped",[27956]],[[194824,194824],"mapped",[28207]],[[194825,194825],"mapped",[28270]],[[194826,194826],"mapped",[15667]],[[194827,194827],"mapped",[28363]],[[194828,194828],"mapped",[28359]],[[194829,194829],"mapped",[147153]],[[194830,194830],"mapped",[28153]],[[194831,194831],"mapped",[28526]],[[194832,194832],"mapped",[147294]],[[194833,194833],"mapped",[147342]],[[194834,194834],"mapped",[28614]],[[194835,194835],"mapped",[28729]],[[194836,194836],"mapped",[28702]],[[194837,194837],"mapped",[28699]],[[194838,194838],"mapped",[15766]],[[194839,194839],"mapped",[28746]],[[194840,194840],"mapped",[28797]],[[194841,194841],"mapped",[28791]],[[194842,194842],"mapped",[28845]],[[194843,194843],"mapped",[132389]],[[194844,194844],"mapped",[28997]],[[194845,194845],"mapped",[148067]],[[194846,194846],"mapped",[29084]],[[194847,194847],"disallowed"],[[194848,194848],"mapped",[29224]],[[194849,194849],"mapped",[29237]],[[194850,194850],"mapped",[29264]],[[194851,194851],"mapped",[149000]],[[194852,194852],"mapped",[29312]],[[194853,194853],"mapped",[29333]],[[194854,194854],"mapped",[149301]],[[194855,194855],"mapped",[149524]],[[194856,194856],"mapped",[29562]],[[194857,194857],"mapped",[29579]],[[194858,194858],"mapped",[16044]],[[194859,194859],"mapped",[29605]],[[194860,194861],"mapped",[16056]],[[194862,194862],"mapped",[29767]],[[194863,194863],"mapped",[29788]],[[194864,194864],"mapped",[29809]],[[194865,194865],"mapped",[29829]],[[194866,194866],"mapped",[29898]],[[194867,194867],"mapped",[16155]],[[194868,194868],"mapped",[29988]],[[194869,194869],"mapped",[150582]],[[194870,194870],"mapped",[30014]],[[194871,194871],"mapped",[150674]],[[194872,194872],"mapped",[30064]],[[194873,194873],"mapped",[139679]],[[194874,194874],"mapped",[30224]],[[194875,194875],"mapped",[151457]],[[194876,194876],"mapped",[151480]],[[194877,194877],"mapped",[151620]],[[194878,194878],"mapped",[16380]],[[194879,194879],"mapped",[16392]],[[194880,194880],"mapped",[30452]],[[194881,194881],"mapped",[151795]],[[194882,194882],"mapped",[151794]],[[194883,194883],"mapped",[151833]],[[194884,194884],"mapped",[151859]],[[194885,194885],"mapped",[30494]],[[194886,194887],"mapped",[30495]],[[194888,194888],"mapped",[30538]],[[194889,194889],"mapped",[16441]],[[194890,194890],"mapped",[30603]],[[194891,194891],"mapped",[16454]],[[194892,194892],"mapped",[16534]],[[194893,194893],"mapped",[152605]],[[194894,194894],"mapped",[30798]],[[194895,194895],"mapped",[30860]],[[194896,194896],"mapped",[30924]],[[194897,194897],"mapped",[16611]],[[194898,194898],"mapped",[153126]],[[194899,194899],"mapped",[31062]],[[194900,194900],"mapped",[153242]],[[194901,194901],"mapped",[153285]],[[194902,194902],"mapped",[31119]],[[194903,194903],"mapped",[31211]],[[194904,194904],"mapped",[16687]],[[194905,194905],"mapped",[31296]],[[194906,194906],"mapped",[31306]],[[194907,194907],"mapped",[31311]],[[194908,194908],"mapped",[153980]],[[194909,194910],"mapped",[154279]],[[194911,194911],"disallowed"],[[194912,194912],"mapped",[16898]],[[194913,194913],"mapped",[154539]],[[194914,194914],"mapped",[31686]],[[194915,194915],"mapped",[31689]],[[194916,194916],"mapped",[16935]],[[194917,194917],"mapped",[154752]],[[194918,194918],"mapped",[31954]],[[194919,194919],"mapped",[17056]],[[194920,194920],"mapped",[31976]],[[194921,194921],"mapped",[31971]],[[194922,194922],"mapped",[32000]],[[194923,194923],"mapped",[155526]],[[194924,194924],"mapped",[32099]],[[194925,194925],"mapped",[17153]],[[194926,194926],"mapped",[32199]],[[194927,194927],"mapped",[32258]],[[194928,194928],"mapped",[32325]],[[194929,194929],"mapped",[17204]],[[194930,194930],"mapped",[156200]],[[194931,194931],"mapped",[156231]],[[194932,194932],"mapped",[17241]],[[194933,194933],"mapped",[156377]],[[194934,194934],"mapped",[32634]],[[194935,194935],"mapped",[156478]],[[194936,194936],"mapped",[32661]],[[194937,194937],"mapped",[32762]],[[194938,194938],"mapped",[32773]],[[194939,194939],"mapped",[156890]],[[194940,194940],"mapped",[156963]],[[194941,194941],"mapped",[32864]],[[194942,194942],"mapped",[157096]],[[194943,194943],"mapped",[32880]],[[194944,194944],"mapped",[144223]],[[194945,194945],"mapped",[17365]],[[194946,194946],"mapped",[32946]],[[194947,194947],"mapped",[33027]],[[194948,194948],"mapped",[17419]],[[194949,194949],"mapped",[33086]],[[194950,194950],"mapped",[23221]],[[194951,194951],"mapped",[157607]],[[194952,194952],"mapped",[157621]],[[194953,194953],"mapped",[144275]],[[194954,194954],"mapped",[144284]],[[194955,194955],"mapped",[33281]],[[194956,194956],"mapped",[33284]],[[194957,194957],"mapped",[36766]],[[194958,194958],"mapped",[17515]],[[194959,194959],"mapped",[33425]],[[194960,194960],"mapped",[33419]],[[194961,194961],"mapped",[33437]],[[194962,194962],"mapped",[21171]],[[194963,194963],"mapped",[33457]],[[194964,194964],"mapped",[33459]],[[194965,194965],"mapped",[33469]],[[194966,194966],"mapped",[33510]],[[194967,194967],"mapped",[158524]],[[194968,194968],"mapped",[33509]],[[194969,194969],"mapped",[33565]],[[194970,194970],"mapped",[33635]],[[194971,194971],"mapped",[33709]],[[194972,194972],"mapped",[33571]],[[194973,194973],"mapped",[33725]],[[194974,194974],"mapped",[33767]],[[194975,194975],"mapped",[33879]],[[194976,194976],"mapped",[33619]],[[194977,194977],"mapped",[33738]],[[194978,194978],"mapped",[33740]],[[194979,194979],"mapped",[33756]],[[194980,194980],"mapped",[158774]],[[194981,194981],"mapped",[159083]],[[194982,194982],"mapped",[158933]],[[194983,194983],"mapped",[17707]],[[194984,194984],"mapped",[34033]],[[194985,194985],"mapped",[34035]],[[194986,194986],"mapped",[34070]],[[194987,194987],"mapped",[160714]],[[194988,194988],"mapped",[34148]],[[194989,194989],"mapped",[159532]],[[194990,194990],"mapped",[17757]],[[194991,194991],"mapped",[17761]],[[194992,194992],"mapped",[159665]],[[194993,194993],"mapped",[159954]],[[194994,194994],"mapped",[17771]],[[194995,194995],"mapped",[34384]],[[194996,194996],"mapped",[34396]],[[194997,194997],"mapped",[34407]],[[194998,194998],"mapped",[34409]],[[194999,194999],"mapped",[34473]],[[195000,195000],"mapped",[34440]],[[195001,195001],"mapped",[34574]],[[195002,195002],"mapped",[34530]],[[195003,195003],"mapped",[34681]],[[195004,195004],"mapped",[34600]],[[195005,195005],"mapped",[34667]],[[195006,195006],"mapped",[34694]],[[195007,195007],"disallowed"],[[195008,195008],"mapped",[34785]],[[195009,195009],"mapped",[34817]],[[195010,195010],"mapped",[17913]],[[195011,195011],"mapped",[34912]],[[195012,195012],"mapped",[34915]],[[195013,195013],"mapped",[161383]],[[195014,195014],"mapped",[35031]],[[195015,195015],"mapped",[35038]],[[195016,195016],"mapped",[17973]],[[195017,195017],"mapped",[35066]],[[195018,195018],"mapped",[13499]],[[195019,195019],"mapped",[161966]],[[195020,195020],"mapped",[162150]],[[195021,195021],"mapped",[18110]],[[195022,195022],"mapped",[18119]],[[195023,195023],"mapped",[35488]],[[195024,195024],"mapped",[35565]],[[195025,195025],"mapped",[35722]],[[195026,195026],"mapped",[35925]],[[195027,195027],"mapped",[162984]],[[195028,195028],"mapped",[36011]],[[195029,195029],"mapped",[36033]],[[195030,195030],"mapped",[36123]],[[195031,195031],"mapped",[36215]],[[195032,195032],"mapped",[163631]],[[195033,195033],"mapped",[133124]],[[195034,195034],"mapped",[36299]],[[195035,195035],"mapped",[36284]],[[195036,195036],"mapped",[36336]],[[195037,195037],"mapped",[133342]],[[195038,195038],"mapped",[36564]],[[195039,195039],"mapped",[36664]],[[195040,195040],"mapped",[165330]],[[195041,195041],"mapped",[165357]],[[195042,195042],"mapped",[37012]],[[195043,195043],"mapped",[37105]],[[195044,195044],"mapped",[37137]],[[195045,195045],"mapped",[165678]],[[195046,195046],"mapped",[37147]],[[195047,195047],"mapped",[37432]],[[195048,195048],"mapped",[37591]],[[195049,195049],"mapped",[37592]],[[195050,195050],"mapped",[37500]],[[195051,195051],"mapped",[37881]],[[195052,195052],"mapped",[37909]],[[195053,195053],"mapped",[166906]],[[195054,195054],"mapped",[38283]],[[195055,195055],"mapped",[18837]],[[195056,195056],"mapped",[38327]],[[195057,195057],"mapped",[167287]],[[195058,195058],"mapped",[18918]],[[195059,195059],"mapped",[38595]],[[195060,195060],"mapped",[23986]],[[195061,195061],"mapped",[38691]],[[195062,195062],"mapped",[168261]],[[195063,195063],"mapped",[168474]],[[195064,195064],"mapped",[19054]],[[195065,195065],"mapped",[19062]],[[195066,195066],"mapped",[38880]],[[195067,195067],"mapped",[168970]],[[195068,195068],"mapped",[19122]],[[195069,195069],"mapped",[169110]],[[195070,195071],"mapped",[38923]],[[195072,195072],"mapped",[38953]],[[195073,195073],"mapped",[169398]],[[195074,195074],"mapped",[39138]],[[195075,195075],"mapped",[19251]],[[195076,195076],"mapped",[39209]],[[195077,195077],"mapped",[39335]],[[195078,195078],"mapped",[39362]],[[195079,195079],"mapped",[39422]],[[195080,195080],"mapped",[19406]],[[195081,195081],"mapped",[170800]],[[195082,195082],"mapped",[39698]],[[195083,195083],"mapped",[40000]],[[195084,195084],"mapped",[40189]],[[195085,195085],"mapped",[19662]],[[195086,195086],"mapped",[19693]],[[195087,195087],"mapped",[40295]],[[195088,195088],"mapped",[172238]],[[195089,195089],"mapped",[19704]],[[195090,195090],"mapped",[172293]],[[195091,195091],"mapped",[172558]],[[195092,195092],"mapped",[172689]],[[195093,195093],"mapped",[40635]],[[195094,195094],"mapped",[19798]],[[195095,195095],"mapped",[40697]],[[195096,195096],"mapped",[40702]],[[195097,195097],"mapped",[40709]],[[195098,195098],"mapped",[40719]],[[195099,195099],"mapped",[40726]],[[195100,195100],"mapped",[40763]],[[195101,195101],"mapped",[173568]],[[195102,196605],"disallowed"],[[196606,196607],"disallowed"],[[196608,262141],"disallowed"],[[262142,262143],"disallowed"],[[262144,327677],"disallowed"],[[327678,327679],"disallowed"],[[327680,393213],"disallowed"],[[393214,393215],"disallowed"],[[393216,458749],"disallowed"],[[458750,458751],"disallowed"],[[458752,524285],"disallowed"],[[524286,524287],"disallowed"],[[524288,589821],"disallowed"],[[589822,589823],"disallowed"],[[589824,655357],"disallowed"],[[655358,655359],"disallowed"],[[655360,720893],"disallowed"],[[720894,720895],"disallowed"],[[720896,786429],"disallowed"],[[786430,786431],"disallowed"],[[786432,851965],"disallowed"],[[851966,851967],"disallowed"],[[851968,917501],"disallowed"],[[917502,917503],"disallowed"],[[917504,917504],"disallowed"],[[917505,917505],"disallowed"],[[917506,917535],"disallowed"],[[917536,917631],"disallowed"],[[917632,917759],"disallowed"],[[917760,917999],"ignored"],[[918000,983037],"disallowed"],[[983038,983039],"disallowed"],[[983040,1048573],"disallowed"],[[1048574,1048575],"disallowed"],[[1048576,1114109],"disallowed"],[[1114110,1114111],"disallowed"]] \ No newline at end of file diff --git a/node_modules/tr46/package.json b/node_modules/tr46/package.json new file mode 100644 index 0000000..b6826da --- /dev/null +++ b/node_modules/tr46/package.json @@ -0,0 +1,31 @@ +{ + "name": "tr46", + "version": "0.0.3", + "description": "An implementation of the Unicode TR46 spec", + "main": "index.js", + "scripts": { + "test": "mocha", + "pretest": "node scripts/getLatestUnicodeTests.js", + "prepublish": "node scripts/generateMappingTable.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/Sebmaster/tr46.js.git" + }, + "keywords": [ + "unicode", + "tr46", + "url", + "whatwg" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "bugs": { + "url": "https://github.com/Sebmaster/tr46.js/issues" + }, + "homepage": "https://github.com/Sebmaster/tr46.js#readme", + "devDependencies": { + "mocha": "^2.2.5", + "request": "^2.57.0" + } +} diff --git a/node_modules/ts-mixer/CHANGELOG.md b/node_modules/ts-mixer/CHANGELOG.md new file mode 100644 index 0000000..2283377 --- /dev/null +++ b/node_modules/ts-mixer/CHANGELOG.md @@ -0,0 +1,113 @@ +# 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. + +### [6.0.3](https://github.com/tannerntannern/ts-mixer/compare/v6.0.2...v6.0.3) (2023-02-09) + + +### Bug Fixes + +* allow abstract constructor signature for hasMixin ([f82e27b](https://github.com/tannerntannern/ts-mixer/commit/f82e27b96d142cfdec6446930a1db354167e88d2)), closes [tannerntannern/ts-mixer#56](https://github.com/tannerntannern/ts-mixer/issues/56) +* allow abstract constructor signatures for hasMixin ([8964b59](https://github.com/tannerntannern/ts-mixer/commit/8964b59e062854fde52424497930ca3e8bb98e87)), closes [#57](https://github.com/tannerntannern/ts-mixer/issues/57) +* simplify signature ([8a79197](https://github.com/tannerntannern/ts-mixer/commit/8a79197cc6bca5757d7c06560d7b26e73491b11f)) + +### [6.0.2](https://github.com/tannerntannern/ts-mixer/compare/v6.0.1...v6.0.2) (2022-11-10) + + +### Bug Fixes + +* **decorators:** support class decorators that don't return anything ([7433cf3](https://github.com/tannerntannern/ts-mixer/commit/7433cf36a43bb18a1dd280aa629ac81ef532c74a)) + +### [6.0.1](https://github.com/tannerntannern/ts-mixer/compare/v6.0.0...v6.0.1) (2022-03-13) + +### Bug Fixes + +* fix bug in `directDecoratorSearch` ([51c50b8](https://github.com/tannerntannern/ts-mixer/commit/51c50b8c50a63e85b133bdd61eaad4427a22e515)) (thanks, [@AMcBain](https://github.com/AMcBain)!) + +## [6.0.0](https://github.com/tannerntannern/ts-mixer/compare/v6.0.0-beta.0...v6.0.0) (2021-07-07) + +## [6.0.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v5.4.1...v6.0.0-beta.0) (2021-06-24) + + +### ⚠ BREAKING CHANGES + +* drop TS < 4.2 support + +### Features + +* add abstract mixin support ([1c4b306](https://github.com/tannerntannern/ts-mixer/commit/1c4b306bae62fa6319c74d1f3040c8aba0da2c28)) + +### [5.4.1](https://github.com/tannerntannern/ts-mixer/compare/v5.4.0...v5.4.1) (2021-04-30) + + +### Bug Fixes + +* "publish" workflow ([bd2e4ec](https://github.com/tannerntannern/ts-mixer/commit/bd2e4ec088b19a403bc013926c7f3a2545cc4171)) +* circular dependency ([66f7e2d](https://github.com/tannerntannern/ts-mixer/commit/66f7e2dc929c90e8c15d718415114ceaa31402c2)) + +## [5.4.0](https://github.com/tannerntannern/ts-mixer/compare/v5.3.0...v5.4.0) (2020-11-18) + + +### Features + +* deep decorator inheritance ([6daabc5](https://github.com/tannerntannern/ts-mixer/commit/6daabc5d340d20c8eda4fe96b635a54f6a7e18fb)) + +## [5.3.0](https://github.com/tannerntannern/ts-mixer/compare/v5.3.0-beta.0...v5.3.0) (2020-06-01) + +## [5.3.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v5.2.1...v5.3.0-beta.0) (2020-05-31) + + +### Features + +* add hasMixin function ([#27](https://github.com/tannerntannern/ts-mixer/issues/27)) ([c8bfc2d](https://github.com/tannerntannern/ts-mixer/commit/c8bfc2d48854808755088332636e8d166007ed9f)) + +### [5.2.1](https://github.com/tannerntannern/ts-mixer/compare/v5.2.0...v5.2.1) (2020-05-08) + + +### Bug Fixes + +* mix decorator not preserving constructor name ([7274fa2](https://github.com/tannerntannern/ts-mixer/commit/7274fa26a68e05cc59cde1108610e6a1ab51b430)) + +## [5.2.0](https://github.com/tannerntannern/ts-mixer/compare/v5.2.0-beta.1...v5.2.0) (2020-04-29) + +## [5.2.0-beta.1](https://github.com/tannerntannern/ts-mixer/compare/v5.2.0-beta.0...v5.2.0-beta.1) (2020-04-23) + + +### Bug Fixes + +* wrong this in init functions for Mixin(A, Mixin(B, C)) scenario ([0ba1128](https://github.com/tannerntannern/ts-mixer/commit/0ba11283c63a878271b85c282f75190758101e63)) + +## [5.2.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v5.1.0...v5.2.0-beta.0) (2020-04-13) + + +### Features + +* adds init func feature for impure constructors ([99a946b](https://github.com/tannerntannern/ts-mixer/commit/99a946b8e272773f6bafd7a7e8bf8313517dec16)) + +## [5.1.0](https://github.com/tannerntannern/ts-mixer/compare/v5.1.0-beta.0...v5.1.0) (2020-03-27) + +## [5.1.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v5.0.0...v5.1.0-beta.0) (2020-03-26) + + +### Features + +* decorator support for class-validators, typeORM, etc ([2c14812](https://github.com/tannerntannern/ts-mixer/commit/2c1481237b325916ca95dbb9e33141b3220f8068)) + +## [5.0.0](https://github.com/tannerntannern/ts-mixer/compare/v5.0.0-beta.0...v5.0.0) (2020-03-01) + +## [5.0.0-beta.0](https://github.com/tannerntannern/ts-mixer/compare/v4.0.0...v5.0.0-beta.0) (2020-02-02) + + +### Features + +* adds and tests a nearestCommonAncestor function ([b084579](https://github.com/tannerntannern/ts-mixer/commit/b084579d5ac52e0b456be95ff6b776309b436473)) +* initial static inheritance implementation ([8467c40](https://github.com/tannerntannern/ts-mixer/commit/8467c40c9748e769eebf77b45cccad5ce785bac9)) +* initial version of proxyMix ([95a91c7](https://github.com/tannerntannern/ts-mixer/commit/95a91c78e5f05af75cfc95d82a65ce5b3413b9f1)) +* makes mixin constructor argument inference slightly smarter ([b844b5c](https://github.com/tannerntannern/ts-mixer/commit/b844b5c93f5eab0d6f522559ed567f67291fae76)) + + +### Bug Fixes + +* mixins with shared ancestor when using proxy prototype ([5af189d](https://github.com/tannerntannern/ts-mixer/commit/5af189d9903083f675f65b5039875c4aa97be1a6)) +* resolves indefinite tuple issue with `Longest` type ([68342b0](https://github.com/tannerntannern/ts-mixer/commit/68342b0a3fe224a485f220039af872050aa941fc)) +* static chain inheritance ([0aca8f0](https://github.com/tannerntannern/ts-mixer/commit/0aca8f056a005ccf27cc564d5a84abe1ef999d7b)) diff --git a/node_modules/ts-mixer/LICENSE b/node_modules/ts-mixer/LICENSE new file mode 100644 index 0000000..c8a6114 --- /dev/null +++ b/node_modules/ts-mixer/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Tanner Nielsen + +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/ts-mixer/README.md b/node_modules/ts-mixer/README.md new file mode 100644 index 0000000..b9e66bd --- /dev/null +++ b/node_modules/ts-mixer/README.md @@ -0,0 +1,270 @@ +# ts-mixer +[version-badge]: https://badgen.net/npm/v/ts-mixer +[version-link]: https://npmjs.com/package/ts-mixer +[build-link]: https://github.com/tannerntannern/ts-mixer/actions +[ts-versions]: https://badgen.net/badge/icon/4.2,4.4,4.6,4.8?icon=typescript&label&list=| +[node-versions]: https://badgen.net/badge/node/12%2C14%2C16%2C18/blue/?list=| +[![npm version][version-badge]][version-link] +[![TS Versions][ts-versions]][build-link] +[![Node.js Versions][node-versions]][build-link] +[![Minified Size](https://badgen.net/bundlephobia/min/ts-mixer)](https://bundlephobia.com/result?p=ts-mixer) +[![Conventional Commits](https://badgen.net/badge/conventional%20commits/1.0.0/yellow)](https://conventionalcommits.org) + +## Overview +`ts-mixer` brings mixins to TypeScript. "Mixins" to `ts-mixer` are just classes, so you already know how to write them, and you can probably mix classes from your favorite library without trouble. + +The mixin problem is more nuanced than it appears. I've seen countless code snippets that work for certain situations, but fail in others. `ts-mixer` tries to take the best from all these solutions while accounting for the situations you might not have considered. + +[Quick start guide](#quick-start) + +### Features +* mixes plain classes +* mixes classes that extend other classes +* mixes classes that were mixed with `ts-mixer` +* supports static properties +* supports protected/private properties (the popular function-that-returns-a-class solution does not) +* mixes abstract classes (requires TypeScript >= 4.2) +* mixes generic classes (with caveats [[1](#caveats)]) +* supports class, method, and property decorators (with caveats [[2, 5](#caveats)]) +* mostly supports the complexity presented by constructor functions (with caveats [[3](#caveats)]) +* comes with an `instanceof`-like replacement (with caveats [[4, 5](#caveats)]) +* [multiple mixing strategies](#settings) (ES6 proxies vs hard copy) + +### Caveats +1. Mixing generic classes requires a more cumbersome notation, but it's still possible. See [mixing generic classes](#mixing-generic-classes) below. +2. Using decorators in mixed classes also requires a more cumbersome notation. See [mixing with decorators](#mixing-with-decorators) below. +3. ES6 made it impossible to use `.apply(...)` on class constructors (or any means of calling them without `new`), which makes it impossible for `ts-mixer` to pass the proper `this` to your constructors. This may or may not be an issue for your code, but there are options to work around it. See [dealing with constructors](#dealing-with-constructors) below. +4. `ts-mixer` does not support `instanceof` for mixins, but it does offer a replacement. See the [hasMixin function](#hasmixin) for more details. +5. Certain features (specifically, `@decorator` and `hasMixin`) make use of ES6 `Map`s, which means you must either use ES6+ or polyfill `Map` to use them. If you don't need these features, you should be fine without. + +## Quick Start +### Installation +``` +$ npm install ts-mixer +``` + +or if you prefer [Yarn](https://yarnpkg.com): + +``` +$ yarn add ts-mixer +``` + +### Basic Example +```typescript +import { Mixin } from 'ts-mixer'; + +class Foo { + protected makeFoo() { + return 'foo'; + } +} + +class Bar { + protected makeBar() { + return 'bar'; + } +} + +class FooBar extends Mixin(Foo, Bar) { + public makeFooBar() { + return this.makeFoo() + this.makeBar(); + } +} + +const fooBar = new FooBar(); + +console.log(fooBar.makeFooBar()); // "foobar" +``` + +## Special Cases +### Mixing Generic Classes +Frustratingly, it is _impossible_ for generic parameters to be referenced in base class expressions. No matter what, you will eventually run into `Base class expressions cannot reference class type parameters.` + +The way to get around this is to leverage [declaration merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html), and a slightly different mixing function from ts-mixer: `mix`. It works exactly like `Mixin`, except it's a decorator, which means it doesn't affect the type information of the class being decorated. See it in action below: + +```typescript +import { mix } from 'ts-mixer'; + +class Foo { + public fooMethod(input: T): T { + return input; + } +} + +class Bar { + public barMethod(input: T): T { + return input; + } +} + +interface FooBar extends Foo, Bar { } +@mix(Foo, Bar) +class FooBar { + public fooBarMethod(input1: T1, input2: T2) { + return [this.fooMethod(input1), this.barMethod(input2)]; + } +} +``` + +Key takeaways from this example: +* `interface FooBar extends Foo, Bar { }` makes sure `FooBar` has the typing we want, thanks to declaration merging +* `@mix(Foo, Bar)` wires things up "on the JavaScript side", since the interface declaration has nothing to do with runtime behavior. +* The reason we have to use the `mix` decorator is that the typing produced by `Mixin(Foo, Bar)` would conflict with the typing of the interface. `mix` has no effect "on the TypeScript side," thus avoiding type conflicts. + +### Mixing with Decorators +Popular libraries such as [class-validator](https://github.com/typestack/class-validator) and [TypeORM](https://github.com/typeorm/typeorm) use decorators to add functionality. Unfortunately, `ts-mixer` has no way of knowing what these libraries do with the decorators behind the scenes. So if you want these decorators to be "inherited" with classes you plan to mix, you first have to wrap them with a special `decorate` function exported by `ts-mixer`. Here's an example using `class-validator`: + +```typescript +import { IsBoolean, IsIn, validate } from 'class-validator'; +import { Mixin, decorate } from 'ts-mixer'; + +class Disposable { + @decorate(IsBoolean()) // instead of @IsBoolean() + isDisposed: boolean = false; +} + +class Statusable { + @decorate(IsIn(['red', 'green'])) // instead of @IsIn(['red', 'green']) + status: string = 'green'; +} + +class ExtendedObject extends Mixin(Disposable, Statusable) {} + +const extendedObject = new ExtendedObject(); +extendedObject.status = 'blue'; + +validate(extendedObject).then(errors => { + console.log(errors); +}); +``` + +### Dealing with Constructors +As mentioned in the [caveats section](#caveats), ES6 disallowed calling constructor functions without `new`. This means that the only way for `ts-mixer` to mix instance properties is to instantiate each base class separately, then copy the instance properties into a common object. The consequence of this is that constructors mixed by `ts-mixer` will _not_ receive the proper `this`. + +**This very well may not be an issue for you!** It only means that your constructors need to be "mostly pure" in terms of how they handle `this`. Specifically, your constructors cannot produce [side effects](https://en.wikipedia.org/wiki/Side_effect_%28computer_science%29) involving `this`, _other than adding properties to `this`_ (the most common side effect in JavaScript constructors). + +If you simply cannot eliminate `this` side effects from your constructor, there is a workaround available: `ts-mixer` will automatically forward constructor parameters to a predesignated init function (`settings.initFunction`) if it's present on the class. Unlike constructors, functions can be called with an arbitrary `this`, so this predesignated init function _will_ have the proper `this`. Here's a basic example: + +```typescript +import { Mixin, settings } from 'ts-mixer'; + +settings.initFunction = 'init'; + +class Person { + public static allPeople: Set = new Set(); + + protected init() { + Person.allPeople.add(this); + } +} + +type PartyAffiliation = 'democrat' | 'republican'; + +class PoliticalParticipant { + public static democrats: Set = new Set(); + public static republicans: Set = new Set(); + + public party: PartyAffiliation; + + // note that these same args will also be passed to init function + public constructor(party: PartyAffiliation) { + this.party = party; + } + + protected init(party: PartyAffiliation) { + if (party === 'democrat') + PoliticalParticipant.democrats.add(this); + else + PoliticalParticipant.republicans.add(this); + } +} + +class Voter extends Mixin(Person, PoliticalParticipant) {} + +const v1 = new Voter('democrat'); +const v2 = new Voter('democrat'); +const v3 = new Voter('republican'); +const v4 = new Voter('republican'); +``` + +Note the above `.add(this)` statements. These would not work as expected if they were placed in the constructor instead, since `this` is not the same between the constructor and `init`, as explained above. + +## Other Features +### hasMixin +As mentioned above, `ts-mixer` does not support `instanceof` for mixins. While it is possible to implement [custom `instanceof` behavior](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance), this library does not do so because it would require modifying the source classes, which is deliberately avoided. + +You can fill this missing functionality with `hasMixin(instance, mixinClass)` instead. See the below example: + +```typescript +import { Mixin, hasMixin } from 'ts-mixer'; + +class Foo {} +class Bar {} +class FooBar extends Mixin(Foo, Bar) {} + +const instance = new FooBar(); + +// doesn't work with instanceof... +console.log(instance instanceof FooBar) // true +console.log(instance instanceof Foo) // false +console.log(instance instanceof Bar) // false + +// but everything works nicely with hasMixin! +console.log(hasMixin(instance, FooBar)) // true +console.log(hasMixin(instance, Foo)) // true +console.log(hasMixin(instance, Bar)) // true +``` + +`hasMixin(instance, mixinClass)` will work anywhere that `instance instanceof mixinClass` works. Additionally, like `instanceof`, you get the same [type narrowing benefits](https://www.typescriptlang.org/docs/handbook/advanced-types.html#instanceof-type-guards): + +```typescript +if (hasMixin(instance, Foo)) { + // inferred type of instance is "Foo" +} + +if (hasMixin(instance, Bar)) { + // inferred type of instance of "Bar" +} +``` + +## Settings +ts-mixer has multiple strategies for mixing classes which can be configured by modifying `settings` from ts-mixer. For example: + +```typescript +import { settings, Mixin } from 'ts-mixer'; + +settings.prototypeStrategy = 'proxy'; + +// then use `Mixin` as normal... +``` + +### `settings.prototypeStrategy` +* Determines how ts-mixer will mix class prototypes together +* Possible values: + - `'copy'` (default) - Copies all methods from the classes being mixed into a new prototype object. (This will include all methods up the prototype chains as well.) This is the default for ES5 compatibility, but it has the downside of stale references. For example, if you mix `Foo` and `Bar` to make `FooBar`, then redefine a method on `Foo`, `FooBar` will not have the latest methods from `Foo`. If this is not a concern for you, `'copy'` is the best value for this setting. + - `'proxy'` - Uses an ES6 Proxy to "soft mix" prototypes. Unlike `'copy'`, updates to the base classes _will_ be reflected in the mixed class, which may be desirable. The downside is that method access is not as performant, nor is it ES5 compatible. + +### `settings.staticsStrategy` +* Determines how static properties are inherited +* Possible values: + - `'copy'` (default) - Simply copies all properties (minus `prototype`) from the base classes/constructor functions onto the mixed class. Like `settings.prototypeStrategy = 'copy'`, this strategy also suffers from stale references, but shouldn't be a concern if you don't redefine static methods after mixing. + - `'proxy'` - Similar to `settings.prototypeStrategy`, proxy's static method access to base classes. Has the same benefits/downsides. + +### `settings.initFunction` +* If set, `ts-mixer` will automatically call the function with this name upon construction +* Possible values: + - `null` (default) - disables the behavior + - a string - function name to call upon construction +* Read more about why you would want this in [dealing with constructors](#dealing-with-constructors) + +### `settings.decoratorInheritance` +* Determines how decorators are inherited from classes passed to `Mixin(...)` +* Possible values: + - `'deep'` (default) - Deeply inherits decorators from all given classes and their ancestors + - `'direct'` - Only inherits decorators defined directly on the given classes + - `'none'` - Skips decorator inheritance + +# Author +Tanner Nielsen +* Website - [tannernielsen.com](http://tannernielsen.com) +* Github - [tannerntannern](https://github.com/tannerntannern) diff --git a/node_modules/ts-mixer/dist/cjs/decorator.js b/node_modules/ts-mixer/dist/cjs/decorator.js new file mode 100644 index 0000000..45d6dba --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/decorator.js @@ -0,0 +1,109 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decorate = exports.getDecoratorsForClass = exports.directDecoratorSearch = exports.deepDecoratorSearch = void 0; +const util_1 = require("./util"); +const mixin_tracking_1 = require("./mixin-tracking"); +const mergeObjectsOfDecorators = (o1, o2) => { + var _a, _b; + const allKeys = (0, util_1.unique)([...Object.getOwnPropertyNames(o1), ...Object.getOwnPropertyNames(o2)]); + const mergedObject = {}; + for (let key of allKeys) + mergedObject[key] = (0, util_1.unique)([...((_a = o1 === null || o1 === void 0 ? void 0 : o1[key]) !== null && _a !== void 0 ? _a : []), ...((_b = o2 === null || o2 === void 0 ? void 0 : o2[key]) !== null && _b !== void 0 ? _b : [])]); + return mergedObject; +}; +const mergePropertyAndMethodDecorators = (d1, d2) => { + var _a, _b, _c, _d; + return ({ + property: mergeObjectsOfDecorators((_a = d1 === null || d1 === void 0 ? void 0 : d1.property) !== null && _a !== void 0 ? _a : {}, (_b = d2 === null || d2 === void 0 ? void 0 : d2.property) !== null && _b !== void 0 ? _b : {}), + method: mergeObjectsOfDecorators((_c = d1 === null || d1 === void 0 ? void 0 : d1.method) !== null && _c !== void 0 ? _c : {}, (_d = d2 === null || d2 === void 0 ? void 0 : d2.method) !== null && _d !== void 0 ? _d : {}), + }); +}; +const mergeDecorators = (d1, d2) => { + var _a, _b, _c, _d, _e, _f; + return ({ + class: (0, util_1.unique)([...(_a = d1 === null || d1 === void 0 ? void 0 : d1.class) !== null && _a !== void 0 ? _a : [], ...(_b = d2 === null || d2 === void 0 ? void 0 : d2.class) !== null && _b !== void 0 ? _b : []]), + static: mergePropertyAndMethodDecorators((_c = d1 === null || d1 === void 0 ? void 0 : d1.static) !== null && _c !== void 0 ? _c : {}, (_d = d2 === null || d2 === void 0 ? void 0 : d2.static) !== null && _d !== void 0 ? _d : {}), + instance: mergePropertyAndMethodDecorators((_e = d1 === null || d1 === void 0 ? void 0 : d1.instance) !== null && _e !== void 0 ? _e : {}, (_f = d2 === null || d2 === void 0 ? void 0 : d2.instance) !== null && _f !== void 0 ? _f : {}), + }); +}; +const decorators = new Map(); +const findAllConstituentClasses = (...classes) => { + var _a; + const allClasses = new Set(); + const frontier = new Set([...classes]); + while (frontier.size > 0) { + for (let clazz of frontier) { + const protoChainClasses = (0, util_1.protoChain)(clazz.prototype).map(proto => proto.constructor); + const mixinClasses = (_a = (0, mixin_tracking_1.getMixinsForClass)(clazz)) !== null && _a !== void 0 ? _a : []; + const potentiallyNewClasses = [...protoChainClasses, ...mixinClasses]; + const newClasses = potentiallyNewClasses.filter(c => !allClasses.has(c)); + for (let newClass of newClasses) + frontier.add(newClass); + allClasses.add(clazz); + frontier.delete(clazz); + } + } + return [...allClasses]; +}; +const deepDecoratorSearch = (...classes) => { + const decoratorsForClassChain = findAllConstituentClasses(...classes) + .map(clazz => decorators.get(clazz)) + .filter(decorators => !!decorators); + if (decoratorsForClassChain.length == 0) + return {}; + if (decoratorsForClassChain.length == 1) + return decoratorsForClassChain[0]; + return decoratorsForClassChain.reduce((d1, d2) => mergeDecorators(d1, d2)); +}; +exports.deepDecoratorSearch = deepDecoratorSearch; +const directDecoratorSearch = (...classes) => { + const classDecorators = classes.map(clazz => (0, exports.getDecoratorsForClass)(clazz)); + if (classDecorators.length === 0) + return {}; + if (classDecorators.length === 1) + return classDecorators[0]; + return classDecorators.reduce((d1, d2) => mergeDecorators(d1, d2)); +}; +exports.directDecoratorSearch = directDecoratorSearch; +const getDecoratorsForClass = (clazz) => { + let decoratorsForClass = decorators.get(clazz); + if (!decoratorsForClass) { + decoratorsForClass = {}; + decorators.set(clazz, decoratorsForClass); + } + return decoratorsForClass; +}; +exports.getDecoratorsForClass = getDecoratorsForClass; +const decorateClass = (decorator) => ((clazz) => { + const decoratorsForClass = (0, exports.getDecoratorsForClass)(clazz); + let classDecorators = decoratorsForClass.class; + if (!classDecorators) { + classDecorators = []; + decoratorsForClass.class = classDecorators; + } + classDecorators.push(decorator); + return decorator(clazz); +}); +const decorateMember = (decorator) => ((object, key, ...otherArgs) => { + var _a, _b, _c; + const decoratorTargetType = typeof object === 'function' ? 'static' : 'instance'; + const decoratorType = typeof object[key] === 'function' ? 'method' : 'property'; + const clazz = decoratorTargetType === 'static' ? object : object.constructor; + const decoratorsForClass = (0, exports.getDecoratorsForClass)(clazz); + const decoratorsForTargetType = (_a = decoratorsForClass === null || decoratorsForClass === void 0 ? void 0 : decoratorsForClass[decoratorTargetType]) !== null && _a !== void 0 ? _a : {}; + decoratorsForClass[decoratorTargetType] = decoratorsForTargetType; + let decoratorsForType = (_b = decoratorsForTargetType === null || decoratorsForTargetType === void 0 ? void 0 : decoratorsForTargetType[decoratorType]) !== null && _b !== void 0 ? _b : {}; + decoratorsForTargetType[decoratorType] = decoratorsForType; + let decoratorsForKey = (_c = decoratorsForType === null || decoratorsForType === void 0 ? void 0 : decoratorsForType[key]) !== null && _c !== void 0 ? _c : []; + decoratorsForType[key] = decoratorsForKey; + // @ts-ignore: array is type `A[] | B[]` and item is type `A | B`, so technically a type error, but it's fine + decoratorsForKey.push(decorator); + // @ts-ignore + return decorator(object, key, ...otherArgs); +}); +const decorate = (decorator) => ((...args) => { + if (args.length === 1) + return decorateClass(decorator)(args[0]); + return decorateMember(decorator)(...args); +}); +exports.decorate = decorate; diff --git a/node_modules/ts-mixer/dist/cjs/index.js b/node_modules/ts-mixer/dist/cjs/index.js new file mode 100644 index 0000000..5702401 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/index.js @@ -0,0 +1,12 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasMixin = exports.decorate = exports.settings = exports.mix = exports.Mixin = void 0; +var mixins_1 = require("./mixins"); +Object.defineProperty(exports, "Mixin", { enumerable: true, get: function () { return mixins_1.Mixin; } }); +Object.defineProperty(exports, "mix", { enumerable: true, get: function () { return mixins_1.mix; } }); +var settings_1 = require("./settings"); +Object.defineProperty(exports, "settings", { enumerable: true, get: function () { return settings_1.settings; } }); +var decorator_1 = require("./decorator"); +Object.defineProperty(exports, "decorate", { enumerable: true, get: function () { return decorator_1.decorate; } }); +var mixin_tracking_1 = require("./mixin-tracking"); +Object.defineProperty(exports, "hasMixin", { enumerable: true, get: function () { return mixin_tracking_1.hasMixin; } }); diff --git a/node_modules/ts-mixer/dist/cjs/mixin-tracking.js b/node_modules/ts-mixer/dist/cjs/mixin-tracking.js new file mode 100644 index 0000000..33ac2e7 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/mixin-tracking.js @@ -0,0 +1,40 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasMixin = exports.registerMixins = exports.getMixinsForClass = void 0; +const util_1 = require("./util"); +// Keeps track of constituent classes for every mixin class created by ts-mixer. +const mixins = new Map(); +const getMixinsForClass = (clazz) => mixins.get(clazz); +exports.getMixinsForClass = getMixinsForClass; +const registerMixins = (mixedClass, constituents) => mixins.set(mixedClass, constituents); +exports.registerMixins = registerMixins; +const hasMixin = (instance, mixin) => { + if (instance instanceof mixin) + return true; + const constructor = instance.constructor; + const visited = new Set(); + let frontier = new Set(); + frontier.add(constructor); + while (frontier.size > 0) { + // check if the frontier has the mixin we're looking for. if not, we can say we visited every item in the frontier + if (frontier.has(mixin)) + return true; + frontier.forEach(item => visited.add(item)); + // build a new frontier based on the associated mixin classes and prototype chains of each frontier item + const newFrontier = new Set(); + frontier.forEach(item => { + var _a; + const itemConstituents = (_a = mixins.get(item)) !== null && _a !== void 0 ? _a : (0, util_1.protoChain)(item.prototype).map(proto => proto.constructor).filter(item => item !== null); + if (itemConstituents) + itemConstituents.forEach(constituent => { + if (!visited.has(constituent) && !frontier.has(constituent)) + newFrontier.add(constituent); + }); + }); + // we have a new frontier, now search again + frontier = newFrontier; + } + // if we get here, we couldn't find the mixin anywhere in the prototype chain or associated mixin classes + return false; +}; +exports.hasMixin = hasMixin; diff --git a/node_modules/ts-mixer/dist/cjs/mixins.js b/node_modules/ts-mixer/dist/cjs/mixins.js new file mode 100644 index 0000000..925e90a --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/mixins.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mix = exports.Mixin = void 0; +const proxy_1 = require("./proxy"); +const settings_1 = require("./settings"); +const util_1 = require("./util"); +const decorator_1 = require("./decorator"); +const mixin_tracking_1 = require("./mixin-tracking"); +function Mixin(...constructors) { + var _a, _b, _c; + const prototypes = constructors.map(constructor => constructor.prototype); + // Here we gather up the init functions of the ingredient prototypes, combine them into one init function, and + // attach it to the mixed class prototype. The reason we do this is because we want the init functions to mix + // similarly to constructors -- not methods, which simply override each other. + const initFunctionName = settings_1.settings.initFunction; + if (initFunctionName !== null) { + const initFunctions = prototypes + .map(proto => proto[initFunctionName]) + .filter(func => typeof func === 'function'); + const combinedInitFunction = function (...args) { + for (let initFunction of initFunctions) + initFunction.apply(this, args); + }; + const extraProto = { [initFunctionName]: combinedInitFunction }; + prototypes.push(extraProto); + } + function MixedClass(...args) { + for (const constructor of constructors) + // @ts-ignore: potentially abstract class + (0, util_1.copyProps)(this, new constructor(...args)); + if (initFunctionName !== null && typeof this[initFunctionName] === 'function') + this[initFunctionName].apply(this, args); + } + MixedClass.prototype = settings_1.settings.prototypeStrategy === 'copy' + ? (0, util_1.hardMixProtos)(prototypes, MixedClass) + : (0, proxy_1.softMixProtos)(prototypes, MixedClass); + Object.setPrototypeOf(MixedClass, settings_1.settings.staticsStrategy === 'copy' + ? (0, util_1.hardMixProtos)(constructors, null, ['prototype']) + : (0, proxy_1.proxyMix)(constructors, Function.prototype)); + let DecoratedMixedClass = MixedClass; + if (settings_1.settings.decoratorInheritance !== 'none') { + const classDecorators = settings_1.settings.decoratorInheritance === 'deep' + ? (0, decorator_1.deepDecoratorSearch)(...constructors) + : (0, decorator_1.directDecoratorSearch)(...constructors); + for (let decorator of (_a = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.class) !== null && _a !== void 0 ? _a : []) { + const result = decorator(DecoratedMixedClass); + if (result) { + DecoratedMixedClass = result; + } + } + applyPropAndMethodDecorators((_b = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.static) !== null && _b !== void 0 ? _b : {}, DecoratedMixedClass); + applyPropAndMethodDecorators((_c = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.instance) !== null && _c !== void 0 ? _c : {}, DecoratedMixedClass.prototype); + } + (0, mixin_tracking_1.registerMixins)(DecoratedMixedClass, constructors); + return DecoratedMixedClass; +} +exports.Mixin = Mixin; +const applyPropAndMethodDecorators = (propAndMethodDecorators, target) => { + const propDecorators = propAndMethodDecorators.property; + const methodDecorators = propAndMethodDecorators.method; + if (propDecorators) + for (let key in propDecorators) + for (let decorator of propDecorators[key]) + decorator(target, key); + if (methodDecorators) + for (let key in methodDecorators) + for (let decorator of methodDecorators[key]) + decorator(target, key, Object.getOwnPropertyDescriptor(target, key)); +}; +/** + * A decorator version of the `Mixin` function. You'll want to use this instead of `Mixin` for mixing generic classes. + */ +const mix = (...ingredients) => decoratedClass => { + // @ts-ignore + const mixedClass = Mixin(...ingredients.concat([decoratedClass])); + Object.defineProperty(mixedClass, 'name', { + value: decoratedClass.name, + writable: false, + }); + return mixedClass; +}; +exports.mix = mix; diff --git a/node_modules/ts-mixer/dist/cjs/proxy.js b/node_modules/ts-mixer/dist/cjs/proxy.js new file mode 100644 index 0000000..f7974c3 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/proxy.js @@ -0,0 +1,82 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.softMixProtos = exports.proxyMix = exports.getIngredientWithProp = void 0; +const util_1 = require("./util"); +/** + * Finds the ingredient with the given prop, searching in reverse order and breadth-first if searching ingredient + * prototypes is required. + */ +const getIngredientWithProp = (prop, ingredients) => { + const protoChains = ingredients.map(ingredient => (0, util_1.protoChain)(ingredient)); + // since we search breadth-first, we need to keep track of our depth in the prototype chains + let protoDepth = 0; + // not all prototype chains are the same depth, so this remains true as long as at least one of the ingredients' + // prototype chains has an object at this depth + let protosAreLeftToSearch = true; + while (protosAreLeftToSearch) { + // with the start of each horizontal slice, we assume this is the one that's deeper than any of the proto chains + protosAreLeftToSearch = false; + // scan through the ingredients right to left + for (let i = ingredients.length - 1; i >= 0; i--) { + const searchTarget = protoChains[i][protoDepth]; + if (searchTarget !== undefined && searchTarget !== null) { + // if we find something, this is proof that this horizontal slice potentially more objects to search + protosAreLeftToSearch = true; + // eureka, we found it + if (Object.getOwnPropertyDescriptor(searchTarget, prop) != undefined) { + return protoChains[i][0]; + } + } + } + protoDepth++; + } + return undefined; +}; +exports.getIngredientWithProp = getIngredientWithProp; +/** + * "Mixes" ingredients by wrapping them in a Proxy. The optional prototype argument allows the mixed object to sit + * downstream of an existing prototype chain. Note that "properties" cannot be added, deleted, or modified. + */ +const proxyMix = (ingredients, prototype = Object.prototype) => new Proxy({}, { + getPrototypeOf() { + return prototype; + }, + setPrototypeOf() { + throw Error('Cannot set prototype of Proxies created by ts-mixer'); + }, + getOwnPropertyDescriptor(_, prop) { + return Object.getOwnPropertyDescriptor((0, exports.getIngredientWithProp)(prop, ingredients) || {}, prop); + }, + defineProperty() { + throw new Error('Cannot define new properties on Proxies created by ts-mixer'); + }, + has(_, prop) { + return (0, exports.getIngredientWithProp)(prop, ingredients) !== undefined || prototype[prop] !== undefined; + }, + get(_, prop) { + return ((0, exports.getIngredientWithProp)(prop, ingredients) || prototype)[prop]; + }, + set(_, prop, val) { + const ingredientWithProp = (0, exports.getIngredientWithProp)(prop, ingredients); + if (ingredientWithProp === undefined) + throw new Error('Cannot set new properties on Proxies created by ts-mixer'); + ingredientWithProp[prop] = val; + return true; + }, + deleteProperty() { + throw new Error('Cannot delete properties on Proxies created by ts-mixer'); + }, + ownKeys() { + return ingredients + .map(Object.getOwnPropertyNames) + .reduce((prev, curr) => curr.concat(prev.filter(key => curr.indexOf(key) < 0))); + }, +}); +exports.proxyMix = proxyMix; +/** + * Creates a new proxy-prototype object that is a "soft" mixture of the given prototypes. The mixing is achieved by + * proxying all property access to the ingredients. This is not ES5 compatible and less performant. However, any + * changes made to the source prototypes will be reflected in the proxy-prototype, which may be desirable. + */ +const softMixProtos = (ingredients, constructor) => (0, exports.proxyMix)([...ingredients, { constructor }]); +exports.softMixProtos = softMixProtos; diff --git a/node_modules/ts-mixer/dist/cjs/settings.js b/node_modules/ts-mixer/dist/cjs/settings.js new file mode 100644 index 0000000..dabb6d3 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/settings.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.settings = void 0; +exports.settings = { + initFunction: null, + staticsStrategy: 'copy', + prototypeStrategy: 'copy', + decoratorInheritance: 'deep', +}; diff --git a/node_modules/ts-mixer/dist/cjs/types.js b/node_modules/ts-mixer/dist/cjs/types.js new file mode 100644 index 0000000..c8ad2e5 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/types.js @@ -0,0 +1,2 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/node_modules/ts-mixer/dist/cjs/util.js b/node_modules/ts-mixer/dist/cjs/util.js new file mode 100644 index 0000000..5151696 --- /dev/null +++ b/node_modules/ts-mixer/dist/cjs/util.js @@ -0,0 +1,85 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.flatten = exports.unique = exports.hardMixProtos = exports.nearestCommonProto = exports.protoChain = exports.copyProps = void 0; +/** + * Utility function that works like `Object.apply`, but copies getters and setters properly as well. Additionally gives + * the option to exclude properties by name. + */ +const copyProps = (dest, src, exclude = []) => { + const props = Object.getOwnPropertyDescriptors(src); + for (let prop of exclude) + delete props[prop]; + Object.defineProperties(dest, props); +}; +exports.copyProps = copyProps; +/** + * Returns the full chain of prototypes up until Object.prototype given a starting object. The order of prototypes will + * be closest to farthest in the chain. + */ +const protoChain = (obj, currentChain = [obj]) => { + const proto = Object.getPrototypeOf(obj); + if (proto === null) + return currentChain; + return (0, exports.protoChain)(proto, [...currentChain, proto]); +}; +exports.protoChain = protoChain; +/** + * Identifies the nearest ancestor common to all the given objects in their prototype chains. For most unrelated + * objects, this function should return Object.prototype. + */ +const nearestCommonProto = (...objs) => { + if (objs.length === 0) + return undefined; + let commonProto = undefined; + const protoChains = objs.map(obj => (0, exports.protoChain)(obj)); + while (protoChains.every(protoChain => protoChain.length > 0)) { + const protos = protoChains.map(protoChain => protoChain.pop()); + const potentialCommonProto = protos[0]; + if (protos.every(proto => proto === potentialCommonProto)) + commonProto = potentialCommonProto; + else + break; + } + return commonProto; +}; +exports.nearestCommonProto = nearestCommonProto; +/** + * Creates a new prototype object that is a mixture of the given prototypes. The mixing is achieved by first + * identifying the nearest common ancestor and using it as the prototype for a new object. Then all properties/methods + * downstream of this prototype (ONLY downstream) are copied into the new object. + * + * The resulting prototype is more performant than softMixProtos(...), as well as ES5 compatible. However, it's not as + * flexible as updates to the source prototypes aren't captured by the mixed result. See softMixProtos for why you may + * want to use that instead. + */ +const hardMixProtos = (ingredients, constructor, exclude = []) => { + var _a; + const base = (_a = (0, exports.nearestCommonProto)(...ingredients)) !== null && _a !== void 0 ? _a : Object.prototype; + const mixedProto = Object.create(base); + // Keeps track of prototypes we've already visited to avoid copying the same properties multiple times. We init the + // list with the proto chain below the nearest common ancestor because we don't want any of those methods mixed in + // when they will already be accessible via prototype access. + const visitedProtos = (0, exports.protoChain)(base); + for (let prototype of ingredients) { + let protos = (0, exports.protoChain)(prototype); + // Apply the prototype chain in reverse order so that old methods don't override newer ones. + for (let i = protos.length - 1; i >= 0; i--) { + let newProto = protos[i]; + if (visitedProtos.indexOf(newProto) === -1) { + (0, exports.copyProps)(mixedProto, newProto, ['constructor', ...exclude]); + visitedProtos.push(newProto); + } + } + } + mixedProto.constructor = constructor; + return mixedProto; +}; +exports.hardMixProtos = hardMixProtos; +const unique = (arr) => arr.filter((e, i) => arr.indexOf(e) == i); +exports.unique = unique; +const flatten = (arr) => arr.length === 0 + ? [] + : arr.length === 1 + ? arr[0] + : arr.reduce((a1, a2) => [...a1, ...a2]); +exports.flatten = flatten; diff --git a/node_modules/ts-mixer/dist/esm/decorator.d.ts b/node_modules/ts-mixer/dist/esm/decorator.d.ts new file mode 100644 index 0000000..dde5df2 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/decorator.d.ts @@ -0,0 +1,18 @@ +import { Class } from './types'; +type ObjectOfDecorators = { + [key: string]: T[]; +}; +export type PropertyAndMethodDecorators = { + property?: ObjectOfDecorators; + method?: ObjectOfDecorators; +}; +type Decorators = { + class?: ClassDecorator[]; + static?: PropertyAndMethodDecorators; + instance?: PropertyAndMethodDecorators; +}; +export declare const deepDecoratorSearch: (...classes: Class[]) => Decorators; +export declare const directDecoratorSearch: (...classes: Class[]) => Decorators; +export declare const getDecoratorsForClass: (clazz: Class) => Decorators; +export declare const decorate: (decorator: T) => T; +export {}; diff --git a/node_modules/ts-mixer/dist/esm/index.d.ts b/node_modules/ts-mixer/dist/esm/index.d.ts new file mode 100644 index 0000000..2a16080 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/index.d.ts @@ -0,0 +1,4 @@ +export { Mixin, mix } from './mixins'; +export { settings } from './settings'; +export { decorate } from './decorator'; +export { hasMixin } from './mixin-tracking'; diff --git a/node_modules/ts-mixer/dist/esm/index.js b/node_modules/ts-mixer/dist/esm/index.js new file mode 100644 index 0000000..991d21b --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/index.js @@ -0,0 +1,364 @@ +/** + * Utility function that works like `Object.apply`, but copies getters and setters properly as well. Additionally gives + * the option to exclude properties by name. + */ +const copyProps = (dest, src, exclude = []) => { + const props = Object.getOwnPropertyDescriptors(src); + for (let prop of exclude) + delete props[prop]; + Object.defineProperties(dest, props); +}; +/** + * Returns the full chain of prototypes up until Object.prototype given a starting object. The order of prototypes will + * be closest to farthest in the chain. + */ +const protoChain = (obj, currentChain = [obj]) => { + const proto = Object.getPrototypeOf(obj); + if (proto === null) + return currentChain; + return protoChain(proto, [...currentChain, proto]); +}; +/** + * Identifies the nearest ancestor common to all the given objects in their prototype chains. For most unrelated + * objects, this function should return Object.prototype. + */ +const nearestCommonProto = (...objs) => { + if (objs.length === 0) + return undefined; + let commonProto = undefined; + const protoChains = objs.map(obj => protoChain(obj)); + while (protoChains.every(protoChain => protoChain.length > 0)) { + const protos = protoChains.map(protoChain => protoChain.pop()); + const potentialCommonProto = protos[0]; + if (protos.every(proto => proto === potentialCommonProto)) + commonProto = potentialCommonProto; + else + break; + } + return commonProto; +}; +/** + * Creates a new prototype object that is a mixture of the given prototypes. The mixing is achieved by first + * identifying the nearest common ancestor and using it as the prototype for a new object. Then all properties/methods + * downstream of this prototype (ONLY downstream) are copied into the new object. + * + * The resulting prototype is more performant than softMixProtos(...), as well as ES5 compatible. However, it's not as + * flexible as updates to the source prototypes aren't captured by the mixed result. See softMixProtos for why you may + * want to use that instead. + */ +const hardMixProtos = (ingredients, constructor, exclude = []) => { + var _a; + const base = (_a = nearestCommonProto(...ingredients)) !== null && _a !== void 0 ? _a : Object.prototype; + const mixedProto = Object.create(base); + // Keeps track of prototypes we've already visited to avoid copying the same properties multiple times. We init the + // list with the proto chain below the nearest common ancestor because we don't want any of those methods mixed in + // when they will already be accessible via prototype access. + const visitedProtos = protoChain(base); + for (let prototype of ingredients) { + let protos = protoChain(prototype); + // Apply the prototype chain in reverse order so that old methods don't override newer ones. + for (let i = protos.length - 1; i >= 0; i--) { + let newProto = protos[i]; + if (visitedProtos.indexOf(newProto) === -1) { + copyProps(mixedProto, newProto, ['constructor', ...exclude]); + visitedProtos.push(newProto); + } + } + } + mixedProto.constructor = constructor; + return mixedProto; +}; +const unique = (arr) => arr.filter((e, i) => arr.indexOf(e) == i); + +/** + * Finds the ingredient with the given prop, searching in reverse order and breadth-first if searching ingredient + * prototypes is required. + */ +const getIngredientWithProp = (prop, ingredients) => { + const protoChains = ingredients.map(ingredient => protoChain(ingredient)); + // since we search breadth-first, we need to keep track of our depth in the prototype chains + let protoDepth = 0; + // not all prototype chains are the same depth, so this remains true as long as at least one of the ingredients' + // prototype chains has an object at this depth + let protosAreLeftToSearch = true; + while (protosAreLeftToSearch) { + // with the start of each horizontal slice, we assume this is the one that's deeper than any of the proto chains + protosAreLeftToSearch = false; + // scan through the ingredients right to left + for (let i = ingredients.length - 1; i >= 0; i--) { + const searchTarget = protoChains[i][protoDepth]; + if (searchTarget !== undefined && searchTarget !== null) { + // if we find something, this is proof that this horizontal slice potentially more objects to search + protosAreLeftToSearch = true; + // eureka, we found it + if (Object.getOwnPropertyDescriptor(searchTarget, prop) != undefined) { + return protoChains[i][0]; + } + } + } + protoDepth++; + } + return undefined; +}; +/** + * "Mixes" ingredients by wrapping them in a Proxy. The optional prototype argument allows the mixed object to sit + * downstream of an existing prototype chain. Note that "properties" cannot be added, deleted, or modified. + */ +const proxyMix = (ingredients, prototype = Object.prototype) => new Proxy({}, { + getPrototypeOf() { + return prototype; + }, + setPrototypeOf() { + throw Error('Cannot set prototype of Proxies created by ts-mixer'); + }, + getOwnPropertyDescriptor(_, prop) { + return Object.getOwnPropertyDescriptor(getIngredientWithProp(prop, ingredients) || {}, prop); + }, + defineProperty() { + throw new Error('Cannot define new properties on Proxies created by ts-mixer'); + }, + has(_, prop) { + return getIngredientWithProp(prop, ingredients) !== undefined || prototype[prop] !== undefined; + }, + get(_, prop) { + return (getIngredientWithProp(prop, ingredients) || prototype)[prop]; + }, + set(_, prop, val) { + const ingredientWithProp = getIngredientWithProp(prop, ingredients); + if (ingredientWithProp === undefined) + throw new Error('Cannot set new properties on Proxies created by ts-mixer'); + ingredientWithProp[prop] = val; + return true; + }, + deleteProperty() { + throw new Error('Cannot delete properties on Proxies created by ts-mixer'); + }, + ownKeys() { + return ingredients + .map(Object.getOwnPropertyNames) + .reduce((prev, curr) => curr.concat(prev.filter(key => curr.indexOf(key) < 0))); + }, +}); +/** + * Creates a new proxy-prototype object that is a "soft" mixture of the given prototypes. The mixing is achieved by + * proxying all property access to the ingredients. This is not ES5 compatible and less performant. However, any + * changes made to the source prototypes will be reflected in the proxy-prototype, which may be desirable. + */ +const softMixProtos = (ingredients, constructor) => proxyMix([...ingredients, { constructor }]); + +const settings = { + initFunction: null, + staticsStrategy: 'copy', + prototypeStrategy: 'copy', + decoratorInheritance: 'deep', +}; + +// Keeps track of constituent classes for every mixin class created by ts-mixer. +const mixins = new Map(); +const getMixinsForClass = (clazz) => mixins.get(clazz); +const registerMixins = (mixedClass, constituents) => mixins.set(mixedClass, constituents); +const hasMixin = (instance, mixin) => { + if (instance instanceof mixin) + return true; + const constructor = instance.constructor; + const visited = new Set(); + let frontier = new Set(); + frontier.add(constructor); + while (frontier.size > 0) { + // check if the frontier has the mixin we're looking for. if not, we can say we visited every item in the frontier + if (frontier.has(mixin)) + return true; + frontier.forEach(item => visited.add(item)); + // build a new frontier based on the associated mixin classes and prototype chains of each frontier item + const newFrontier = new Set(); + frontier.forEach(item => { + var _a; + const itemConstituents = (_a = mixins.get(item)) !== null && _a !== void 0 ? _a : protoChain(item.prototype).map(proto => proto.constructor).filter(item => item !== null); + if (itemConstituents) + itemConstituents.forEach(constituent => { + if (!visited.has(constituent) && !frontier.has(constituent)) + newFrontier.add(constituent); + }); + }); + // we have a new frontier, now search again + frontier = newFrontier; + } + // if we get here, we couldn't find the mixin anywhere in the prototype chain or associated mixin classes + return false; +}; + +const mergeObjectsOfDecorators = (o1, o2) => { + var _a, _b; + const allKeys = unique([...Object.getOwnPropertyNames(o1), ...Object.getOwnPropertyNames(o2)]); + const mergedObject = {}; + for (let key of allKeys) + mergedObject[key] = unique([...((_a = o1 === null || o1 === void 0 ? void 0 : o1[key]) !== null && _a !== void 0 ? _a : []), ...((_b = o2 === null || o2 === void 0 ? void 0 : o2[key]) !== null && _b !== void 0 ? _b : [])]); + return mergedObject; +}; +const mergePropertyAndMethodDecorators = (d1, d2) => { + var _a, _b, _c, _d; + return ({ + property: mergeObjectsOfDecorators((_a = d1 === null || d1 === void 0 ? void 0 : d1.property) !== null && _a !== void 0 ? _a : {}, (_b = d2 === null || d2 === void 0 ? void 0 : d2.property) !== null && _b !== void 0 ? _b : {}), + method: mergeObjectsOfDecorators((_c = d1 === null || d1 === void 0 ? void 0 : d1.method) !== null && _c !== void 0 ? _c : {}, (_d = d2 === null || d2 === void 0 ? void 0 : d2.method) !== null && _d !== void 0 ? _d : {}), + }); +}; +const mergeDecorators = (d1, d2) => { + var _a, _b, _c, _d, _e, _f; + return ({ + class: unique([...(_a = d1 === null || d1 === void 0 ? void 0 : d1.class) !== null && _a !== void 0 ? _a : [], ...(_b = d2 === null || d2 === void 0 ? void 0 : d2.class) !== null && _b !== void 0 ? _b : []]), + static: mergePropertyAndMethodDecorators((_c = d1 === null || d1 === void 0 ? void 0 : d1.static) !== null && _c !== void 0 ? _c : {}, (_d = d2 === null || d2 === void 0 ? void 0 : d2.static) !== null && _d !== void 0 ? _d : {}), + instance: mergePropertyAndMethodDecorators((_e = d1 === null || d1 === void 0 ? void 0 : d1.instance) !== null && _e !== void 0 ? _e : {}, (_f = d2 === null || d2 === void 0 ? void 0 : d2.instance) !== null && _f !== void 0 ? _f : {}), + }); +}; +const decorators = new Map(); +const findAllConstituentClasses = (...classes) => { + var _a; + const allClasses = new Set(); + const frontier = new Set([...classes]); + while (frontier.size > 0) { + for (let clazz of frontier) { + const protoChainClasses = protoChain(clazz.prototype).map(proto => proto.constructor); + const mixinClasses = (_a = getMixinsForClass(clazz)) !== null && _a !== void 0 ? _a : []; + const potentiallyNewClasses = [...protoChainClasses, ...mixinClasses]; + const newClasses = potentiallyNewClasses.filter(c => !allClasses.has(c)); + for (let newClass of newClasses) + frontier.add(newClass); + allClasses.add(clazz); + frontier.delete(clazz); + } + } + return [...allClasses]; +}; +const deepDecoratorSearch = (...classes) => { + const decoratorsForClassChain = findAllConstituentClasses(...classes) + .map(clazz => decorators.get(clazz)) + .filter(decorators => !!decorators); + if (decoratorsForClassChain.length == 0) + return {}; + if (decoratorsForClassChain.length == 1) + return decoratorsForClassChain[0]; + return decoratorsForClassChain.reduce((d1, d2) => mergeDecorators(d1, d2)); +}; +const directDecoratorSearch = (...classes) => { + const classDecorators = classes.map(clazz => getDecoratorsForClass(clazz)); + if (classDecorators.length === 0) + return {}; + if (classDecorators.length === 1) + return classDecorators[0]; + return classDecorators.reduce((d1, d2) => mergeDecorators(d1, d2)); +}; +const getDecoratorsForClass = (clazz) => { + let decoratorsForClass = decorators.get(clazz); + if (!decoratorsForClass) { + decoratorsForClass = {}; + decorators.set(clazz, decoratorsForClass); + } + return decoratorsForClass; +}; +const decorateClass = (decorator) => ((clazz) => { + const decoratorsForClass = getDecoratorsForClass(clazz); + let classDecorators = decoratorsForClass.class; + if (!classDecorators) { + classDecorators = []; + decoratorsForClass.class = classDecorators; + } + classDecorators.push(decorator); + return decorator(clazz); +}); +const decorateMember = (decorator) => ((object, key, ...otherArgs) => { + var _a, _b, _c; + const decoratorTargetType = typeof object === 'function' ? 'static' : 'instance'; + const decoratorType = typeof object[key] === 'function' ? 'method' : 'property'; + const clazz = decoratorTargetType === 'static' ? object : object.constructor; + const decoratorsForClass = getDecoratorsForClass(clazz); + const decoratorsForTargetType = (_a = decoratorsForClass === null || decoratorsForClass === void 0 ? void 0 : decoratorsForClass[decoratorTargetType]) !== null && _a !== void 0 ? _a : {}; + decoratorsForClass[decoratorTargetType] = decoratorsForTargetType; + let decoratorsForType = (_b = decoratorsForTargetType === null || decoratorsForTargetType === void 0 ? void 0 : decoratorsForTargetType[decoratorType]) !== null && _b !== void 0 ? _b : {}; + decoratorsForTargetType[decoratorType] = decoratorsForType; + let decoratorsForKey = (_c = decoratorsForType === null || decoratorsForType === void 0 ? void 0 : decoratorsForType[key]) !== null && _c !== void 0 ? _c : []; + decoratorsForType[key] = decoratorsForKey; + // @ts-ignore: array is type `A[] | B[]` and item is type `A | B`, so technically a type error, but it's fine + decoratorsForKey.push(decorator); + // @ts-ignore + return decorator(object, key, ...otherArgs); +}); +const decorate = (decorator) => ((...args) => { + if (args.length === 1) + return decorateClass(decorator)(args[0]); + return decorateMember(decorator)(...args); +}); + +function Mixin(...constructors) { + var _a, _b, _c; + const prototypes = constructors.map(constructor => constructor.prototype); + // Here we gather up the init functions of the ingredient prototypes, combine them into one init function, and + // attach it to the mixed class prototype. The reason we do this is because we want the init functions to mix + // similarly to constructors -- not methods, which simply override each other. + const initFunctionName = settings.initFunction; + if (initFunctionName !== null) { + const initFunctions = prototypes + .map(proto => proto[initFunctionName]) + .filter(func => typeof func === 'function'); + const combinedInitFunction = function (...args) { + for (let initFunction of initFunctions) + initFunction.apply(this, args); + }; + const extraProto = { [initFunctionName]: combinedInitFunction }; + prototypes.push(extraProto); + } + function MixedClass(...args) { + for (const constructor of constructors) + // @ts-ignore: potentially abstract class + copyProps(this, new constructor(...args)); + if (initFunctionName !== null && typeof this[initFunctionName] === 'function') + this[initFunctionName].apply(this, args); + } + MixedClass.prototype = settings.prototypeStrategy === 'copy' + ? hardMixProtos(prototypes, MixedClass) + : softMixProtos(prototypes, MixedClass); + Object.setPrototypeOf(MixedClass, settings.staticsStrategy === 'copy' + ? hardMixProtos(constructors, null, ['prototype']) + : proxyMix(constructors, Function.prototype)); + let DecoratedMixedClass = MixedClass; + if (settings.decoratorInheritance !== 'none') { + const classDecorators = settings.decoratorInheritance === 'deep' + ? deepDecoratorSearch(...constructors) + : directDecoratorSearch(...constructors); + for (let decorator of (_a = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.class) !== null && _a !== void 0 ? _a : []) { + const result = decorator(DecoratedMixedClass); + if (result) { + DecoratedMixedClass = result; + } + } + applyPropAndMethodDecorators((_b = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.static) !== null && _b !== void 0 ? _b : {}, DecoratedMixedClass); + applyPropAndMethodDecorators((_c = classDecorators === null || classDecorators === void 0 ? void 0 : classDecorators.instance) !== null && _c !== void 0 ? _c : {}, DecoratedMixedClass.prototype); + } + registerMixins(DecoratedMixedClass, constructors); + return DecoratedMixedClass; +} +const applyPropAndMethodDecorators = (propAndMethodDecorators, target) => { + const propDecorators = propAndMethodDecorators.property; + const methodDecorators = propAndMethodDecorators.method; + if (propDecorators) + for (let key in propDecorators) + for (let decorator of propDecorators[key]) + decorator(target, key); + if (methodDecorators) + for (let key in methodDecorators) + for (let decorator of methodDecorators[key]) + decorator(target, key, Object.getOwnPropertyDescriptor(target, key)); +}; +/** + * A decorator version of the `Mixin` function. You'll want to use this instead of `Mixin` for mixing generic classes. + */ +const mix = (...ingredients) => decoratedClass => { + // @ts-ignore + const mixedClass = Mixin(...ingredients.concat([decoratedClass])); + Object.defineProperty(mixedClass, 'name', { + value: decoratedClass.name, + writable: false, + }); + return mixedClass; +}; + +export { Mixin, decorate, hasMixin, mix, settings }; diff --git a/node_modules/ts-mixer/dist/esm/index.min.js b/node_modules/ts-mixer/dist/esm/index.min.js new file mode 100644 index 0000000..04ab5ba --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/index.min.js @@ -0,0 +1 @@ +const t=(t,e,o=[])=>{const r=Object.getOwnPropertyDescriptors(e);for(let t of o)delete r[t];Object.defineProperties(t,r)},e=(t,o=[t])=>{const r=Object.getPrototypeOf(t);return null===r?o:e(r,[...o,r])},o=(o,r,n=[])=>{var l;const i=null!==(l=((...t)=>{if(0===t.length)return;let o;const r=t.map((t=>e(t)));for(;r.every((t=>t.length>0));){const t=r.map((t=>t.pop())),e=t[0];if(!t.every((t=>t===e)))break;o=e}return o})(...o))&&void 0!==l?l:Object.prototype,c=Object.create(i),s=e(i);for(let r of o){let o=e(r);for(let e=o.length-1;e>=0;e--){let r=o[e];-1===s.indexOf(r)&&(t(c,r,["constructor",...n]),s.push(r))}}return c.constructor=r,c},r=t=>t.filter(((e,o)=>t.indexOf(e)==o)),n=(t,o)=>{const r=o.map((t=>e(t)));let n=0,l=!0;for(;l;){l=!1;for(let e=o.length-1;e>=0;e--){const o=r[e][n];if(null!=o&&(l=!0,null!=Object.getOwnPropertyDescriptor(o,t)))return r[e][0]}n++}},l=(t,e=Object.prototype)=>new Proxy({},{getPrototypeOf:()=>e,setPrototypeOf(){throw Error("Cannot set prototype of Proxies created by ts-mixer")},getOwnPropertyDescriptor:(e,o)=>Object.getOwnPropertyDescriptor(n(o,t)||{},o),defineProperty(){throw new Error("Cannot define new properties on Proxies created by ts-mixer")},has:(o,r)=>void 0!==n(r,t)||void 0!==e[r],get:(o,r)=>(n(r,t)||e)[r],set(e,o,r){const l=n(o,t);if(void 0===l)throw new Error("Cannot set new properties on Proxies created by ts-mixer");return l[o]=r,!0},deleteProperty(){throw new Error("Cannot delete properties on Proxies created by ts-mixer")},ownKeys:()=>t.map(Object.getOwnPropertyNames).reduce(((t,e)=>e.concat(t.filter((t=>e.indexOf(t)<0)))))}),i={initFunction:null,staticsStrategy:"copy",prototypeStrategy:"copy",decoratorInheritance:"deep"},c=new Map,s=t=>c.get(t),p=(t,o)=>{if(t instanceof o)return!0;const r=t.constructor,n=new Set;let l=new Set;for(l.add(r);l.size>0;){if(l.has(o))return!0;l.forEach((t=>n.add(t)));const t=new Set;l.forEach((o=>{var r;const i=null!==(r=c.get(o))&&void 0!==r?r:e(o.prototype).map((t=>t.constructor)).filter((t=>null!==t));i&&i.forEach((e=>{n.has(e)||l.has(e)||t.add(e)}))})),l=t}return!1},u=(t,e)=>{var o,n;const l=r([...Object.getOwnPropertyNames(t),...Object.getOwnPropertyNames(e)]),i={};for(let c of l)i[c]=r([...null!==(o=null==t?void 0:t[c])&&void 0!==o?o:[],...null!==(n=null==e?void 0:e[c])&&void 0!==n?n:[]]);return i},a=(t,e)=>{var o,r,n,l;return{property:u(null!==(o=null==t?void 0:t.property)&&void 0!==o?o:{},null!==(r=null==e?void 0:e.property)&&void 0!==r?r:{}),method:u(null!==(n=null==t?void 0:t.method)&&void 0!==n?n:{},null!==(l=null==e?void 0:e.method)&&void 0!==l?l:{})}},d=(t,e)=>{var o,n,l,i,c,s;return{class:r([...null!==(o=null==t?void 0:t.class)&&void 0!==o?o:[],...null!==(n=null==e?void 0:e.class)&&void 0!==n?n:[]]),static:a(null!==(l=null==t?void 0:t.static)&&void 0!==l?l:{},null!==(i=null==e?void 0:e.static)&&void 0!==i?i:{}),instance:a(null!==(c=null==t?void 0:t.instance)&&void 0!==c?c:{},null!==(s=null==e?void 0:e.instance)&&void 0!==s?s:{})}},f=new Map,v=(...t)=>{const o=((...t)=>{var o;const r=new Set,n=new Set([...t]);for(;n.size>0;)for(let t of n){const l=[...e(t.prototype).map((t=>t.constructor)),...null!==(o=s(t))&&void 0!==o?o:[]].filter((t=>!r.has(t)));for(let t of l)n.add(t);r.add(t),n.delete(t)}return[...r]})(...t).map((t=>f.get(t))).filter((t=>!!t));return 0==o.length?{}:1==o.length?o[0]:o.reduce(((t,e)=>d(t,e)))},y=t=>{let e=f.get(t);return e||(e={},f.set(t,e)),e},h=t=>(...e)=>1===e.length?(t=>e=>{const o=y(e);let r=o.class;return r||(r=[],o.class=r),r.push(t),t(e)})(t)(e[0]):(t=>(e,o,...r)=>{var n,l,i;const c="function"==typeof e?"static":"instance",s="function"==typeof e[o]?"method":"property",p="static"===c?e:e.constructor,u=y(p),a=null!==(n=null==u?void 0:u[c])&&void 0!==n?n:{};u[c]=a;let d=null!==(l=null==a?void 0:a[s])&&void 0!==l?l:{};a[s]=d;let f=null!==(i=null==d?void 0:d[o])&&void 0!==i?i:[];return d[o]=f,f.push(t),t(e,o,...r)})(t)(...e);function O(...e){var r,n,s;const p=e.map((t=>t.prototype)),u=i.initFunction;if(null!==u){const t=p.map((t=>t[u])).filter((t=>"function"==typeof t)),e={[u]:function(...e){for(let o of t)o.apply(this,e)}};p.push(e)}function a(...o){for(const r of e)t(this,new r(...o));null!==u&&"function"==typeof this[u]&&this[u].apply(this,o)}var f,h;a.prototype="copy"===i.prototypeStrategy?o(p,a):(f=p,h=a,l([...f,{constructor:h}])),Object.setPrototypeOf(a,"copy"===i.staticsStrategy?o(e,null,["prototype"]):l(e,Function.prototype));let O=a;if("none"!==i.decoratorInheritance){const t="deep"===i.decoratorInheritance?v(...e):((...t)=>{const e=t.map((t=>y(t)));return 0===e.length?{}:1===e.length?e[0]:e.reduce(((t,e)=>d(t,e)))})(...e);for(let e of null!==(r=null==t?void 0:t.class)&&void 0!==r?r:[]){const t=e(O);t&&(O=t)}g(null!==(n=null==t?void 0:t.static)&&void 0!==n?n:{},O),g(null!==(s=null==t?void 0:t.instance)&&void 0!==s?s:{},O.prototype)}var w,m;return w=O,m=e,c.set(w,m),O}const g=(t,e)=>{const o=t.property,r=t.method;if(o)for(let t in o)for(let r of o[t])r(e,t);if(r)for(let t in r)for(let o of r[t])o(e,t,Object.getOwnPropertyDescriptor(e,t))},w=(...t)=>e=>{const o=O(...t.concat([e]));return Object.defineProperty(o,"name",{value:e.name,writable:!1}),o};export{O as Mixin,h as decorate,p as hasMixin,w as mix,i as settings}; diff --git a/node_modules/ts-mixer/dist/esm/mixin-tracking.d.ts b/node_modules/ts-mixer/dist/esm/mixin-tracking.d.ts new file mode 100644 index 0000000..1beaf87 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/mixin-tracking.d.ts @@ -0,0 +1,4 @@ +import { Class } from './types'; +export declare const getMixinsForClass: (clazz: Class) => Function[] | undefined; +export declare const registerMixins: (mixedClass: any, constituents: Function[]) => Map; +export declare const hasMixin: (instance: any, mixin: abstract new (...args: any[]) => M) => instance is M; diff --git a/node_modules/ts-mixer/dist/esm/mixins.d.ts b/node_modules/ts-mixer/dist/esm/mixins.d.ts new file mode 100644 index 0000000..a4f65be --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/mixins.d.ts @@ -0,0 +1,16 @@ +import { Class, Longest } from './types'; +declare function Mixin(c1: Class): Class; +declare function Mixin(c1: Class, c2: Class): Class, I1 & I2, S1 & S2>; +declare function Mixin(c1: Class, c2: Class, c3: Class): Class, I1 & I2 & I3, S1 & S2 & S3>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class): Class, I1 & I2 & I3 & I4, S1 & S2 & S3 & S4>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class): Class, I1 & I2 & I3 & I4 & I5, S1 & S2 & S3 & S4 & S5>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class): Class, I1 & I2 & I3 & I4 & I5 & I6, S1 & S2 & S3 & S4 & S5 & S6>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7, S1 & S2 & S3 & S4 & S5 & S6 & S7>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class, c9: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class, c9: Class, c10: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9 & I10, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10>; +/** + * A decorator version of the `Mixin` function. You'll want to use this instead of `Mixin` for mixing generic classes. + */ +declare const mix: (...ingredients: Class[]) => (decoratedClass: any) => any; +export { Mixin, mix }; diff --git a/node_modules/ts-mixer/dist/esm/proxy.d.ts b/node_modules/ts-mixer/dist/esm/proxy.d.ts new file mode 100644 index 0000000..fafe399 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/proxy.d.ts @@ -0,0 +1,16 @@ +/** + * Finds the ingredient with the given prop, searching in reverse order and breadth-first if searching ingredient + * prototypes is required. + */ +export declare const getIngredientWithProp: (prop: string | number | symbol, ingredients: any[]) => object | undefined; +/** + * "Mixes" ingredients by wrapping them in a Proxy. The optional prototype argument allows the mixed object to sit + * downstream of an existing prototype chain. Note that "properties" cannot be added, deleted, or modified. + */ +export declare const proxyMix: (ingredients: any[], prototype?: Object) => {}; +/** + * Creates a new proxy-prototype object that is a "soft" mixture of the given prototypes. The mixing is achieved by + * proxying all property access to the ingredients. This is not ES5 compatible and less performant. However, any + * changes made to the source prototypes will be reflected in the proxy-prototype, which may be desirable. + */ +export declare const softMixProtos: (ingredients: any[], constructor: Function) => object; diff --git a/node_modules/ts-mixer/dist/esm/settings.d.ts b/node_modules/ts-mixer/dist/esm/settings.d.ts new file mode 100644 index 0000000..d34d2b4 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/settings.d.ts @@ -0,0 +1,7 @@ +export type Settings = { + initFunction: string | null; + staticsStrategy: 'copy' | 'proxy'; + prototypeStrategy: 'copy' | 'proxy'; + decoratorInheritance: 'deep' | 'direct' | 'none'; +}; +export declare const settings: Settings; diff --git a/node_modules/ts-mixer/dist/esm/types.d.ts b/node_modules/ts-mixer/dist/esm/types.d.ts new file mode 100644 index 0000000..cb25fc1 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/types.d.ts @@ -0,0 +1,13 @@ +/** + * Returns the longer of the two tuples. Indefinite tuples will always be considered longest. + */ +type _Longest = any[] extends T1 ? T1 : any[] extends T2 ? T2 : Exclude extends never ? T2 : T1; +/** + * Returns the longest of up to 10 different tuples. + */ +export type Longest = _Longest<_Longest<_Longest<_Longest, _Longest>, _Longest<_Longest, _Longest>>, _Longest>; +/** + * A rigorous type alias for a class. + */ +export type Class = (abstract new (...args: any[]) => InstanceType) & StaticType; +export {}; diff --git a/node_modules/ts-mixer/dist/esm/util.d.ts b/node_modules/ts-mixer/dist/esm/util.d.ts new file mode 100644 index 0000000..4797ef4 --- /dev/null +++ b/node_modules/ts-mixer/dist/esm/util.d.ts @@ -0,0 +1,27 @@ +/** + * Utility function that works like `Object.apply`, but copies getters and setters properly as well. Additionally gives + * the option to exclude properties by name. + */ +export declare const copyProps: (dest: object, src: object, exclude?: string[]) => void; +/** + * Returns the full chain of prototypes up until Object.prototype given a starting object. The order of prototypes will + * be closest to farthest in the chain. + */ +export declare const protoChain: (obj: object, currentChain?: object[]) => object[]; +/** + * Identifies the nearest ancestor common to all the given objects in their prototype chains. For most unrelated + * objects, this function should return Object.prototype. + */ +export declare const nearestCommonProto: (...objs: object[]) => object | undefined; +/** + * Creates a new prototype object that is a mixture of the given prototypes. The mixing is achieved by first + * identifying the nearest common ancestor and using it as the prototype for a new object. Then all properties/methods + * downstream of this prototype (ONLY downstream) are copied into the new object. + * + * The resulting prototype is more performant than softMixProtos(...), as well as ES5 compatible. However, it's not as + * flexible as updates to the source prototypes aren't captured by the mixed result. See softMixProtos for why you may + * want to use that instead. + */ +export declare const hardMixProtos: (ingredients: any[], constructor: Function | null, exclude?: string[]) => object; +export declare const unique: (arr: T[]) => T[]; +export declare const flatten: (arr: T[][]) => T[]; diff --git a/node_modules/ts-mixer/dist/types/decorator.d.ts b/node_modules/ts-mixer/dist/types/decorator.d.ts new file mode 100644 index 0000000..dde5df2 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/decorator.d.ts @@ -0,0 +1,18 @@ +import { Class } from './types'; +type ObjectOfDecorators = { + [key: string]: T[]; +}; +export type PropertyAndMethodDecorators = { + property?: ObjectOfDecorators; + method?: ObjectOfDecorators; +}; +type Decorators = { + class?: ClassDecorator[]; + static?: PropertyAndMethodDecorators; + instance?: PropertyAndMethodDecorators; +}; +export declare const deepDecoratorSearch: (...classes: Class[]) => Decorators; +export declare const directDecoratorSearch: (...classes: Class[]) => Decorators; +export declare const getDecoratorsForClass: (clazz: Class) => Decorators; +export declare const decorate: (decorator: T) => T; +export {}; diff --git a/node_modules/ts-mixer/dist/types/index.d.ts b/node_modules/ts-mixer/dist/types/index.d.ts new file mode 100644 index 0000000..2a16080 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/index.d.ts @@ -0,0 +1,4 @@ +export { Mixin, mix } from './mixins'; +export { settings } from './settings'; +export { decorate } from './decorator'; +export { hasMixin } from './mixin-tracking'; diff --git a/node_modules/ts-mixer/dist/types/mixin-tracking.d.ts b/node_modules/ts-mixer/dist/types/mixin-tracking.d.ts new file mode 100644 index 0000000..1beaf87 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/mixin-tracking.d.ts @@ -0,0 +1,4 @@ +import { Class } from './types'; +export declare const getMixinsForClass: (clazz: Class) => Function[] | undefined; +export declare const registerMixins: (mixedClass: any, constituents: Function[]) => Map; +export declare const hasMixin: (instance: any, mixin: abstract new (...args: any[]) => M) => instance is M; diff --git a/node_modules/ts-mixer/dist/types/mixins.d.ts b/node_modules/ts-mixer/dist/types/mixins.d.ts new file mode 100644 index 0000000..a4f65be --- /dev/null +++ b/node_modules/ts-mixer/dist/types/mixins.d.ts @@ -0,0 +1,16 @@ +import { Class, Longest } from './types'; +declare function Mixin(c1: Class): Class; +declare function Mixin(c1: Class, c2: Class): Class, I1 & I2, S1 & S2>; +declare function Mixin(c1: Class, c2: Class, c3: Class): Class, I1 & I2 & I3, S1 & S2 & S3>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class): Class, I1 & I2 & I3 & I4, S1 & S2 & S3 & S4>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class): Class, I1 & I2 & I3 & I4 & I5, S1 & S2 & S3 & S4 & S5>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class): Class, I1 & I2 & I3 & I4 & I5 & I6, S1 & S2 & S3 & S4 & S5 & S6>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7, S1 & S2 & S3 & S4 & S5 & S6 & S7>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class, c9: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9>; +declare function Mixin(c1: Class, c2: Class, c3: Class, c4: Class, c5: Class, c6: Class, c7: Class, c8: Class, c9: Class, c10: Class): Class, I1 & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9 & I10, S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10>; +/** + * A decorator version of the `Mixin` function. You'll want to use this instead of `Mixin` for mixing generic classes. + */ +declare const mix: (...ingredients: Class[]) => (decoratedClass: any) => any; +export { Mixin, mix }; diff --git a/node_modules/ts-mixer/dist/types/proxy.d.ts b/node_modules/ts-mixer/dist/types/proxy.d.ts new file mode 100644 index 0000000..fafe399 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/proxy.d.ts @@ -0,0 +1,16 @@ +/** + * Finds the ingredient with the given prop, searching in reverse order and breadth-first if searching ingredient + * prototypes is required. + */ +export declare const getIngredientWithProp: (prop: string | number | symbol, ingredients: any[]) => object | undefined; +/** + * "Mixes" ingredients by wrapping them in a Proxy. The optional prototype argument allows the mixed object to sit + * downstream of an existing prototype chain. Note that "properties" cannot be added, deleted, or modified. + */ +export declare const proxyMix: (ingredients: any[], prototype?: Object) => {}; +/** + * Creates a new proxy-prototype object that is a "soft" mixture of the given prototypes. The mixing is achieved by + * proxying all property access to the ingredients. This is not ES5 compatible and less performant. However, any + * changes made to the source prototypes will be reflected in the proxy-prototype, which may be desirable. + */ +export declare const softMixProtos: (ingredients: any[], constructor: Function) => object; diff --git a/node_modules/ts-mixer/dist/types/settings.d.ts b/node_modules/ts-mixer/dist/types/settings.d.ts new file mode 100644 index 0000000..d34d2b4 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/settings.d.ts @@ -0,0 +1,7 @@ +export type Settings = { + initFunction: string | null; + staticsStrategy: 'copy' | 'proxy'; + prototypeStrategy: 'copy' | 'proxy'; + decoratorInheritance: 'deep' | 'direct' | 'none'; +}; +export declare const settings: Settings; diff --git a/node_modules/ts-mixer/dist/types/types.d.ts b/node_modules/ts-mixer/dist/types/types.d.ts new file mode 100644 index 0000000..cb25fc1 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/types.d.ts @@ -0,0 +1,13 @@ +/** + * Returns the longer of the two tuples. Indefinite tuples will always be considered longest. + */ +type _Longest = any[] extends T1 ? T1 : any[] extends T2 ? T2 : Exclude extends never ? T2 : T1; +/** + * Returns the longest of up to 10 different tuples. + */ +export type Longest = _Longest<_Longest<_Longest<_Longest, _Longest>, _Longest<_Longest, _Longest>>, _Longest>; +/** + * A rigorous type alias for a class. + */ +export type Class = (abstract new (...args: any[]) => InstanceType) & StaticType; +export {}; diff --git a/node_modules/ts-mixer/dist/types/util.d.ts b/node_modules/ts-mixer/dist/types/util.d.ts new file mode 100644 index 0000000..4797ef4 --- /dev/null +++ b/node_modules/ts-mixer/dist/types/util.d.ts @@ -0,0 +1,27 @@ +/** + * Utility function that works like `Object.apply`, but copies getters and setters properly as well. Additionally gives + * the option to exclude properties by name. + */ +export declare const copyProps: (dest: object, src: object, exclude?: string[]) => void; +/** + * Returns the full chain of prototypes up until Object.prototype given a starting object. The order of prototypes will + * be closest to farthest in the chain. + */ +export declare const protoChain: (obj: object, currentChain?: object[]) => object[]; +/** + * Identifies the nearest ancestor common to all the given objects in their prototype chains. For most unrelated + * objects, this function should return Object.prototype. + */ +export declare const nearestCommonProto: (...objs: object[]) => object | undefined; +/** + * Creates a new prototype object that is a mixture of the given prototypes. The mixing is achieved by first + * identifying the nearest common ancestor and using it as the prototype for a new object. Then all properties/methods + * downstream of this prototype (ONLY downstream) are copied into the new object. + * + * The resulting prototype is more performant than softMixProtos(...), as well as ES5 compatible. However, it's not as + * flexible as updates to the source prototypes aren't captured by the mixed result. See softMixProtos for why you may + * want to use that instead. + */ +export declare const hardMixProtos: (ingredients: any[], constructor: Function | null, exclude?: string[]) => object; +export declare const unique: (arr: T[]) => T[]; +export declare const flatten: (arr: T[][]) => T[]; diff --git a/node_modules/ts-mixer/package.json b/node_modules/ts-mixer/package.json new file mode 100644 index 0000000..ddb92f2 --- /dev/null +++ b/node_modules/ts-mixer/package.json @@ -0,0 +1,63 @@ +{ + "name": "ts-mixer", + "version": "6.0.3", + "description": "A very small TypeScript library that provides tolerable Mixin functionality.", + "main": "dist/cjs/index.js", + "module": "dist/esm/index.js", + "browser": "dist/esm/index.js", + "unpkg": "dist/esm/index.min.js", + "types": "dist/types/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "prebuild": "yarn clean", + "build": "rollup -c && tsc", + "clean": "rimraf dist", + "lint": "eslint src/**/*.ts", + "test": "nyc mocha", + "codegen": "node ./codegen.js", + "release": "standard-version" + }, + "devDependencies": { + "@commitlint/cli": "^12.1.4", + "@commitlint/config-conventional": "^12.1.4", + "@rollup/plugin-typescript": "^8.2.1", + "@types/chai": "^4.2.19", + "@types/mocha": "^8.2.2", + "@types/node": "^15.12.4", + "@types/sinon": "^10.0.2", + "@typescript-eslint/parser": "^4.27.0", + "chai": "^4.3.4", + "class-validator": "^0.13.1", + "coveralls": "^3.1.0", + "eslint": "^7.29.0", + "husky": "^4.2.5", + "js-yaml": "^4.1.0", + "mocha": "^9.0.1", + "nyc": "14.1.1", + "rimraf": "^3.0.2", + "rollup": "^2.52.1", + "rollup-plugin-terser": "^7.0.2", + "sinon": "^11.1.1", + "standard-version": "^9.3.0", + "ts-node": "^10.0.0", + "tslib": "^2.3.0", + "typescript": "^4.3.4", + "yarn-add-no-save": "^1.0.3" + }, + "homepage": "https://github.com/tannerntannern/ts-mixer#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/tannerntannern/ts-mixer.git" + }, + "keywords": [ + "typescript", + "mixin", + "mixins", + "multiple inheritance", + "mixin classes" + ], + "author": "Tanner Nielsen", + "license": "MIT" +} diff --git a/node_modules/tslib/CopyrightNotice.txt b/node_modules/tslib/CopyrightNotice.txt new file mode 100644 index 0000000..5d7d2d9 --- /dev/null +++ b/node_modules/tslib/CopyrightNotice.txt @@ -0,0 +1,15 @@ +/****************************************************************************** +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. +***************************************************************************** */ + diff --git a/node_modules/tslib/LICENSE.txt b/node_modules/tslib/LICENSE.txt new file mode 100644 index 0000000..fa7d1bd --- /dev/null +++ b/node_modules/tslib/LICENSE.txt @@ -0,0 +1,12 @@ +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. \ No newline at end of file diff --git a/node_modules/tslib/README.md b/node_modules/tslib/README.md new file mode 100644 index 0000000..14b9a83 --- /dev/null +++ b/node_modules/tslib/README.md @@ -0,0 +1,164 @@ +# tslib + +This is a runtime library for [TypeScript](https://www.typescriptlang.org/) that contains all of the TypeScript helper functions. + +This library is primarily used by the `--importHelpers` flag in TypeScript. +When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file: + +```ts +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +exports.x = {}; +exports.y = __assign({}, exports.x); + +``` + +will instead be emitted as something like the following: + +```ts +var tslib_1 = require("tslib"); +exports.x = {}; +exports.y = tslib_1.__assign({}, exports.x); +``` + +Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead. +For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`. + +# Installing + +For the latest stable version, run: + +## npm + +```sh +# TypeScript 3.9.2 or later +npm install tslib + +# TypeScript 3.8.4 or earlier +npm install tslib@^1 + +# TypeScript 2.3.2 or earlier +npm install tslib@1.6.1 +``` + +## yarn + +```sh +# TypeScript 3.9.2 or later +yarn add tslib + +# TypeScript 3.8.4 or earlier +yarn add tslib@^1 + +# TypeScript 2.3.2 or earlier +yarn add tslib@1.6.1 +``` + +## bower + +```sh +# TypeScript 3.9.2 or later +bower install tslib + +# TypeScript 3.8.4 or earlier +bower install tslib@^1 + +# TypeScript 2.3.2 or earlier +bower install tslib@1.6.1 +``` + +## JSPM + +```sh +# TypeScript 3.9.2 or later +jspm install tslib + +# TypeScript 3.8.4 or earlier +jspm install tslib@^1 + +# TypeScript 2.3.2 or earlier +jspm install tslib@1.6.1 +``` + +# Usage + +Set the `importHelpers` compiler option on the command line: + +``` +tsc --importHelpers file.ts +``` + +or in your tsconfig.json: + +```json +{ + "compilerOptions": { + "importHelpers": true + } +} +``` + +#### For bower and JSPM users + +You will need to add a `paths` mapping for `tslib`, e.g. For Bower users: + +```json +{ + "compilerOptions": { + "module": "amd", + "importHelpers": true, + "baseUrl": "./", + "paths": { + "tslib" : ["bower_components/tslib/tslib.d.ts"] + } + } +} +``` + +For JSPM users: + +```json +{ + "compilerOptions": { + "module": "system", + "importHelpers": true, + "baseUrl": "./", + "paths": { + "tslib" : ["jspm_packages/npm/tslib@2.x.y/tslib.d.ts"] + } + } +} +``` + +## Deployment + +- Choose your new version number +- Set it in `package.json` and `bower.json` +- Create a tag: `git tag [version]` +- Push the tag: `git push --tags` +- Create a [release in GitHub](https://github.com/microsoft/tslib/releases) +- Run the [publish to npm](https://github.com/microsoft/tslib/actions?query=workflow%3A%22Publish+to+NPM%22) workflow + +Done. + +# Contribute + +There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. + +* [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. +* Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). +* Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). +* Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. +* [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). + +# Documentation + +* [Quick tutorial](http://www.typescriptlang.org/Tutorial) +* [Programming handbook](http://www.typescriptlang.org/Handbook) +* [Homepage](http://www.typescriptlang.org/) diff --git a/node_modules/tslib/SECURITY.md b/node_modules/tslib/SECURITY.md new file mode 100644 index 0000000..869fdfe --- /dev/null +++ b/node_modules/tslib/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). + + diff --git a/node_modules/tslib/modules/index.d.ts b/node_modules/tslib/modules/index.d.ts new file mode 100644 index 0000000..0fedae8 --- /dev/null +++ b/node_modules/tslib/modules/index.d.ts @@ -0,0 +1,37 @@ +// Note: named reexports are used instead of `export *` because +// TypeScript itself doesn't resolve the `export *` when checking +// if a particular helper exists. +export { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __createBinding, + __addDisposableResource, + __disposeResources, +} from '../tslib.js'; +export * as default from '../tslib.js'; diff --git a/node_modules/tslib/modules/index.js b/node_modules/tslib/modules/index.js new file mode 100644 index 0000000..0c9dcd5 --- /dev/null +++ b/node_modules/tslib/modules/index.js @@ -0,0 +1,68 @@ +import tslib from '../tslib.js'; +const { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, +} = tslib; +export { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, +}; +export default tslib; diff --git a/node_modules/tslib/modules/package.json b/node_modules/tslib/modules/package.json new file mode 100644 index 0000000..96ae6e5 --- /dev/null +++ b/node_modules/tslib/modules/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/node_modules/tslib/package.json b/node_modules/tslib/package.json new file mode 100644 index 0000000..0a1fdec --- /dev/null +++ b/node_modules/tslib/package.json @@ -0,0 +1,47 @@ +{ + "name": "tslib", + "author": "Microsoft Corp.", + "homepage": "https://www.typescriptlang.org/", + "version": "2.6.2", + "license": "0BSD", + "description": "Runtime library for TypeScript helper functions", + "keywords": [ + "TypeScript", + "Microsoft", + "compiler", + "language", + "javascript", + "tslib", + "runtime" + ], + "bugs": { + "url": "https://github.com/Microsoft/TypeScript/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/tslib.git" + }, + "main": "tslib.js", + "module": "tslib.es6.js", + "jsnext:main": "tslib.es6.js", + "typings": "tslib.d.ts", + "sideEffects": false, + "exports": { + ".": { + "module": { + "types": "./modules/index.d.ts", + "default": "./tslib.es6.mjs" + }, + "import": { + "node": "./modules/index.js", + "default": { + "types": "./modules/index.d.ts", + "default": "./tslib.es6.mjs" + } + }, + "default": "./tslib.js" + }, + "./*": "./*", + "./": "./" + } +} diff --git a/node_modules/tslib/tslib.d.ts b/node_modules/tslib/tslib.d.ts new file mode 100644 index 0000000..95cbc4f --- /dev/null +++ b/node_modules/tslib/tslib.d.ts @@ -0,0 +1,453 @@ +/****************************************************************************** +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. +***************************************************************************** */ + +/** + * Used to shim class extends. + * + * @param d The derived class. + * @param b The base class. + */ +export declare function __extends(d: Function, b: Function): void; + +/** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * + * @param t The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ +export declare function __assign(t: any, ...sources: any[]): any; + +/** + * Performs a rest spread on an object. + * + * @param t The source value. + * @param propertyNames The property names excluded from the rest spread. + */ +export declare function __rest(t: any, propertyNames: (string | symbol)[]): any; + +/** + * Applies decorators to a target object + * + * @param decorators The set of decorators to apply. + * @param target The target object. + * @param key If specified, the own property to apply the decorators to. + * @param desc The property descriptor, defaults to fetching the descriptor from the target object. + * @experimental + */ +export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any; + +/** + * Creates an observing function decorator from a parameter decorator. + * + * @param paramIndex The parameter index to apply the decorator to. + * @param decorator The parameter decorator to apply. Note that the return value is ignored. + * @experimental + */ +export declare function __param(paramIndex: number, decorator: Function): Function; + +/** + * Applies decorators to a class or class member, following the native ECMAScript decorator specification. + * @param ctor For non-field class members, the class constructor. Otherwise, `null`. + * @param descriptorIn The `PropertyDescriptor` to use when unable to look up the property from `ctor`. + * @param decorators The decorators to apply + * @param contextIn The `DecoratorContext` to clone for each decorator application. + * @param initializers An array of field initializer mutation functions into which new initializers are written. + * @param extraInitializers An array of extra initializer functions into which new initializers are written. + */ +export declare function __esDecorate(ctor: Function | null, descriptorIn: object | null, decorators: Function[], contextIn: object, initializers: Function[] | null, extraInitializers: Function[]): void; + +/** + * Runs field initializers or extra initializers generated by `__esDecorate`. + * @param thisArg The `this` argument to use. + * @param initializers The array of initializers to evaluate. + * @param value The initial value to pass to the initializers. + */ +export declare function __runInitializers(thisArg: unknown, initializers: Function[], value?: any): any; + +/** + * Converts a computed property name into a `string` or `symbol` value. + */ +export declare function __propKey(x: any): string | symbol; + +/** + * Assigns the name of a function derived from the left-hand side of an assignment. + * @param f The function to rename. + * @param name The new name for the function. + * @param prefix A prefix (such as `"get"` or `"set"`) to insert before the name. + */ +export declare function __setFunctionName(f: Function, name: string | symbol, prefix?: string): Function; + +/** + * Creates a decorator that sets metadata. + * + * @param metadataKey The metadata key + * @param metadataValue The metadata value + * @experimental + */ +export declare function __metadata(metadataKey: any, metadataValue: any): Function; + +/** + * Converts a generator function into a pseudo-async function, by treating each `yield` as an `await`. + * + * @param thisArg The reference to use as the `this` value in the generator function + * @param _arguments The optional arguments array + * @param P The optional promise constructor argument, defaults to the `Promise` property of the global object. + * @param generator The generator function + */ +export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any; + +/** + * Creates an Iterator object using the body as the implementation. + * + * @param thisArg The reference to use as the `this` value in the function + * @param body The generator state-machine based implementation. + * + * @see [./docs/generator.md] + */ +export declare function __generator(thisArg: any, body: Function): any; + +/** + * Creates bindings for all enumerable properties of `m` on `exports` + * + * @param m The source object + * @param exports The `exports` object. + */ +export declare function __exportStar(m: any, o: any): void; + +/** + * Creates a value iterator from an `Iterable` or `ArrayLike` object. + * + * @param o The object. + * @throws {TypeError} If `o` is neither `Iterable`, nor an `ArrayLike`. + */ +export declare function __values(o: any): any; + +/** + * Reads values from an `Iterable` or `ArrayLike` object and returns the resulting array. + * + * @param o The object to read from. + * @param n The maximum number of arguments to read, defaults to `Infinity`. + */ +export declare function __read(o: any, n?: number): any[]; + +/** + * Creates an array from iterable spread. + * + * @param args The Iterable objects to spread. + * @deprecated since TypeScript 4.2 - Use `__spreadArray` + */ +export declare function __spread(...args: any[][]): any[]; + +/** + * Creates an array from array spread. + * + * @param args The ArrayLikes to spread into the resulting array. + * @deprecated since TypeScript 4.2 - Use `__spreadArray` + */ +export declare function __spreadArrays(...args: any[][]): any[]; + +/** + * Spreads the `from` array into the `to` array. + * + * @param pack Replace empty elements with `undefined`. + */ +export declare function __spreadArray(to: any[], from: any[], pack?: boolean): any[]; + +/** + * Creates an object that signals to `__asyncGenerator` that it shouldn't be yielded, + * and instead should be awaited and the resulting value passed back to the generator. + * + * @param v The value to await. + */ +export declare function __await(v: any): any; + +/** + * Converts a generator function into an async generator function, by using `yield __await` + * in place of normal `await`. + * + * @param thisArg The reference to use as the `this` value in the generator function + * @param _arguments The optional arguments array + * @param generator The generator function + */ +export declare function __asyncGenerator(thisArg: any, _arguments: any, generator: Function): any; + +/** + * Used to wrap a potentially async iterator in such a way so that it wraps the result + * of calling iterator methods of `o` in `__await` instances, and then yields the awaited values. + * + * @param o The potentially async iterator. + * @returns A synchronous iterator yielding `__await` instances on every odd invocation + * and returning the awaited `IteratorResult` passed to `next` every even invocation. + */ +export declare function __asyncDelegator(o: any): any; + +/** + * Creates a value async iterator from an `AsyncIterable`, `Iterable` or `ArrayLike` object. + * + * @param o The object. + * @throws {TypeError} If `o` is neither `AsyncIterable`, `Iterable`, nor an `ArrayLike`. + */ +export declare function __asyncValues(o: any): any; + +/** + * Creates a `TemplateStringsArray` frozen object from the `cooked` and `raw` arrays. + * + * @param cooked The cooked possibly-sparse array. + * @param raw The raw string content. + */ +export declare function __makeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray; + +/** + * Used to shim default and named imports in ECMAScript Modules transpiled to CommonJS. + * + * ```js + * import Default, { Named, Other } from "mod"; + * // or + * import { default as Default, Named, Other } from "mod"; + * ``` + * + * @param mod The CommonJS module exports object. + */ +export declare function __importStar(mod: T): T; + +/** + * Used to shim default imports in ECMAScript Modules transpiled to CommonJS. + * + * ```js + * import Default from "mod"; + * ``` + * + * @param mod The CommonJS module exports object. + */ +export declare function __importDefault(mod: T): T | { default: T }; + +/** + * Emulates reading a private instance field. + * + * @param receiver The instance from which to read the private field. + * @param state A WeakMap containing the private field value for an instance. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet( + receiver: T, + state: { has(o: T): boolean, get(o: T): V | undefined }, + kind?: "f" +): V; + +/** + * Emulates reading a private static field. + * + * @param receiver The object from which to read the private static field. + * @param state The class constructor containing the definition of the static field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The descriptor that holds the static field value. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V>( + receiver: T, + state: T, + kind: "f", + f: { value: V } +): V; + +/** + * Emulates evaluating a private instance "get" accessor. + * + * @param receiver The instance on which to evaluate the private "get" accessor. + * @param state A WeakSet used to verify an instance supports the private "get" accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "get" accessor function to evaluate. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet( + receiver: T, + state: { has(o: T): boolean }, + kind: "a", + f: () => V +): V; + +/** + * Emulates evaluating a private static "get" accessor. + * + * @param receiver The object on which to evaluate the private static "get" accessor. + * @param state The class constructor containing the definition of the static "get" accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "get" accessor function to evaluate. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V>( + receiver: T, + state: T, + kind: "a", + f: () => V +): V; + +/** + * Emulates reading a private instance method. + * + * @param receiver The instance from which to read a private method. + * @param state A WeakSet used to verify an instance supports the private method. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The function to return as the private instance method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet unknown>( + receiver: T, + state: { has(o: T): boolean }, + kind: "m", + f: V +): V; + +/** + * Emulates reading a private static method. + * + * @param receiver The object from which to read the private static method. + * @param state The class constructor containing the definition of the static method. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The function to return as the private static method. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V extends (...args: any[]) => unknown>( + receiver: T, + state: T, + kind: "m", + f: V +): V; + +/** + * Emulates writing to a private instance field. + * + * @param receiver The instance on which to set a private field value. + * @param state A WeakMap used to store the private field value for an instance. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldSet( + receiver: T, + state: { has(o: T): boolean, set(o: T, value: V): unknown }, + value: V, + kind?: "f" +): V; + +/** + * Emulates writing to a private static field. + * + * @param receiver The object on which to set the private static field. + * @param state The class constructor containing the definition of the private static field. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The descriptor that holds the static field value. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldSet unknown, V>( + receiver: T, + state: T, + value: V, + kind: "f", + f: { value: V } +): V; + +/** + * Emulates writing to a private instance "set" accessor. + * + * @param receiver The instance on which to evaluate the private instance "set" accessor. + * @param state A WeakSet used to verify an instance supports the private "set" accessor. + * @param value The value to store in the private accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "set" accessor function to evaluate. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldSet( + receiver: T, + state: { has(o: T): boolean }, + value: V, + kind: "a", + f: (v: V) => void +): V; + +/** + * Emulates writing to a private static "set" accessor. + * + * @param receiver The object on which to evaluate the private static "set" accessor. + * @param state The class constructor containing the definition of the static "set" accessor. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "set" accessor function to evaluate. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldSet unknown, V>( + receiver: T, + state: T, + value: V, + kind: "a", + f: (v: V) => void +): V; + +/** + * Checks for the existence of a private field/method/accessor. + * + * @param state The class constructor containing the static member, or the WeakMap or WeakSet associated with a private instance member. + * @param receiver The object for which to test the presence of the private member. + */ +export declare function __classPrivateFieldIn( + state: (new (...args: any[]) => unknown) | { has(o: any): boolean }, + receiver: unknown, +): boolean; + +/** + * Creates a re-export binding on `object` with key `objectKey` that references `target[key]`. + * + * @param object The local `exports` object. + * @param target The object to re-export from. + * @param key The property key of `target` to re-export. + * @param objectKey The property key to re-export as. Defaults to `key`. + */ +export declare function __createBinding(object: object, target: object, key: PropertyKey, objectKey?: PropertyKey): void; + +/** + * Adds a disposable resource to a resource-tracking environment object. + * @param env A resource-tracking environment object. + * @param value Either a Disposable or AsyncDisposable object, `null`, or `undefined`. + * @param async When `true`, `AsyncDisposable` resources can be added. When `false`, `AsyncDisposable` resources cannot be added. + * @returns The {@link value} argument. + * + * @throws {TypeError} If {@link value} is not an object, or if either `Symbol.dispose` or `Symbol.asyncDispose` are not + * defined, or if {@link value} does not have an appropriate `Symbol.dispose` or `Symbol.asyncDispose` method. + */ +export declare function __addDisposableResource(env: { stack: { value?: unknown, dispose?: Function, async: boolean }[]; error: unknown; hasError: boolean; }, value: T, async: boolean): T; + +/** + * Disposes all resources in a resource-tracking environment object. + * @param env A resource-tracking environment object. + * @returns A {@link Promise} if any resources in the environment were marked as `async` when added; otherwise, `void`. + * + * @throws {SuppressedError} if an error thrown during disposal would have suppressed a prior error from disposal or the + * error recorded in the resource-tracking environment object. + * @seealso {@link __addDisposableResource} + */ +export declare function __disposeResources(env: { stack: { value?: unknown, dispose?: Function, async: boolean }[]; error: unknown; hasError: boolean; }): any; diff --git a/node_modules/tslib/tslib.es6.html b/node_modules/tslib/tslib.es6.html new file mode 100644 index 0000000..b122e41 --- /dev/null +++ b/node_modules/tslib/tslib.es6.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/tslib/tslib.es6.js b/node_modules/tslib/tslib.es6.js new file mode 100644 index 0000000..66174fb --- /dev/null +++ b/node_modules/tslib/tslib.es6.js @@ -0,0 +1,370 @@ +/****************************************************************************** +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 */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export 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."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export 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); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +export function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +export function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); +} + +export default { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __createBinding: __createBinding, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, +}; diff --git a/node_modules/tslib/tslib.es6.mjs b/node_modules/tslib/tslib.es6.mjs new file mode 100644 index 0000000..c8e2999 --- /dev/null +++ b/node_modules/tslib/tslib.es6.mjs @@ -0,0 +1,370 @@ +/****************************************************************************** +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 */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export 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."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export 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); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +export function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +export function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); +} + +export default { + __extends, + __assign, + __rest, + __decorate, + __param, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, +}; diff --git a/node_modules/tslib/tslib.html b/node_modules/tslib/tslib.html new file mode 100644 index 0000000..44c9ba5 --- /dev/null +++ b/node_modules/tslib/tslib.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/node_modules/tslib/tslib.js b/node_modules/tslib/tslib.js new file mode 100644 index 0000000..7c53293 --- /dev/null +++ b/node_modules/tslib/tslib.js @@ -0,0 +1,421 @@ +/****************************************************************************** +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 global, define, Symbol, Reflect, Promise, SuppressedError */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __classPrivateFieldIn; +var __createBinding; +var __addDisposableResource; +var __disposeResources; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if (typeof module === "object" && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (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."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (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); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + + __addDisposableResource = function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + }; + + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); +}); diff --git a/node_modules/undici-types/README.md b/node_modules/undici-types/README.md new file mode 100644 index 0000000..20a721c --- /dev/null +++ b/node_modules/undici-types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/node_modules/undici-types/agent.d.ts b/node_modules/undici-types/agent.d.ts new file mode 100644 index 0000000..58081ce --- /dev/null +++ b/node_modules/undici-types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from "./dispatcher"; + +export default Agent + +declare class Agent extends Dispatcher{ + constructor(opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean; + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean; + /** Dispatches a request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + /** Integer. Default: `0` */ + maxRedirections?: number; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + /** Integer. */ + maxRedirections?: number; + } +} diff --git a/node_modules/undici-types/api.d.ts b/node_modules/undici-types/api.d.ts new file mode 100644 index 0000000..400341d --- /dev/null +++ b/node_modules/undici-types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +export { + request, + stream, + pipeline, + connect, + upgrade, +} + +/** Performs an HTTP request. */ +declare function request( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit & Partial>, +): Promise; + +/** A faster version of `request`. */ +declare function stream( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + factory: Dispatcher.StreamFactory +): Promise; + +/** For easy use with `stream.pipeline`. */ +declare function pipeline( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + handler: Dispatcher.PipelineHandler +): Duplex; + +/** Starts two-way communications with the requested resource. */ +declare function connect( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; + +/** Upgrade to a different protocol. */ +declare function upgrade( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; diff --git a/node_modules/undici-types/balanced-pool.d.ts b/node_modules/undici-types/balanced-pool.d.ts new file mode 100644 index 0000000..d1e9375 --- /dev/null +++ b/node_modules/undici-types/balanced-pool.d.ts @@ -0,0 +1,18 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +declare class BalancedPool extends Dispatcher { + constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + + addUpstream(upstream: string | URL): BalancedPool; + removeUpstream(upstream: string | URL): BalancedPool; + upstreams: Array; + + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; +} diff --git a/node_modules/undici-types/cache.d.ts b/node_modules/undici-types/cache.d.ts new file mode 100644 index 0000000..4c33335 --- /dev/null +++ b/node_modules/undici-types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/node_modules/undici-types/client.d.ts b/node_modules/undici-types/client.d.ts new file mode 100644 index 0000000..74948b1 --- /dev/null +++ b/node_modules/undici-types/client.d.ts @@ -0,0 +1,97 @@ +import { URL } from 'url' +import { TlsOptions } from 'tls' +import Dispatcher from './dispatcher' +import buildConnector from "./connector"; + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor(url: string | URL, options?: Client.Options); + /** Property to get and set the pipelining factor. */ + pipelining: number; + /** `true` after `client.close()` has been called. */ + closed: boolean; + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean; +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + maxRedirections?: number; + /** TODO */ + connect?: buildConnector.BuildOptions | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overriden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client; diff --git a/node_modules/undici-types/connector.d.ts b/node_modules/undici-types/connector.d.ts new file mode 100644 index 0000000..bd92433 --- /dev/null +++ b/node_modules/undici-types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/node_modules/undici-types/content-type.d.ts b/node_modules/undici-types/content-type.d.ts new file mode 100644 index 0000000..f2a87f1 --- /dev/null +++ b/node_modules/undici-types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/node_modules/undici-types/cookies.d.ts b/node_modules/undici-types/cookies.d.ts new file mode 100644 index 0000000..aa38cae --- /dev/null +++ b/node_modules/undici-types/cookies.d.ts @@ -0,0 +1,28 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void diff --git a/node_modules/undici-types/diagnostics-channel.d.ts b/node_modules/undici-types/diagnostics-channel.d.ts new file mode 100644 index 0000000..85d4482 --- /dev/null +++ b/node_modules/undici-types/diagnostics-channel.d.ts @@ -0,0 +1,67 @@ +import { Socket } from "net"; +import { URL } from "url"; +import Connector from "./connector"; +import Dispatcher from "./dispatcher"; + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: string; + addHeader(key: string, value: string): Request; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + type Error = unknown; + interface ConnectParams { + host: URL["host"]; + hostname: URL["hostname"]; + protocol: URL["protocol"]; + port: URL["port"]; + servername: string | null; + } + type Connector = Connector.connector; + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/node_modules/undici-types/dispatcher.d.ts b/node_modules/undici-types/dispatcher.d.ts new file mode 100644 index 0000000..816db19 --- /dev/null +++ b/node_modules/undici-types/dispatcher.d.ts @@ -0,0 +1,241 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' + +type AbortSignal = unknown; + +export default Dispatcher + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise; + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise; + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + /** Upgrade to a different protocol. */ + upgrade(options: Dispatcher.UpgradeOptions): Promise; + upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close(): Promise; + close(callback: () => void): void; + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + + on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'drain', callback: (origin: URL) => void): this; + + + once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'drain', callback: (origin: URL) => void): this; + + + off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'drain', callback: (origin: URL) => void): this; + + + addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'drain', callback: (origin: URL) => void): this; + + removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; + + listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'drain'): ((origin: URL) => void)[]; + + rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; + + emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; + emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'drain', origin: URL): boolean; +} + +declare namespace Dispatcher { + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/ + expectContinue?: boolean; + } + export interface ConnectOptions { + path: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: unknown; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: unknown; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeader?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: unknown; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: unknown; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable; + export interface DispatchHandlers { + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + onConnect?(abort: () => void): void; + /** Invoked when an error has occurred. */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + onHeaders?(statusCode: number, headers: Buffer[] | string[] | null, resume: () => void): boolean; + /** Invoked when response payload data is received. */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable; + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; // throws on node v16.6.0 + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch'] + } +} diff --git a/node_modules/undici-types/errors.d.ts b/node_modules/undici-types/errors.d.ts new file mode 100644 index 0000000..7923ddd --- /dev/null +++ b/node_modules/undici-types/errors.d.ts @@ -0,0 +1,128 @@ +import { IncomingHttpHeaders } from "./header"; +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string; + code: string; + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError'; + code: 'UND_ERR_CONNECT_TIMEOUT'; + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError'; + code: 'UND_ERR_HEADERS_TIMEOUT'; + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError'; + code: 'UND_ERR_BODY_TIMEOUT'; + } + + export class ResponseStatusCodeError extends UndiciError { + constructor ( + message?: string, + statusCode?: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'ResponseStatusCodeError'; + code: 'UND_ERR_RESPONSE_STATUS_CODE'; + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null; + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError'; + code: 'UND_ERR_INVALID_ARG'; + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError'; + code: 'UND_ERR_INVALID_RETURN_VALUE'; + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError'; + code: 'UND_ERR_ABORTED'; + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError'; + code: 'UND_ERR_INFO'; + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError'; + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError'; + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError'; + code: 'UND_ERR_DESTROYED'; + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError'; + code: 'UND_ERR_CLOSED'; + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError'; + code: 'UND_ERR_SOCKET'; + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError'; + code: 'UND_ERR_NOT_SUPPORTED'; + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError'; + code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError'; + code: string; + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError'; + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } +} diff --git a/node_modules/undici-types/fetch.d.ts b/node_modules/undici-types/fetch.d.ts new file mode 100644 index 0000000..fa4619c --- /dev/null +++ b/node_modules/undici-types/fetch.d.ts @@ -0,0 +1,209 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' + +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export interface BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = string[][] | Record> | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + method?: string + keepalive?: boolean + headers?: HeadersInit + body?: BodyInit + redirect?: RequestRedirect + integrity?: string + signal?: AbortSignal + credentials?: RequestCredentials + mode?: RequestMode + referrer?: string + referrerPolicy?: ReferrerPolicy + window?: null + dispatcher?: Dispatcher + duplex?: RequestDuplex +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url'; + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request implements BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrerPolicy: string + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response implements BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Response + + static error (): Response + static json(data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/node_modules/undici-types/file.d.ts b/node_modules/undici-types/file.d.ts new file mode 100644 index 0000000..c695b7a --- /dev/null +++ b/node_modules/undici-types/file.d.ts @@ -0,0 +1,39 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT) +/// + +import { Blob } from 'buffer' + +export interface BlobPropertyBag { + type?: string + endings?: 'native' | 'transparent' +} + +export interface FilePropertyBag extends BlobPropertyBag { + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + lastModified?: number +} + +export declare class File extends Blob { + /** + * Creates a new File instance. + * + * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + * @param fileName The name of the file. + * @param options An options object containing optional attributes for the file. + */ + constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag) + + /** + * Name of the file referenced by the File object. + */ + readonly name: string + + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + readonly lastModified: number + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici-types/filereader.d.ts b/node_modules/undici-types/filereader.d.ts new file mode 100644 index 0000000..f05d231 --- /dev/null +++ b/node_modules/undici-types/filereader.d.ts @@ -0,0 +1,54 @@ +/// + +import { Blob } from 'buffer' +import { DOMException, Event, EventInit, EventTarget } from './patch' + +export declare class FileReader { + __proto__: EventTarget & FileReader + + constructor () + + readAsArrayBuffer (blob: Blob): void + readAsBinaryString (blob: Blob): void + readAsText (blob: Blob, encoding?: string): void + readAsDataURL (blob: Blob): void + + abort (): void + + static readonly EMPTY = 0 + static readonly LOADING = 1 + static readonly DONE = 2 + + readonly EMPTY = 0 + readonly LOADING = 1 + readonly DONE = 2 + + readonly readyState: number + + readonly result: string | ArrayBuffer | null + + readonly error: DOMException | null + + onloadstart: null | ((this: FileReader, event: ProgressEvent) => void) + onprogress: null | ((this: FileReader, event: ProgressEvent) => void) + onload: null | ((this: FileReader, event: ProgressEvent) => void) + onabort: null | ((this: FileReader, event: ProgressEvent) => void) + onerror: null | ((this: FileReader, event: ProgressEvent) => void) + onloadend: null | ((this: FileReader, event: ProgressEvent) => void) +} + +export interface ProgressEventInit extends EventInit { + lengthComputable?: boolean + loaded?: number + total?: number +} + +export declare class ProgressEvent { + __proto__: Event & ProgressEvent + + constructor (type: string, eventInitDict?: ProgressEventInit) + + readonly lengthComputable: boolean + readonly loaded: number + readonly total: number +} diff --git a/node_modules/undici-types/formdata.d.ts b/node_modules/undici-types/formdata.d.ts new file mode 100644 index 0000000..df29a57 --- /dev/null +++ b/node_modules/undici-types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from './file' +import { SpecIterator, SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append(name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set(name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get(name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll(name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has(name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete(name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici-types/global-dispatcher.d.ts b/node_modules/undici-types/global-dispatcher.d.ts new file mode 100644 index 0000000..728f95c --- /dev/null +++ b/node_modules/undici-types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export { + getGlobalDispatcher, + setGlobalDispatcher +} + +declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; +declare function getGlobalDispatcher(): Dispatcher; diff --git a/node_modules/undici-types/global-origin.d.ts b/node_modules/undici-types/global-origin.d.ts new file mode 100644 index 0000000..322542d --- /dev/null +++ b/node_modules/undici-types/global-origin.d.ts @@ -0,0 +1,7 @@ +export { + setGlobalOrigin, + getGlobalOrigin +} + +declare function setGlobalOrigin(origin: string | URL | undefined): void; +declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/node_modules/undici-types/handlers.d.ts b/node_modules/undici-types/handlers.d.ts new file mode 100644 index 0000000..eb4f5a9 --- /dev/null +++ b/node_modules/undici-types/handlers.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export declare class RedirectHandler implements Dispatcher.DispatchHandlers{ + constructor (dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandlers{ + constructor (handler: Dispatcher.DispatchHandlers) +} diff --git a/node_modules/undici-types/header.d.ts b/node_modules/undici-types/header.d.ts new file mode 100644 index 0000000..bfdb329 --- /dev/null +++ b/node_modules/undici-types/header.d.ts @@ -0,0 +1,4 @@ +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record; diff --git a/node_modules/undici-types/index.d.ts b/node_modules/undici-types/index.d.ts new file mode 100644 index 0000000..4589845 --- /dev/null +++ b/node_modules/undici-types/index.d.ts @@ -0,0 +1,63 @@ +import Dispatcher from'./dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from'./pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from'./client' +import buildConnector from'./connector' +import errors from'./errors' +import Agent from'./agent' +import MockClient from'./mock-client' +import MockPool from'./mock-pool' +import MockAgent from'./mock-agent' +import mockErrors from'./mock-errors' +import ProxyAgent from'./proxy-agent' +import { request, pipeline, stream, connect, upgrade } from './api' + +export * from './cookies' +export * from './fetch' +export * from './file' +export * from './filereader' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, RedirectHandler, DecoratorHandler } +export default Undici + +declare namespace Undici { + var Dispatcher: typeof import('./dispatcher').default + var Pool: typeof import('./pool').default; + var RedirectHandler: typeof import ('./handlers').RedirectHandler + var DecoratorHandler: typeof import ('./handlers').DecoratorHandler + var createRedirectInterceptor: typeof import ('./interceptors').createRedirectInterceptor + var BalancedPool: typeof import('./balanced-pool').default; + var Client: typeof import('./client').default; + var buildConnector: typeof import('./connector').default; + var errors: typeof import('./errors').default; + var Agent: typeof import('./agent').default; + var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher; + var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher; + var request: typeof import('./api').request; + var stream: typeof import('./api').stream; + var pipeline: typeof import('./api').pipeline; + var connect: typeof import('./api').connect; + var upgrade: typeof import('./api').upgrade; + var MockClient: typeof import('./mock-client').default; + var MockPool: typeof import('./mock-pool').default; + var MockAgent: typeof import('./mock-agent').default; + var mockErrors: typeof import('./mock-errors').default; + var fetch: typeof import('./fetch').fetch; + var Headers: typeof import('./fetch').Headers; + var Response: typeof import('./fetch').Response; + var Request: typeof import('./fetch').Request; + var FormData: typeof import('./formdata').FormData; + var File: typeof import('./file').File; + var FileReader: typeof import('./filereader').FileReader; + var caches: typeof import('./cache').caches; +} diff --git a/node_modules/undici-types/interceptors.d.ts b/node_modules/undici-types/interceptors.d.ts new file mode 100644 index 0000000..047ac17 --- /dev/null +++ b/node_modules/undici-types/interceptors.d.ts @@ -0,0 +1,5 @@ +import Dispatcher from "./dispatcher"; + +type RedirectInterceptorOpts = { maxRedirections?: number } + +export declare function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatchInterceptor diff --git a/node_modules/undici-types/mock-agent.d.ts b/node_modules/undici-types/mock-agent.d.ts new file mode 100644 index 0000000..98cd645 --- /dev/null +++ b/node_modules/undici-types/mock-agent.d.ts @@ -0,0 +1,50 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch; + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor(options?: MockAgent.Options) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable; + get(origin: RegExp): TInterceptable; + get(origin: ((origin: string) => boolean)): TInterceptable; + /** Dispatches a mocked request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close(): Promise; + /** Disables mocking in MockAgent. */ + deactivate(): void; + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate(): void; + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect(): void; + enableNetConnect(host: string): void; + enableNetConnect(host: RegExp): void; + enableNetConnect(host: ((host: string) => boolean)): void; + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect(): void; + pendingInterceptors(): PendingInterceptor[]; + assertNoPendingInterceptors(options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void; +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Agent; + } +} diff --git a/node_modules/undici-types/mock-client.d.ts b/node_modules/undici-types/mock-client.d.ts new file mode 100644 index 0000000..51d008c --- /dev/null +++ b/node_modules/undici-types/mock-client.d.ts @@ -0,0 +1,25 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor(origin: string, options: MockClient.Options); + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici-types/mock-errors.d.ts b/node_modules/undici-types/mock-errors.d.ts new file mode 100644 index 0000000..3d9e727 --- /dev/null +++ b/node_modules/undici-types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor(message?: string); + name: 'MockNotMatchedError'; + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } +} diff --git a/node_modules/undici-types/mock-interceptor.d.ts b/node_modules/undici-types/mock-interceptor.d.ts new file mode 100644 index 0000000..6b3961c --- /dev/null +++ b/node_modules/undici-types/mock-interceptor.d.ts @@ -0,0 +1,93 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher'; +import { BodyInit, Headers } from './fetch' + +export { + Interceptable, + MockInterceptor, + MockScope +} + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor(mockDispatch: MockInterceptor.MockDispatch); + /** Delay a reply by a set amount of time in ms. */ + delay(waitInMs: number): MockScope; + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist(): MockScope; + /** Define a reply for a set amount of matching requests. */ + times(repeatTimes: number): MockScope; +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope; + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope; + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers(trailers: Record): MockInterceptor; + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength(): MockInterceptor; +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + origin: string; + method: string; + body?: BodyInit | Dispatcher.DispatchOptions['body']; + headers: Headers | Record; + maxRedirections: number; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string; + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; +} diff --git a/node_modules/undici-types/mock-pool.d.ts b/node_modules/undici-types/mock-pool.d.ts new file mode 100644 index 0000000..39e709a --- /dev/null +++ b/node_modules/undici-types/mock-pool.d.ts @@ -0,0 +1,25 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor(origin: string, options: MockPool.Options); + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici-types/package.json b/node_modules/undici-types/package.json new file mode 100644 index 0000000..be7aa4c --- /dev/null +++ b/node_modules/undici-types/package.json @@ -0,0 +1,55 @@ +{ + "name": "undici-types", + "version": "5.26.5", + "description": "A stand-alone types package for Undici", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "types": "index.d.ts", + "files": [ + "*.d.ts" + ], + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ] +} \ No newline at end of file diff --git a/node_modules/undici-types/patch.d.ts b/node_modules/undici-types/patch.d.ts new file mode 100644 index 0000000..3871acf --- /dev/null +++ b/node_modules/undici-types/patch.d.ts @@ -0,0 +1,71 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export type DOMException = typeof globalThis extends { DOMException: infer T } + ? T + : any + +export type EventTarget = typeof globalThis extends { EventTarget: infer T } + ? T + : { + addEventListener( + type: string, + listener: any, + options?: any, + ): void + dispatchEvent(event: Event): boolean + removeEventListener( + type: string, + listener: any, + options?: any | boolean, + ): void + } + +export type Event = typeof globalThis extends { Event: infer T } + ? T + : { + readonly bubbles: boolean + cancelBubble: () => void + readonly cancelable: boolean + readonly composed: boolean + composedPath(): [EventTarget?] + readonly currentTarget: EventTarget | null + readonly defaultPrevented: boolean + readonly eventPhase: 0 | 2 + readonly isTrusted: boolean + preventDefault(): void + returnValue: boolean + readonly srcElement: EventTarget | null + stopImmediatePropagation(): void + stopPropagation(): void + readonly target: EventTarget | null + readonly timeStamp: number + readonly type: string + } + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/node_modules/undici-types/pool-stats.d.ts b/node_modules/undici-types/pool-stats.d.ts new file mode 100644 index 0000000..8b6d2bf --- /dev/null +++ b/node_modules/undici-types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from "./pool" + +export default PoolStats + +declare class PoolStats { + constructor(pool: Pool); + /** Number of open socket connections in this pool. */ + connected: number; + /** Number of open socket connections in this pool that do not have an active request. */ + free: number; + /** Number of pending requests across all clients in this pool. */ + pending: number; + /** Number of queued requests across all clients in this pool. */ + queued: number; + /** Number of currently active requests across all clients in this pool. */ + running: number; + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number; +} diff --git a/node_modules/undici-types/pool.d.ts b/node_modules/undici-types/pool.d.ts new file mode 100644 index 0000000..7747d48 --- /dev/null +++ b/node_modules/undici-types/pool.d.ts @@ -0,0 +1,28 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from "./dispatcher"; + +export default Pool + +declare class Pool extends Dispatcher { + constructor(url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats; +} + +declare namespace Pool { + export type PoolStats = TPoolStats; + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + } +} diff --git a/node_modules/undici-types/proxy-agent.d.ts b/node_modules/undici-types/proxy-agent.d.ts new file mode 100644 index 0000000..96b2638 --- /dev/null +++ b/node_modules/undici-types/proxy-agent.d.ts @@ -0,0 +1,30 @@ +import Agent from './agent' +import buildConnector from './connector'; +import Client from './client' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' +import Pool from './pool' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor(options: ProxyAgent.Options | string) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + } +} diff --git a/node_modules/undici-types/readable.d.ts b/node_modules/undici-types/readable.d.ts new file mode 100644 index 0000000..4549a8c --- /dev/null +++ b/node_modules/undici-types/readable.d.ts @@ -0,0 +1,61 @@ +import { Readable } from "stream"; +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor( + resume?: (this: Readable, size: number) => void | null, + abort?: () => void | null, + contentType?: string + ) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text(): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json(): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob(): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer(): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData(): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** Throws on node 16.6.0 + * + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 262144 + */ + dump(opts?: { limit: number }): Promise +} diff --git a/node_modules/undici-types/webidl.d.ts b/node_modules/undici-types/webidl.d.ts new file mode 100644 index 0000000..40cfe06 --- /dev/null +++ b/node_modules/undici-types/webidl.d.ts @@ -0,0 +1,220 @@ +// These types are not exported, and are only used internally + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + exception (opts: { header: string, message: string }): TypeError + /** + * @description Throw an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + IntegerPart (N: number): number +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + [Key: string]: (...args: any[]) => unknown +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (cls: Interface): ( + V: unknown, + opts?: { strict: boolean } + ) => asserts V is typeof cls + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: { + header: string + message?: string + }): void +} diff --git a/node_modules/undici-types/websocket.d.ts b/node_modules/undici-types/websocket.d.ts new file mode 100644 index 0000000..15a357d --- /dev/null +++ b/node_modules/undici-types/websocket.d.ts @@ -0,0 +1,131 @@ +/// + +import type { Blob } from 'buffer' +import type { MessagePort } from 'worker_threads' +import { + EventTarget, + Event, + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: Event + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} diff --git a/node_modules/undici/LICENSE b/node_modules/undici/LICENSE new file mode 100644 index 0000000..e7323bb --- /dev/null +++ b/node_modules/undici/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Matteo Collina and Undici contributors + +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/undici/README.md b/node_modules/undici/README.md new file mode 100644 index 0000000..3ba8989 --- /dev/null +++ b/node_modules/undici/README.md @@ -0,0 +1,443 @@ +# undici + +[![Node CI](https://github.com/nodejs/undici/actions/workflows/nodejs.yml/badge.svg)](https://github.com/nodejs/undici/actions/workflows/nodejs.yml) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) [![npm version](https://badge.fury.io/js/undici.svg)](https://badge.fury.io/js/undici) [![codecov](https://codecov.io/gh/nodejs/undici/branch/main/graph/badge.svg?token=yZL6LtXkOA)](https://codecov.io/gh/nodejs/undici) + +An HTTP/1.1 client, written from scratch for Node.js. + +> Undici means eleven in Italian. 1.1 -> 11 -> Eleven -> Undici. +It is also a Stranger Things reference. + +Have a question about using Undici? Open a [Q&A Discussion](https://github.com/nodejs/undici/discussions/new) or join our official OpenJS [Slack](https://openjs-foundation.slack.com/archives/C01QF9Q31QD) channel. + +## Install + +``` +npm i undici +``` + +## Benchmarks + +The benchmark is a simple `hello world` [example](benchmarks/benchmark.js) using a +number of unix sockets (connections) with a pipelining depth of 10 running on Node 20.6.0. + +### Connections 1 + + +| Tests | Samples | Result | Tolerance | Difference with slowest | +|---------------------|---------|---------------|-----------|-------------------------| +| http - no keepalive | 15 | 5.32 req/sec | ± 2.61 % | - | +| http - keepalive | 10 | 5.35 req/sec | ± 2.47 % | + 0.44 % | +| undici - fetch | 15 | 41.85 req/sec | ± 2.49 % | + 686.04 % | +| undici - pipeline | 40 | 50.36 req/sec | ± 2.77 % | + 845.92 % | +| undici - stream | 15 | 60.58 req/sec | ± 2.75 % | + 1037.72 % | +| undici - request | 10 | 61.19 req/sec | ± 2.60 % | + 1049.24 % | +| undici - dispatch | 20 | 64.84 req/sec | ± 2.81 % | + 1117.81 % | + + +### Connections 50 + +| Tests | Samples | Result | Tolerance | Difference with slowest | +|---------------------|---------|------------------|-----------|-------------------------| +| undici - fetch | 30 | 2107.19 req/sec | ± 2.69 % | - | +| http - no keepalive | 10 | 2698.90 req/sec | ± 2.68 % | + 28.08 % | +| http - keepalive | 10 | 4639.49 req/sec | ± 2.55 % | + 120.17 % | +| undici - pipeline | 40 | 6123.33 req/sec | ± 2.97 % | + 190.59 % | +| undici - stream | 50 | 9426.51 req/sec | ± 2.92 % | + 347.35 % | +| undici - request | 10 | 10162.88 req/sec | ± 2.13 % | + 382.29 % | +| undici - dispatch | 50 | 11191.11 req/sec | ± 2.98 % | + 431.09 % | + + +## Quick Start + +```js +import { request } from 'undici' + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) +console.log('headers', headers) + +for await (const data of body) { + console.log('data', data) +} + +console.log('trailers', trailers) +``` + +## Body Mixins + +The `body` mixins are the most common way to format the request/response body. Mixins include: + +- [`.formData()`](https://fetch.spec.whatwg.org/#dom-body-formdata) +- [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +- [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) + +Example usage: + +```js +import { request } from 'undici' + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) +console.log('headers', headers) +console.log('data', await body.json()) +console.log('trailers', trailers) +``` + +_Note: Once a mixin has been called then the body cannot be reused, thus calling additional mixins on `.body`, e.g. `.body.json(); .body.text()` will result in an error `TypeError: unusable` being thrown and returned through the `Promise` rejection._ + +Should you need to access the `body` in plain-text after using a mixin, the best practice is to use the `.text()` mixin first and then manually parse the text to the desired format. + +For more information about their behavior, please reference the body mixin from the [Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). + +## Common API Methods + +This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site. + +### `undici.request([url, options]): Promise` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`RequestOptions`](./docs/api/Dispatcher.md#parameter-requestoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` + +Returns a promise with the result of the `Dispatcher.request` method. + +Calls `options.dispatcher.request(options)`. + +See [Dispatcher.request](./docs/api/Dispatcher.md#dispatcherrequestoptions-callback) for more details. + +### `undici.stream([url, options, ]factory): Promise` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`StreamOptions`](./docs/api/Dispatcher.md#parameter-streamoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` +* **factory** `Dispatcher.stream.factory` + +Returns a promise with the result of the `Dispatcher.stream` method. + +Calls `options.dispatcher.stream(options, factory)`. + +See [Dispatcher.stream](docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback) for more details. + +### `undici.pipeline([url, options, ]handler): Duplex` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`PipelineOptions`](docs/api/Dispatcher.md#parameter-pipelineoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` +* **handler** `Dispatcher.pipeline.handler` + +Returns: `stream.Duplex` + +Calls `options.dispatch.pipeline(options, handler)`. + +See [Dispatcher.pipeline](docs/api/Dispatcher.md#dispatcherpipelineoptions-handler) for more details. + +### `undici.connect([url, options]): Promise` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`ConnectOptions`](docs/api/Dispatcher.md#parameter-connectoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **maxRedirections** `Integer` - Default: `0` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns a promise with the result of the `Dispatcher.connect` method. + +Calls `options.dispatch.connect(options)`. + +See [Dispatcher.connect](docs/api/Dispatcher.md#dispatcherconnectoptions-callback) for more details. + +### `undici.fetch(input[, init]): Promise` + +Implements [fetch](https://fetch.spec.whatwg.org/#fetch-method). + +* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch +* https://fetch.spec.whatwg.org/#fetch-method + +Only supported on Node 16.8+. + +Basic usage example: + +```js +import { fetch } from 'undici' + + +const res = await fetch('https://example.com') +const json = await res.json() +console.log(json) +``` + +You can pass an optional dispatcher to `fetch` as: + +```js +import { fetch, Agent } from 'undici' + +const res = await fetch('https://example.com', { + // Mocks are also supported + dispatcher: new Agent({ + keepAliveTimeout: 10, + keepAliveMaxTimeout: 10 + }) +}) +const json = await res.json() +console.log(json) +``` + +#### `request.body` + +A body can be of the following types: + +- ArrayBuffer +- ArrayBufferView +- AsyncIterables +- Blob +- Iterables +- String +- URLSearchParams +- FormData + +In this implementation of fetch, ```request.body``` now accepts ```Async Iterables```. It is not present in the [Fetch Standard.](https://fetch.spec.whatwg.org) + +```js +import { fetch } from 'undici' + +const data = { + async *[Symbol.asyncIterator]() { + yield 'hello' + yield 'world' + }, +} + +await fetch('https://example.com', { body: data, method: 'POST', duplex: 'half' }) +``` + +#### `request.duplex` + +- half + +In this implementation of fetch, `request.duplex` must be set if `request.body` is `ReadableStream` or `Async Iterables`. And fetch requests are currently always be full duplex. More detail refer to [Fetch Standard.](https://fetch.spec.whatwg.org/#dom-requestinit-duplex) + +#### `response.body` + +Nodejs has two kinds of streams: [web streams](https://nodejs.org/dist/latest-v16.x/docs/api/webstreams.html), which follow the API of the WHATWG web standard found in browsers, and an older Node-specific [streams API](https://nodejs.org/api/stream.html). `response.body` returns a readable web stream. If you would prefer to work with a Node stream you can convert a web stream using `.fromWeb()`. + +```js +import { fetch } from 'undici' +import { Readable } from 'node:stream' + +const response = await fetch('https://example.com') +const readableWebStream = response.body +const readableNodeStream = Readable.fromWeb(readableWebStream) +``` + +#### Specification Compliance + +This section documents parts of the [Fetch Standard](https://fetch.spec.whatwg.org) that Undici does +not support or does not fully implement. + +##### Garbage Collection + +* https://fetch.spec.whatwg.org/#garbage-collection + +The [Fetch Standard](https://fetch.spec.whatwg.org) allows users to skip consuming the response body by relying on +[garbage collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management#garbage_collection) to release connection resources. Undici does not do the same. Therefore, it is important to always either consume or cancel the response body. + +Garbage collection in Node is less aggressive and deterministic +(due to the lack of clear idle periods that browsers have through the rendering refresh rate) +which means that leaving the release of connection resources to the garbage collector can lead +to excessive connection usage, reduced performance (due to less connection re-use), and even +stalls or deadlocks when running out of connections. + +```js +// Do +const headers = await fetch(url) + .then(async res => { + for await (const chunk of res.body) { + // force consumption of body + } + return res.headers + }) + +// Do not +const headers = await fetch(url) + .then(res => res.headers) +``` + +However, if you want to get only headers, it might be better to use `HEAD` request method. Usage of this method will obviate the need for consumption or cancelling of the response body. See [MDN - HTTP - HTTP request methods - HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) for more details. + +```js +const headers = await fetch(url, { method: 'HEAD' }) + .then(res => res.headers) +``` + +##### Forbidden and Safelisted Header Names + +* https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name +* https://fetch.spec.whatwg.org/#forbidden-header-name +* https://fetch.spec.whatwg.org/#forbidden-response-header-name +* https://github.com/wintercg/fetch/issues/6 + +The [Fetch Standard](https://fetch.spec.whatwg.org) requires implementations to exclude certain headers from requests and responses. In browser environments, some headers are forbidden so the user agent remains in full control over them. In Undici, these constraints are removed to give more control to the user. + +### `undici.upgrade([url, options]): Promise` + +Upgrade to a different protocol. See [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`UpgradeOptions`](docs/api/Dispatcher.md#parameter-upgradeoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **maxRedirections** `Integer` - Default: `0` +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns a promise with the result of the `Dispatcher.upgrade` method. + +Calls `options.dispatcher.upgrade(options)`. + +See [Dispatcher.upgrade](docs/api/Dispatcher.md#dispatcherupgradeoptions-callback) for more details. + +### `undici.setGlobalDispatcher(dispatcher)` + +* dispatcher `Dispatcher` + +Sets the global dispatcher used by Common API Methods. + +### `undici.getGlobalDispatcher()` + +Gets the global dispatcher used by Common API Methods. + +Returns: `Dispatcher` + +### `undici.setGlobalOrigin(origin)` + +* origin `string | URL | undefined` + +Sets the global origin used in `fetch`. + +If `undefined` is passed, the global origin will be reset. This will cause `Response.redirect`, `new Request()`, and `fetch` to throw an error when a relative path is passed. + +```js +setGlobalOrigin('http://localhost:3000') + +const response = await fetch('/api/ping') + +console.log(response.url) // http://localhost:3000/api/ping +``` + +### `undici.getGlobalOrigin()` + +Gets the global origin used in `fetch`. + +Returns: `URL` + +### `UrlObject` + +* **port** `string | number` (optional) +* **path** `string` (optional) +* **pathname** `string` (optional) +* **hostname** `string` (optional) +* **origin** `string` (optional) +* **protocol** `string` (optional) +* **search** `string` (optional) + +## Specification Compliance + +This section documents parts of the HTTP/1.1 specification that Undici does +not support or does not fully implement. + +### Expect + +Undici does not support the `Expect` request header field. The request +body is always immediately sent and the `100 Continue` response will be +ignored. + +Refs: https://tools.ietf.org/html/rfc7231#section-5.1.1 + +### Pipelining + +Undici will only use pipelining if configured with a `pipelining` factor +greater than `1`. + +Undici always assumes that connections are persistent and will immediately +pipeline requests, without checking whether the connection is persistent. +Hence, automatic fallback to HTTP/1.0 or HTTP/1.1 without pipelining is +not supported. + +Undici will immediately pipeline when retrying requests after a failed +connection. However, Undici will not retry the first remaining requests in +the prior pipeline and instead error the corresponding callback/promise/stream. + +Undici will abort all running requests in the pipeline when any of them are +aborted. + +* Refs: https://tools.ietf.org/html/rfc2616#section-8.1.2.2 +* Refs: https://tools.ietf.org/html/rfc7230#section-6.3.2 + +### Manual Redirect + +Since it is not possible to manually follow an HTTP redirect on the server-side, +Undici returns the actual response instead of an `opaqueredirect` filtered one +when invoked with a `manual` redirect. This aligns `fetch()` with the other +implementations in Deno and Cloudflare Workers. + +Refs: https://fetch.spec.whatwg.org/#atomic-http-redirect-handling + +## Workarounds + +### Network address family autoselection. + +If you experience problem when connecting to a remote server that is resolved by your DNS servers to a IPv6 (AAAA record) +first, there are chances that your local router or ISP might have problem connecting to IPv6 networks. In that case +undici will throw an error with code `UND_ERR_CONNECT_TIMEOUT`. + +If the target server resolves to both a IPv6 and IPv4 (A records) address and you are using a compatible Node version +(18.3.0 and above), you can fix the problem by providing the `autoSelectFamily` option (support by both `undici.request` +and `undici.Agent`) which will enable the family autoselection algorithm when establishing the connection. + +## Collaborators + +* [__Daniele Belardi__](https://github.com/dnlup), +* [__Ethan Arrowood__](https://github.com/ethan-arrowood), +* [__Matteo Collina__](https://github.com/mcollina), +* [__Matthew Aitken__](https://github.com/KhafraDev), +* [__Robert Nagy__](https://github.com/ronag), +* [__Szymon Marczak__](https://github.com/szmarczak), +* [__Tomas Della Vedova__](https://github.com/delvedor), + +### Releasers + +* [__Ethan Arrowood__](https://github.com/ethan-arrowood), +* [__Matteo Collina__](https://github.com/mcollina), +* [__Robert Nagy__](https://github.com/ronag), +* [__Matthew Aitken__](https://github.com/KhafraDev), + +## License + +MIT diff --git a/node_modules/undici/docs/api/Agent.md b/node_modules/undici/docs/api/Agent.md new file mode 100644 index 0000000..dd5d99b --- /dev/null +++ b/node_modules/undici/docs/api/Agent.md @@ -0,0 +1,80 @@ +# Agent + +Extends: `undici.Dispatcher` + +Agent allow dispatching requests against multiple different origins. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new undici.Agent([options])` + +Arguments: + +* **options** `AgentOptions` (optional) + +Returns: `Agent` + +### Parameter: `AgentOptions` + +Extends: [`PoolOptions`](Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` +* **maxRedirections** `Integer` - Default: `0`. The number of HTTP redirection to follow unless otherwise specified in `DispatchOptions`. +* **interceptors** `{ Agent: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. + +## Instance Properties + +### `Agent.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `Agent.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +## Instance Methods + +### `Agent.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Agent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` +* **maxRedirections** `Integer`. + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Agent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Agent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Agent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Agent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Agent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). diff --git a/node_modules/undici/docs/api/BalancedPool.md b/node_modules/undici/docs/api/BalancedPool.md new file mode 100644 index 0000000..290c734 --- /dev/null +++ b/node_modules/undici/docs/api/BalancedPool.md @@ -0,0 +1,99 @@ +# Class: BalancedPool + +Extends: `undici.Dispatcher` + +A pool of [Pool](Pool.md) instances connected to multiple upstreams. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new BalancedPool(upstreams [, options])` + +Arguments: + +* **upstreams** `URL | string | string[]` - It should only include the **protocol, hostname, and port**. +* **options** `BalancedPoolOptions` (optional) + +### Parameter: `BalancedPoolOptions` + +Extends: [`PoolOptions`](Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` + +The `PoolOptions` are passed to each of the `Pool` instances being created. +## Instance Properties + +### `BalancedPool.upstreams` + +Returns an array of upstreams that were previously added. + +### `BalancedPool.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `BalancedPool.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `BalancedPool.addUpstream(upstream)` + +Add an upstream. + +Arguments: + +* **upstream** `string` - It should only include the **protocol, hostname, and port**. + +### `BalancedPool.removeUpstream(upstream)` + +Removes an upstream that was previously addded. + +### `BalancedPool.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `BalancedPool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `BalancedPool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `BalancedPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `BalancedPool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `BalancedPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `BalancedPool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `BalancedPool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/api/CacheStorage.md b/node_modules/undici/docs/api/CacheStorage.md new file mode 100644 index 0000000..08ee99f --- /dev/null +++ b/node_modules/undici/docs/api/CacheStorage.md @@ -0,0 +1,30 @@ +# CacheStorage + +Undici exposes a W3C spec-compliant implementation of [CacheStorage](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage) and [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + +## Opening a Cache + +Undici exports a top-level CacheStorage instance. You can open a new Cache, or duplicate a Cache with an existing name, by using `CacheStorage.prototype.open`. If you open a Cache with the same name as an already-existing Cache, its list of cached Responses will be shared between both instances. + +```mjs +import { caches } from 'undici' + +const cache_1 = await caches.open('v1') +const cache_2 = await caches.open('v1') + +// Although .open() creates a new instance, +assert(cache_1 !== cache_2) +// The same Response is matched in both. +assert.deepStrictEqual(await cache_1.match('/req'), await cache_2.match('/req')) +``` + +## Deleting a Cache + +If a Cache is deleted, the cached Responses/Requests can still be used. + +```mjs +const response = await cache_1.match('/req') +await caches.delete('v1') + +await response.text() // the Response's body +``` diff --git a/node_modules/undici/docs/api/Client.md b/node_modules/undici/docs/api/Client.md new file mode 100644 index 0000000..4266838 --- /dev/null +++ b/node_modules/undici/docs/api/Client.md @@ -0,0 +1,273 @@ +# Class: Client + +Extends: `undici.Dispatcher` + +A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Client(url[, options])` + +Arguments: + +* **url** `URL | string` - Should only include the **protocol, hostname, and port**. +* **options** `ClientOptions` (optional) + +Returns: `Client` + +### Parameter: `ClientOptions` + +> ⚠️ Warning: The `H2` support is experimental. + +* **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Defaults to 10 minutes. +* **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. +* **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `1e3` - A number of milliseconds subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 1 second. +* **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. +* **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. +* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections. +* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`. +* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. +* **interceptors** `{ Client: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. +* **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. +* **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. +* **allowH2**: `boolean` - Default: `false`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. +* **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overriden by a SETTINGS remote frame. + +#### Parameter: `ConnectOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100. +* **timeout** `number | null` (optional) - In milliseconds, Default `10e3`. +* **servername** `string | null` (optional) +* **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled +* **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds + +### Example - Basic Client instantiation + +This will instantiate the undici Client, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`. + +```js +'use strict' +import { Client } from 'undici' + +const client = new Client('http://localhost:3000') +``` + +### Example - Custom connector + +This will allow you to perform some additional check on the socket that will be used for the next request. + +```js +'use strict' +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +## Instance Methods + +### `Client.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Client.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). + +### `Client.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Client.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Client.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Client.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Client.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Client.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Properties + +### `Client.closed` + +* `boolean` + +`true` after `client.close()` has been called. + +### `Client.destroyed` + +* `boolean` + +`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. + +### `Client.pipelining` + +* `number` + +Property to get and set the pipelining factor. + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +Emitted when a socket has been created and connected. The client will connect once `client.size > 0`. + +#### Example - Client connect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('connect', (origin) => { + console.log(`Connected to ${origin}`) // should print before the request body statement +}) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf-8') + body.on('data', console.log) + client.close() + server.close() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`. + +#### Example - Client disconnect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.destroy() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('disconnect', (origin) => { + console.log(`Disconnected from ${origin}`) +}) + +try { + await client.request({ + path: '/', + method: 'GET' + }) +} catch (error) { + console.error(error.message) + client.close() + server.close() +} +``` + +### Event: `'drain'` + +Emitted when pipeline is no longer busy. + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). + +#### Example - Client drain event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('drain', () => { + console.log('drain event') + client.close() + server.close() +}) + +const requests = [ + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }) +] + +await Promise.all(requests) + +console.log('requests completed') +``` + +### Event: `'error'` + +Invoked for users errors such as throwing in the `onError` handler. diff --git a/node_modules/undici/docs/api/Connector.md b/node_modules/undici/docs/api/Connector.md new file mode 100644 index 0000000..56821bd --- /dev/null +++ b/node_modules/undici/docs/api/Connector.md @@ -0,0 +1,115 @@ +# Connector + +Undici creates the underlying socket via the connector builder. +Normally, this happens automatically and you don't need to care about this, +but if you need to perform some additional check over the currently used socket, +this is the right place. + +If you want to create a custom connector, you must import the `buildConnector` utility. + +#### Parameter: `buildConnector.BuildOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: `100`. +* **timeout** `number | null` (optional) - In milliseconds. Default `10e3`. +* **servername** `string | null` (optional) + +Once you call `buildConnector`, it will return a connector function, which takes the following parameters. + +#### Parameter: `connector.Options` + +* **hostname** `string` (required) +* **host** `string` (optional) +* **protocol** `string` (required) +* **port** `string` (required) +* **servername** `string` (optional) +* **localAddress** `string | null` (optional) Local address the socket should connect from. +* **httpSocket** `Socket` (optional) Establish secure connection on a given socket rather than creating a new socket. It can only be sent on TLS update. + +### Basic example + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +### Example: validate the CA fingerprint + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const caFingerprint = 'FO:OB:AR' +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) { + socket.destroy() + cb(new Error('Fingerprint does not match or malformed certificate')) + } else { + cb(null, socket) + } + }) + } +}) + +client.request({ + path: '/', + method: 'GET' +}, (err, data) => { + if (err) throw err + + const bufs = [] + data.body.on('data', (buf) => { + bufs.push(buf) + }) + data.body.on('end', () => { + console.log(Buffer.concat(bufs).toString('utf8')) + client.close() + }) +}) + +function getIssuerCertificate (socket) { + let certificate = socket.getPeerCertificate(true) + while (certificate && Object.keys(certificate).length > 0) { + // invalid certificate + if (certificate.issuerCertificate == null) { + return null + } + + // We have reached the root certificate. + // In case of self-signed certificates, `issuerCertificate` may be a circular reference. + if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) { + break + } + + // continue the loop + certificate = certificate.issuerCertificate + } + return certificate +} +``` diff --git a/node_modules/undici/docs/api/ContentType.md b/node_modules/undici/docs/api/ContentType.md new file mode 100644 index 0000000..2bcc9f7 --- /dev/null +++ b/node_modules/undici/docs/api/ContentType.md @@ -0,0 +1,57 @@ +# MIME Type Parsing + +## `MIMEType` interface + +* **type** `string` +* **subtype** `string` +* **parameters** `Map` +* **essence** `string` + +## `parseMIMEType(input)` + +Implements [parse a MIME type](https://mimesniff.spec.whatwg.org/#parse-a-mime-type). + +Parses a MIME type, returning its type, subtype, and any associated parameters. If the parser can't parse an input it returns the string literal `'failure'`. + +```js +import { parseMIMEType } from 'undici' + +parseMIMEType('text/html; charset=gbk') +// { +// type: 'text', +// subtype: 'html', +// parameters: Map(1) { 'charset' => 'gbk' }, +// essence: 'text/html' +// } +``` + +Arguments: + +* **input** `string` + +Returns: `MIMEType|'failure'` + +## `serializeAMimeType(input)` + +Implements [serialize a MIME type](https://mimesniff.spec.whatwg.org/#serialize-a-mime-type). + +Serializes a MIMEType object. + +```js +import { serializeAMimeType } from 'undici' + +serializeAMimeType({ + type: 'text', + subtype: 'html', + parameters: new Map([['charset', 'gbk']]), + essence: 'text/html' +}) +// text/html;charset=gbk + +``` + +Arguments: + +* **mimeType** `MIMEType` + +Returns: `string` diff --git a/node_modules/undici/docs/api/Cookies.md b/node_modules/undici/docs/api/Cookies.md new file mode 100644 index 0000000..0cad379 --- /dev/null +++ b/node_modules/undici/docs/api/Cookies.md @@ -0,0 +1,101 @@ +# Cookie Handling + +## `Cookie` interface + +* **name** `string` +* **value** `string` +* **expires** `Date|number` (optional) +* **maxAge** `number` (optional) +* **domain** `string` (optional) +* **path** `string` (optional) +* **secure** `boolean` (optional) +* **httpOnly** `boolean` (optional) +* **sameSite** `'String'|'Lax'|'None'` (optional) +* **unparsed** `string[]` (optional) Left over attributes that weren't parsed. + +## `deleteCookie(headers, name[, attributes])` + +Sets the expiry time of the cookie to the unix epoch, causing browsers to delete it when received. + +```js +import { deleteCookie, Headers } from 'undici' + +const headers = new Headers() +deleteCookie(headers, 'name') + +console.log(headers.get('set-cookie')) // name=; Expires=Thu, 01 Jan 1970 00:00:00 GMT +``` + +Arguments: + +* **headers** `Headers` +* **name** `string` +* **attributes** `{ path?: string, domain?: string }` (optional) + +Returns: `void` + +## `getCookies(headers)` + +Parses the `Cookie` header and returns a list of attributes and values. + +```js +import { getCookies, Headers } from 'undici' + +const headers = new Headers({ + cookie: 'get=cookies; and=attributes' +}) + +console.log(getCookies(headers)) // { get: 'cookies', and: 'attributes' } +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Record` + +## `getSetCookies(headers)` + +Parses all `Set-Cookie` headers. + +```js +import { getSetCookies, Headers } from 'undici' + +const headers = new Headers({ 'set-cookie': 'undici=getSetCookies; Secure' }) + +console.log(getSetCookies(headers)) +// [ +// { +// name: 'undici', +// value: 'getSetCookies', +// secure: true +// } +// ] + +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Cookie[]` + +## `setCookie(headers, cookie)` + +Appends a cookie to the `Set-Cookie` header. + +```js +import { setCookie, Headers } from 'undici' + +const headers = new Headers() +setCookie(headers, { name: 'undici', value: 'setCookie' }) + +console.log(headers.get('Set-Cookie')) // undici=setCookie +``` + +Arguments: + +* **headers** `Headers` +* **cookie** `Cookie` + +Returns: `void` diff --git a/node_modules/undici/docs/api/DiagnosticsChannel.md b/node_modules/undici/docs/api/DiagnosticsChannel.md new file mode 100644 index 0000000..0aa0b9a --- /dev/null +++ b/node_modules/undici/docs/api/DiagnosticsChannel.md @@ -0,0 +1,204 @@ +# Diagnostics Channel Support + +Stability: Experimental. + +Undici supports the [`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html) (currently available only on Node.js v16+). +It is the preferred way to instrument Undici and retrieve internal information. + +The channels available are the following. + +## `undici:request:create` + +This message is published when a new outgoing request is created. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:create').subscribe(({ request }) => { + console.log('origin', request.origin) + console.log('completed', request.completed) + console.log('method', request.method) + console.log('path', request.path) + console.log('headers') // raw text, e.g: 'bar: bar\r\n' + request.addHeader('hello', 'world') + console.log('headers', request.headers) // e.g. 'bar: bar\r\nhello: world\r\n' +}) +``` + +Note: a request is only loosely completed to a given socket. + + +## `undici:request:bodySent` + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodySent').subscribe(({ request }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:headers` + +This message is published after the response headers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:headers').subscribe(({ request, response }) => { + // request is the same object undici:request:create + console.log('statusCode', response.statusCode) + console.log(response.statusText) + // response.headers are buffers. + console.log(response.headers.map((x) => x.toString())) +}) +``` + +## `undici:request:trailers` + +This message is published after the response body and trailers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:trailers').subscribe(({ request, trailers }) => { + // request is the same object undici:request:create + console.log('completed', request.completed) + // trailers are buffers. + console.log(trailers.map((x) => x.toString())) +}) +``` + +## `undici:request:error` + +This message is published if the request is going to error, but it has not errored yet. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:error').subscribe(({ request, error }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:client:sendHeaders` + +This message is published right before the first byte of the request is written to the socket. + +*Note*: It will publish the exact headers that will be sent to the server in raw format. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(({ request, headers, socket }) => { + // request is the same object undici:request:create + console.log(`Full headers list ${headers.split('\r\n')}`); +}) +``` + +## `undici:client:beforeConnect` + +This message is published before creating a new connection for **any** request. +You can not assume that this event is related to any specific request. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(({ connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connected` + +This message is published after a connection is established. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connected').subscribe(({ socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connectError` + +This message is published if it did not succeed to create new connection + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connectError').subscribe(({ error, socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket + console.log(`Connect failed with ${error.message}`) +}) +``` + +## `undici:websocket:open` + +This message is published after the client has successfully connected to a server. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:open').subscribe(({ address, protocol, extensions }) => { + console.log(address) // address, family, and port + console.log(protocol) // negotiated subprotocols + console.log(extensions) // negotiated extensions +}) +``` + +## `undici:websocket:close` + +This message is published after the connection has closed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:close').subscribe(({ websocket, code, reason }) => { + console.log(websocket) // the WebSocket object + console.log(code) // the closing status code + console.log(reason) // the closing reason +}) +``` + +## `undici:websocket:socket_error` + +This message is published if the socket experiences an error. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:socket_error').subscribe((error) => { + console.log(error) +}) +``` + +## `undici:websocket:ping` + +This message is published after the client receives a ping frame, if the connection is not closing. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:ping').subscribe(({ payload }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) +}) +``` + +## `undici:websocket:pong` + +This message is published after the client receives a pong frame. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:pong').subscribe(({ payload }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) +}) +``` diff --git a/node_modules/undici/docs/api/DispatchInterceptor.md b/node_modules/undici/docs/api/DispatchInterceptor.md new file mode 100644 index 0000000..7dfc260 --- /dev/null +++ b/node_modules/undici/docs/api/DispatchInterceptor.md @@ -0,0 +1,60 @@ +# Interface: DispatchInterceptor + +Extends: `Function` + +A function that can be applied to the `Dispatcher.Dispatch` function before it is invoked with a dispatch request. + +This allows one to write logic to intercept both the outgoing request, and the incoming response. + +### Parameter: `Dispatcher.Dispatch` + +The base dispatch function you are decorating. + +### ReturnType: `Dispatcher.Dispatch` + +A dispatch function that has been altered to provide additional logic + +### Basic Example + +Here is an example of an interceptor being used to provide a JWT bearer token + +```js +'use strict' + +const insertHeaderInterceptor = dispatch => { + return function InterceptedDispatch(opts, handler){ + opts.headers.push('Authorization', 'Bearer [Some token]') + return dispatch(opts, handler) + } +} + +const client = new Client('https://localhost:3000', { + interceptors: { Client: [insertHeaderInterceptor] } +}) + +``` + +### Basic Example 2 + +Here is a contrived example of an interceptor stripping the headers from a response. + +```js +'use strict' + +const clearHeadersInterceptor = dispatch => { + const { DecoratorHandler } = require('undici') + class ResultInterceptor extends DecoratorHandler { + onHeaders (statusCode, headers, resume) { + return super.onHeaders(statusCode, [], resume) + } + } + return function InterceptedDispatch(opts, handler){ + return dispatch(opts, new ResultInterceptor(handler)) + } +} + +const client = new Client('https://localhost:3000', { + interceptors: { Client: [clearHeadersInterceptor] } +}) + +``` diff --git a/node_modules/undici/docs/api/Dispatcher.md b/node_modules/undici/docs/api/Dispatcher.md new file mode 100644 index 0000000..fd463bf --- /dev/null +++ b/node_modules/undici/docs/api/Dispatcher.md @@ -0,0 +1,887 @@ +# Dispatcher + +Extends: `events.EventEmitter` + +Dispatcher is the core API used to dispatch requests. + +Requests are not guaranteed to be dispatched in order of invocation. + +## Instance Methods + +### `Dispatcher.close([callback]): Promise` + +Closes the dispatcher and gracefully waits for enqueued requests to complete before resolving. + +Arguments: + +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.close() // -> Promise +dispatcher.close(() => {}) // -> void +``` + +#### Example - Request resolves before Client closes + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('undici') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf8') + body.on('data', console.log) +} catch (error) {} + +await client.close() + +console.log('Client closed') +server.close() +``` + +### `Dispatcher.connect(options[, callback])` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **options** `ConnectOptions` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `ConnectOptions` + +* **path** `string` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null` +* **opaque** `unknown` (optional) - This argument parameter is passed through to `ConnectData` + +#### Parameter: `ConnectData` + +* **statusCode** `number` +* **headers** `Record` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example - Connect request with echo + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + throw Error('should never get here') +}).listen() + +server.on('connect', (req, socket, head) => { + socket.write('HTTP/1.1 200 Connection established\r\n\r\n') + + let data = head.toString() + socket.on('data', (buf) => { + data += buf.toString() + }) + + socket.on('end', () => { + socket.end(data) + }) +}) + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { socket } = await client.connect({ + path: '/' + }) + const wanted = 'Body' + let data = '' + socket.on('data', d => { data += d }) + socket.on('end', () => { + console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) + client.close() + server.close() + }) + socket.write(wanted) + socket.end() +} catch (error) { } +``` + +### `Dispatcher.destroy([error, callback]): Promise` + +Destroy the dispatcher abruptly with the given error. All the pending and running requests will be asynchronously aborted and error. Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. + +Both arguments are optional; the method can be called in four different ways: + +Arguments: + +* **error** `Error | null` (optional) +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.destroy() // -> Promise +dispatcher.destroy(new Error()) // -> Promise +dispatcher.destroy(() => {}) // -> void +dispatcher.destroy(new Error(), () => {}) // -> void +``` + +#### Example - Request is aborted when Client is destroyed + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const request = client.request({ + path: '/', + method: 'GET' + }) + client.destroy() + .then(() => { + console.log('Client destroyed') + server.close() + }) + await request +} catch (error) { + console.error(error) +} +``` + +### `Dispatcher.dispatch(options, handler)` + +This is the low level API which all the preceding APIs are implemented on top of. +This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. +It is primarily intended for library developers who implement higher level APIs on top of this. + +Arguments: + +* **options** `DispatchOptions` +* **handler** `DispatchHandler` + +Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls won't make any progress until the `'drain'` event has been emitted. + +#### Parameter: `DispatchOptions` + +* **origin** `string | URL` +* **path** `string` +* **method** `string` +* **reset** `boolean` (optional) - Default: `false` - If `false`, the request will attempt to create a long-living connection by sending the `connection: keep-alive` header,otherwise will attempt to close it immediately after response by sending `connection: close` within the request and closing the socket afterwards. +* **body** `string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null` (optional) - Default: `null` +* **headers** `UndiciHeaders | string[]` (optional) - Default: `null`. +* **query** `Record | null` (optional) - Default: `null` - Query string params to be embedded in the request URL. Note that both keys and values of query are encoded using `encodeURIComponent`. If for some reason you need to send them unencoded, embed query params into path directly instead. +* **idempotent** `boolean` (optional) - Default: `true` if `method` is `'HEAD'` or `'GET'` - Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline has completed. +* **blocking** `boolean` (optional) - Default: `false` - Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. +* **upgrade** `string | null` (optional) - Default: `null` - Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. +* **bodyTimeout** `number | null` (optional) - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **throwOnError** `boolean` (optional) - Default: `false` - Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. +* **expectContinue** `boolean` (optional) - Default: `false` - For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server + +#### Parameter: `DispatchHandler` + +* **onConnect** `(abort: () => void, context: object) => void` - Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. +* **onError** `(error: Error) => void` - Invoked when an error has occurred. May not throw. +* **onUpgrade** `(statusCode: number, headers: Buffer[], socket: Duplex) => void` (optional) - Invoked when request is upgraded. Required if `DispatchOptions.upgrade` is defined or `DispatchOptions.method === 'CONNECT'`. +* **onHeaders** `(statusCode: number, headers: Buffer[], resume: () => void, statusText: string) => boolean` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests. +* **onData** `(chunk: Buffer) => boolean` - Invoked when response payload data is received. Not required for `upgrade` requests. +* **onComplete** `(trailers: Buffer[]) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests. +* **onBodySent** `(chunk: string | Buffer | Uint8Array) => void` - Invoked when a body chunk is sent to the server. Not required. For a stream or iterable body this will be invoked for every chunk. For other body types, it will be invoked once after the body is sent. + +#### Example 1 - Dispatch GET request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'GET', + headers: { + 'x-foo': 'bar' + } +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Data: ${res}`) + client.close() + server.close() + } +}) +``` + +#### Example 2 - Dispatch Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +server.on('upgrade', (request, socket, head) => { + console.log('Node.js Server - upgrade event') + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n') + socket.write('Upgrade: WebSocket\r\n') + socket.write('Connection: Upgrade\r\n') + socket.write('\r\n') + socket.end() +}) + +const client = new Client(`http://localhost:${server.address().port}`) + +client.dispatch({ + path: '/', + method: 'GET', + upgrade: 'websocket' +}, { + onConnect: () => { + console.log('Undici Client - onConnect') + }, + onError: (error) => { + console.log('onError') // shouldn't print + }, + onUpgrade: (statusCode, headers, socket) => { + console.log('Undici Client - onUpgrade') + console.log(`onUpgrade Headers: ${headers}`) + socket.on('data', buffer => { + console.log(buffer.toString('utf8')) + }) + socket.on('end', () => { + client.close() + server.close() + }) + socket.end() + } +}) +``` + +#### Example 3 - Dispatch POST request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.on('data', (data) => { + console.log(`Request Data: ${data.toString('utf8')}`) + const body = JSON.parse(data) + body.message = 'World' + response.end(JSON.stringify(body)) + }) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify({ message: 'Hello' }) +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Response Data: ${res}`) + client.close() + server.close() + } +}) +``` + +### `Dispatcher.pipeline(options, handler)` + +For easy use with [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback). The `handler` argument should return a `Readable` from which the result will be read. Usually it should just return the `body` argument unless some kind of transformation needs to be performed based on e.g. `headers` or `statusCode`. The `handler` should validate the response and save any required state. If there is an error, it should be thrown. The function returns a `Duplex` which writes to the request and reads from the response. + +Arguments: + +* **options** `PipelineOptions` +* **handler** `(data: PipelineHandlerData) => stream.Readable` + +Returns: `stream.Duplex` + +#### Parameter: PipelineOptions + +Extends: [`RequestOptions`](#parameter-requestoptions) + +* **objectMode** `boolean` (optional) - Default: `false` - Set to `true` if the `handler` will return an object stream. + +#### Parameter: PipelineHandlerData + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **body** `stream.Readable` +* **context** `object` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Example 1 - Pipeline Echo + +```js +import { Readable, Writable, PassThrough, pipeline } from 'stream' +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.pipe(response) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +let res = '' + +pipeline( + new Readable({ + read () { + this.push(Buffer.from('undici')) + this.push(null) + } + }), + client.pipeline({ + path: '/', + method: 'GET' + }, ({ statusCode, headers, body }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return pipeline(body, new PassThrough(), () => {}) + }), + new Writable({ + write (chunk, _, callback) { + res += chunk.toString() + callback() + }, + final (callback) { + console.log(`Response pipelined to writable: ${res}`) + callback() + } + }), + error => { + if (error) { + console.error(error) + } + + client.close() + server.close() + } +) +``` + +### `Dispatcher.request(options[, callback])` + +Performs a HTTP request. + +Non-idempotent requests will not be pipelined in order +to avoid indirect failures. + +Idempotent requests will be automatically retried if +they fail due to indirect failure from the request +at the head of the pipeline. This does not apply to +idempotent requests with a stream request body. + +All response bodies must always be fully consumed or destroyed. + +Arguments: + +* **options** `RequestOptions` +* **callback** `(error: Error | null, data: ResponseData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed. + +#### Parameter: `RequestOptions` + +Extends: [`DispatchOptions`](#parameter-dispatchoptions) + +* **opaque** `unknown` (optional) - Default: `null` - Used for passing through context to `ResponseData`. +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null`. +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +The `RequestOptions.method` property should not be value `'CONNECT'`. + +#### Parameter: `ResponseData` + +* **statusCode** `number` +* **headers** `Record` - Note that all header keys are lower-cased, e. g. `content-type`. +* **body** `stream.Readable` which also implements [the body mixin from the Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). +* **trailers** `Record` - This object starts out + as empty and will be mutated to contain trailers after `body` has emitted `'end'`. +* **opaque** `unknown` +* **context** `object` + +`body` contains the following additional [body mixin](https://fetch.spec.whatwg.org/#body-mixin) methods and properties: + +- `text()` +- `json()` +- `arrayBuffer()` +- `body` +- `bodyUsed` + +`body` can not be consumed twice. For example, calling `text()` after `json()` throws `TypeError`. + +`body` contains the following additional extensions: + +- `dump({ limit: Integer })`, dump the response by reading up to `limit` bytes without killing the socket (optional) - Default: 262144. + +Note that body will still be a `Readable` even if it is empty, but attempting to deserialize it with `json()` will result in an exception. Recommended way to ensure there is a body to deserialize is to check if status code is not 204, and `content-type` header starts with `application/json`. + +#### Example 1 - Basic GET Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body, headers, statusCode, trailers } = await client.request({ + path: '/', + method: 'GET' + }) + console.log(`response received ${statusCode}`) + console.log('headers', headers) + body.setEncoding('utf8') + body.on('data', console.log) + body.on('end', () => { + console.log('trailers', trailers) + }) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Aborting a request + +> Node.js v15+ is required to run this example + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const abortController = new AbortController() + +try { + client.request({ + path: '/', + method: 'GET', + signal: abortController.signal + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +abortController.abort() +``` + +Alternatively, any `EventEmitter` that emits an `'abort'` event may be used as an abort controller: + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import EventEmitter, { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const ee = new EventEmitter() + +try { + client.request({ + path: '/', + method: 'GET', + signal: ee + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +ee.emit('abort') +``` + +Destroying the request or response body will have the same effect. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.destroy() +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} +``` + +### `Dispatcher.stream(options, factory[, callback])` + +A faster version of `Dispatcher.request`. This method expects the second argument `factory` to return a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream which the response will be written to. This improves performance by avoiding creating an intermediate [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams) stream when the user expects to directly pipe the response body to a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream. + +As demonstrated in [Example 1 - Basic GET stream request](#example-1---basic-get-stream-request), it is recommended to use the `option.opaque` property to avoid creating a closure for the `factory` method. This pattern works well with Node.js Web Frameworks such as [Fastify](https://fastify.io). See [Example 2 - Stream to Fastify Response](#example-2---stream-to-fastify-response) for more details. + +Arguments: + +* **options** `RequestOptions` +* **factory** `(data: StreamFactoryData) => stream.Writable` +* **callback** `(error: Error | null, data: StreamData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `StreamFactoryData` + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Parameter: `StreamData` + +* **opaque** `unknown` +* **trailers** `Record` +* **context** `object` + +#### Example 1 - Basic GET stream request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import { Writable } from 'stream' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const bufs = [] + +try { + await client.stream({ + path: '/', + method: 'GET', + opaque: { bufs } + }, ({ statusCode, headers, opaque: { bufs } }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return new Writable({ + write (chunk, encoding, callback) { + bufs.push(chunk) + callback() + } + }) + }) + + console.log(Buffer.concat(bufs).toString('utf-8')) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Stream to Fastify Response + +In this example, a (fake) request is made to the fastify server using `fastify.inject()`. This request then executes the fastify route handler which makes a subsequent request to the raw Node.js http server using `undici.dispatcher.stream()`. The fastify response is passed to the `opaque` option so that undici can tap into the underlying writable stream using `response.raw`. This methodology demonstrates how one could use undici and fastify together to create fast-as-possible requests from one backend server to another. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import fastify from 'fastify' + +const nodeServer = createServer((request, response) => { + response.end('Hello, World! From Node.js HTTP Server') +}).listen() + +await once(nodeServer, 'listening') + +console.log('Node Server listening') + +const nodeServerUndiciClient = new Client(`http://localhost:${nodeServer.address().port}`) + +const fastifyServer = fastify() + +fastifyServer.route({ + url: '/', + method: 'GET', + handler: (request, response) => { + nodeServerUndiciClient.stream({ + path: '/', + method: 'GET', + opaque: response + }, ({ opaque }) => opaque.raw) + } +}) + +await fastifyServer.listen() + +console.log('Fastify Server listening') + +const fastifyServerUndiciClient = new Client(`http://localhost:${fastifyServer.server.address().port}`) + +try { + const { statusCode, body } = await fastifyServerUndiciClient.request({ + path: '/', + method: 'GET' + }) + + console.log(`response received ${statusCode}`) + body.setEncoding('utf8') + body.on('data', console.log) + + nodeServerUndiciClient.close() + fastifyServerUndiciClient.close() + fastifyServer.close() + nodeServer.close() +} catch (error) { } +``` + +### `Dispatcher.upgrade(options[, callback])` + +Upgrade to a different protocol. Visit [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **options** `UpgradeOptions` + +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `UpgradeOptions` + +* **path** `string` +* **method** `string` (optional) - Default: `'GET'` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **protocol** `string` (optional) - Default: `'Websocket'` - A string of comma separated protocols, in descending preference order. +* **signal** `AbortSignal | EventEmitter | null` (optional) - Default: `null` + +#### Parameter: `UpgradeData` + +* **headers** `http.IncomingHeaders` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example 1 - Basic Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.statusCode = 101 + response.setHeader('connection', 'upgrade') + response.setHeader('upgrade', request.headers.upgrade) + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { headers, socket } = await client.upgrade({ + path: '/', + }) + socket.on('end', () => { + console.log(`upgrade: ${headers.upgrade}`) // upgrade: Websocket + client.close() + server.close() + }) + socket.end() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +## Instance Events + +### Event: `'connect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +### Event: `'disconnect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +### Event: `'connectionError'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when dispatcher fails to connect to +origin. + +### Event: `'drain'` + +Parameters: + +* **origin** `URL` + +Emitted when dispatcher is no longer busy. + +## Parameter: `UndiciHeaders` + +* `Record | string[] | null` + +Header arguments such as `options.headers` in [`Client.dispatch`](Client.md#clientdispatchoptions-handlers) can be specified in two forms; either as an object specified by the `Record` (`IncomingHttpHeaders`) type, or an array of strings. An array representation of a header list must have an even length or an `InvalidArgumentError` will be thrown. + +Keys are lowercase and values are not modified. + +Response headers will derive a `host` from the `url` of the [Client](Client.md#class-client) instance if no `host` header was previously specified. + +### Example 1 - Object + +```js +{ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +} +``` + +### Example 2 - Array + +```js +[ + 'content-length', '123', + 'content-type', 'text/plain', + 'connection', 'keep-alive', + 'host', 'mysite.com', + 'accept', '*/*' +] +``` diff --git a/node_modules/undici/docs/api/Errors.md b/node_modules/undici/docs/api/Errors.md new file mode 100644 index 0000000..917e45d --- /dev/null +++ b/node_modules/undici/docs/api/Errors.md @@ -0,0 +1,47 @@ +# Errors + +Undici exposes a variety of error objects that you can use to enhance your error handling. +You can find all the error objects inside the `errors` key. + +```js +import { errors } from 'undici' +``` + +| Error | Error Codes | Description | +| ------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------- | +| `UndiciError` | `UND_ERR` | all errors below are extended from `UndiciError`. | +| `ConnectTimeoutError` | `UND_ERR_CONNECT_TIMEOUT` | socket is destroyed due to connect timeout. | +| `HeadersTimeoutError` | `UND_ERR_HEADERS_TIMEOUT` | socket is destroyed due to headers timeout. | +| `HeadersOverflowError` | `UND_ERR_HEADERS_OVERFLOW` | socket is destroyed due to headers' max size being exceeded. | +| `BodyTimeoutError` | `UND_ERR_BODY_TIMEOUT` | socket is destroyed due to body timeout. | +| `ResponseStatusCodeError` | `UND_ERR_RESPONSE_STATUS_CODE` | an error is thrown when `throwOnError` is `true` for status codes >= 400. | +| `InvalidArgumentError` | `UND_ERR_INVALID_ARG` | passed an invalid argument. | +| `InvalidReturnValueError` | `UND_ERR_INVALID_RETURN_VALUE` | returned an invalid value. | +| `RequestAbortedError` | `UND_ERR_ABORTED` | the request has been aborted by the user | +| `ClientDestroyedError` | `UND_ERR_DESTROYED` | trying to use a destroyed client. | +| `ClientClosedError` | `UND_ERR_CLOSED` | trying to use a closed client. | +| `SocketError` | `UND_ERR_SOCKET` | there is an error with the socket. | +| `NotSupportedError` | `UND_ERR_NOT_SUPPORTED` | encountered unsupported functionality. | +| `RequestContentLengthMismatchError` | `UND_ERR_REQ_CONTENT_LENGTH_MISMATCH` | request body does not match content-length header | +| `ResponseContentLengthMismatchError` | `UND_ERR_RES_CONTENT_LENGTH_MISMATCH` | response body does not match content-length header | +| `InformationalError` | `UND_ERR_INFO` | expected error with reason | +| `ResponseExceededMaxSizeError` | `UND_ERR_RES_EXCEEDED_MAX_SIZE` | response body exceed the max size allowed | + +### `SocketError` + +The `SocketError` has a `.socket` property which holds socket metadata: + +```ts +interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number +} +``` + +Be aware that in some cases the `.socket` property can be `null`. diff --git a/node_modules/undici/docs/api/Fetch.md b/node_modules/undici/docs/api/Fetch.md new file mode 100644 index 0000000..b5a6242 --- /dev/null +++ b/node_modules/undici/docs/api/Fetch.md @@ -0,0 +1,27 @@ +# Fetch + +Undici exposes a fetch() method starts the process of fetching a resource from the network. + +Documentation and examples can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch). + +## File + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/File) + +In Node versions v18.13.0 and above and v19.2.0 and above, undici will default to using Node's [File](https://nodejs.org/api/buffer.html#class-file) class. In versions where it's not available, it will default to the undici one. + +## FormData + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FormData) + +## Response + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response) + +## Request + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request) + +## Header + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Headers) diff --git a/node_modules/undici/docs/api/MockAgent.md b/node_modules/undici/docs/api/MockAgent.md new file mode 100644 index 0000000..85ae690 --- /dev/null +++ b/node_modules/undici/docs/api/MockAgent.md @@ -0,0 +1,540 @@ +# Class: MockAgent + +Extends: `undici.Dispatcher` + +A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. + +## `new MockAgent([options])` + +Arguments: + +* **options** `MockAgentOptions` (optional) - It extends the `Agent` options. + +Returns: `MockAgent` + +### Parameter: `MockAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **agent** `Agent` (optional) - Default: `new Agent([options])` - a custom agent encapsulated by the MockAgent. + +### Example - Basic MockAgent instantiation + +This will instantiate the MockAgent. It will not do anything until registered as the agent to use with requests and mock interceptions are added. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +``` + +### Example - Basic MockAgent instantiation with custom agent + +```js +import { Agent, MockAgent } from 'undici' + +const agent = new Agent() + +const mockAgent = new MockAgent({ agent }) +``` + +## Instance Methods + +### `MockAgent.get(origin)` + +This method creates and retrieves MockPool or MockClient instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. + +For subsequent `MockAgent.get` calls on the same origin, the same mock instance will be returned. + +Arguments: + +* **origin** `string | RegExp | (value) => boolean` - a matcher for the pool origin to be retrieved from the MockAgent. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Returns: `MockClient | MockPool`. + +| `MockAgentOptions` | Mock instance returned | +| -------------------- | ---------------------- | +| `connections === 1` | `MockClient` | +| `connections` > `1` | `MockPool` | + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock agent dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock pool dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockPool }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock client dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockClient }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') +mockPool.intercept({ path: '/hello'}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` +#### Example - Mock different requests within the same file +```js +const { MockAgent, setGlobalDispatcher } = require('undici'); +const agent = new MockAgent(); +agent.disableNetConnect(); +setGlobalDispatcher(agent); +describe('Test', () => { + it('200', async () => { + const mockAgent = agent.get('http://test.com'); + // your test + }); + it('200', async () => { + const mockAgent = agent.get('http://testing.com'); + // your test + }); +}); +``` + +#### Example - Mocked request with query body, headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2' +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2' +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request with origin regex + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get(new RegExp('http://localhost:3000')) +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with origin function + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get((origin) => origin === 'http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.close()` + +Closes the mock agent and waits for registered mock pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +await mockAgent.close() +``` + +### `MockAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](Agent.md#parameter-agentdispatchoptions). + +### `MockAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockAgent request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockAgent.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.deactivate()` + +This method disables mocking in MockAgent. + +Returns: `void` + +#### Example - Deactivate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +``` + +### `MockAgent.activate()` + +This method enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. + +Returns: `void` + +#### Example - Activate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +// No mocking will occur + +// Later +mockAgent.activate() +``` + +### `MockAgent.enableNetConnect([host])` + +When requests are not matched in a MockAgent intercept, a real HTTP request is attempted. We can control this further through the use of `enableNetConnect`. This is achieved by defining host matchers so only matching requests will be attempted. + +When using a string, it should only include the **hostname and optionally, the port**. In addition, calling this method multiple times with a string will allow all HTTP requests that match these values. + +Arguments: + +* **host** `string | RegExp | (value) => boolean` - (optional) + +Returns: `void` + +#### Example - Allow all non-matching urls to be dispatched in a real HTTP request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect() + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host string to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect('example-1.com') +mockAgent.enableNetConnect('example-2.com:8080') + +await request('http://example-1.com') +// A real request is made + +await request('http://example-2.com:8080') +// A real request is made + +await request('http://example-3.com') +// Will throw +``` + +#### Example - Allow requests matching a host regex to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect(new RegExp('example.com')) + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host function to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect((value) => value === 'example.com') + +await request('http://example.com') +// A real request is made +``` + +### `MockAgent.disableNetConnect()` + +This method causes all requests to throw when requests are not matched in a MockAgent intercept. + +Returns: `void` + +#### Example - Disable all non-matching requests by throwing an error for each + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +mockAgent.disableNetConnect() + +await request('http://example.com') +// Will throw +``` + +### `MockAgent.pendingInterceptors()` + +This method returns any pending interceptors registered on a mock agent. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +Returns: `PendingInterceptor[]` (where `PendingInterceptor` is a `MockDispatch` with an additional `origin: string`) + +#### Example - List all pending inteceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +const pendingInterceptors = agent.pendingInterceptors() +// Returns [ +// { +// timesInvoked: 0, +// times: 1, +// persist: false, +// consumed: false, +// pending: true, +// path: '/', +// method: 'GET', +// body: undefined, +// headers: undefined, +// data: { +// error: null, +// statusCode: 200, +// data: '', +// headers: {}, +// trailers: {} +// }, +// origin: 'https://example.com' +// } +// ] +``` + +### `MockAgent.assertNoPendingInterceptors([options])` + +This method throws if the mock agent has any pending interceptors. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +#### Example - Check that there are no pending interceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +agent.assertNoPendingInterceptors() +// Throws an UndiciError with the following message: +// +// 1 interceptor is pending: +// +// ┌─────────┬────────┬───────────────────────┬──────┬─────────────┬────────────┬─────────────┬───────────┐ +// │ (index) │ Method │ Origin │ Path │ Status code │ Persistent │ Invocations │ Remaining │ +// ├─────────┼────────┼───────────────────────┼──────┼─────────────┼────────────┼─────────────┼───────────┤ +// │ 0 │ 'GET' │ 'https://example.com' │ '/' │ 200 │ '❌' │ 0 │ 1 │ +// └─────────┴────────┴───────────────────────┴──────┴─────────────┴────────────┴─────────────┴───────────┘ +``` diff --git a/node_modules/undici/docs/api/MockClient.md b/node_modules/undici/docs/api/MockClient.md new file mode 100644 index 0000000..ac54691 --- /dev/null +++ b/node_modules/undici/docs/api/MockClient.md @@ -0,0 +1,77 @@ +# Class: MockClient + +Extends: `undici.Client` + +A mock client class that implements the same api as [MockPool](MockPool.md). + +## `new MockClient(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockClientOptions` - It extends the `Client` options. + +Returns: `MockClient` + +### Parameter: `MockClientOptions` + +Extends: `ClientOptions` + +* **agent** `Agent` - the agent to associate this MockClient with. + +### Example - Basic MockClient instantiation + +We can use MockAgent to instantiate a MockClient ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +// Connections must be set to 1 to return a MockClient instance +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockClient.intercept(options)` + +Implements: [`MockPool.intercept(options)`](MockPool.md#mockpoolinterceptoptions) + +### `MockClient.close()` + +Implements: [`MockPool.close()`](MockPool.md#mockpoolclose) + +### `MockClient.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockClient.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockClient request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockClient.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/api/MockErrors.md b/node_modules/undici/docs/api/MockErrors.md new file mode 100644 index 0000000..c1aa3db --- /dev/null +++ b/node_modules/undici/docs/api/MockErrors.md @@ -0,0 +1,12 @@ +# MockErrors + +Undici exposes a variety of mock error objects that you can use to enhance your mock error handling. +You can find all the mock error objects inside the `mockErrors` key. + +```js +import { mockErrors } from 'undici' +``` + +| Mock Error | Mock Error Codes | Description | +| --------------------- | ------------------------------- | ---------------------------------------------------------- | +| `MockNotMatchedError` | `UND_MOCK_ERR_MOCK_NOT_MATCHED` | The request does not match any registered mock dispatches. | diff --git a/node_modules/undici/docs/api/MockPool.md b/node_modules/undici/docs/api/MockPool.md new file mode 100644 index 0000000..de53914 --- /dev/null +++ b/node_modules/undici/docs/api/MockPool.md @@ -0,0 +1,513 @@ +# Class: MockPool + +Extends: `undici.Pool` + +A mock Pool class that implements the Pool API and is used by MockAgent to intercept real requests and return mocked responses. + +## `new MockPool(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockPoolOptions` - It extends the `Pool` options. + +Returns: `MockPool` + +### Parameter: `MockPoolOptions` + +Extends: `PoolOptions` + +* **agent** `Agent` - the agent to associate this MockPool with. + +### Example - Basic MockPool instantiation + +We can use MockAgent to instantiate a MockPool ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockPool.intercept(options)` + +This method defines the interception rules for matching against requests for a MockPool or MockPool. We can intercept multiple times on a single instance, but each intercept is only used once. +For example if you expect to make 2 requests inside a test, you need to call `intercept()` twice. Assuming you use `disableNetConnect()` you will get `MockNotMatchedError` on the second request when you only call `intercept()` once. + +When defining interception rules, all the rules must pass for a request to be intercepted. If a request is not intercepted, a real request will be attempted. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Arguments: + +* **options** `MockPoolInterceptOptions` - Interception options. + +Returns: `MockInterceptor` corresponding to the input options. + +### Parameter: `MockPoolInterceptOptions` + +* **path** `string | RegExp | (path: string) => boolean` - a matcher for the HTTP request path. +* **method** `string | RegExp | (method: string) => boolean` - (optional) - a matcher for the HTTP request method. Defaults to `GET`. +* **body** `string | RegExp | (body: string) => boolean` - (optional) - a matcher for the HTTP request body. +* **headers** `Record boolean`> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way. +* **query** `Record | null` - (optional) - a matcher for the HTTP request query string params. + +### Return: `MockInterceptor` + +We can define the behaviour of an intercepted request with the following options. + +* **reply** `(statusCode: number, replyData: string | Buffer | object | MockInterceptor.MockResponseDataHandler, responseOptions?: MockResponseOptions) => MockScope` - define a reply for a matching request. You can define the replyData as a callback to read incoming request data. Default for `responseOptions` is `{}`. +* **reply** `(callback: MockInterceptor.MockReplyOptionsCallback) => MockScope` - define a reply for a matching request, allowing dynamic mocking of all reply options rather than just the data. +* **replyWithError** `(error: Error) => MockScope` - define an error for a matching request to throw. +* **defaultReplyHeaders** `(headers: Record) => MockInterceptor` - define default headers to be included in subsequent replies. These are in addition to headers on a specific reply. +* **defaultReplyTrailers** `(trailers: Record) => MockInterceptor` - define default trailers to be included in subsequent replies. These are in addition to trailers on a specific reply. +* **replyContentLength** `() => MockInterceptor` - define automatically calculated `content-length` headers to be included in subsequent replies. + +The reply data of an intercepted request may either be a string, buffer, or JavaScript object. Objects are converted to JSON while strings and buffers are sent as-is. + +By default, `reply` and `replyWithError` define the behaviour for the first matching request only. Subsequent requests will not be affected (this can be changed using the returned `MockScope`). + +### Parameter: `MockResponseOptions` + +* **headers** `Record` - headers to be included on the mocked reply. +* **trailers** `Record` - trailers to be included on the mocked reply. + +### Return: `MockScope` + +A `MockScope` is associated with a single `MockInterceptor`. With this, we can configure the default behaviour of a intercepted reply. + +* **delay** `(waitInMs: number) => MockScope` - delay the associated reply by a set amount in ms. +* **persist** `() => MockScope` - any matching request will always reply with the defined response indefinitely. +* **times** `(repeatTimes: number) => MockScope` - any matching request will reply with the defined response a fixed amount of times. This is overridden by **persist**. + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +// MockPool +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request using reply data callbacks + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, ({ headers }) => ({ message: headers.get('message') })) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Mocked request using reply options callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(({ headers }) => ({ statusCode: 200, data: { message: headers.get('message') }}))) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo') + +mockPool.intercept({ + path: '/hello', + method: 'GET', +}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` + +#### Example - Mocked request with query body, request headers and response headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } + }) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request using different matchers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: /^GET$/, + body: (value) => value === 'form=data', + headers: { + 'User-Agent': 'undici', + Host: /^example.com$/ + } +}).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { + method: 'GET', + body: 'form=data', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with reply with a defined error + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyWithError(new Error('kaboom')) + +try { + await request('http://localhost:3000/foo', { + method: 'GET' + }) +} catch (error) { + console.error(error) // Error: kaboom +} +``` + +#### Example - Mocked request with defaultReplyHeaders + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyHeaders({ foo: 'bar' }) + .reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { foo: 'bar' } +``` + +#### Example - Mocked request with defaultReplyTrailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyTrailers({ foo: 'bar' }) + .reply(200, 'foo') + +const { trailers } = await request('http://localhost:3000/foo') + +console.log('trailers', trailers) // trailers { foo: 'bar' } +``` + +#### Example - Mocked request with automatic content-length calculation + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '3' } +``` + +#### Example - Mocked request with automatic content-length calculation on an object + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, { foo: 'bar' }) + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '13' } +``` + +#### Example - Mocked request with persist enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').persist() + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +// Etc +``` + +#### Example - Mocked request with times enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').times(2) + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result3 = await request('http://localhost:3000/foo') +// Will not match and make attempt a real request +``` + +### `MockPool.close()` + +Closes the mock pool and de-registers from associated MockAgent. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +const mockPool = mockAgent.get('http://localhost:3000') + +await mockPool.close() +``` + +### `MockPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockPool request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ + path: '/foo', + method: 'GET', +}).reply(200, 'foo') + +const { + statusCode, + body +} = await mockPool.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/api/Pool.md b/node_modules/undici/docs/api/Pool.md new file mode 100644 index 0000000..8fcabac --- /dev/null +++ b/node_modules/undici/docs/api/Pool.md @@ -0,0 +1,84 @@ +# Class: Pool + +Extends: `undici.Dispatcher` + +A pool of [Client](Client.md) instances connected to the same upstream target. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Pool(url[, options])` + +Arguments: + +* **url** `URL | string` - It should only include the **protocol, hostname, and port**. +* **options** `PoolOptions` (optional) + +### Parameter: `PoolOptions` + +Extends: [`ClientOptions`](Client.md#parameter-clientoptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)` +* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `Pool` instance will create an unlimited amount of `Client` instances. +* **interceptors** `{ Pool: DispatchInterceptor[] } }` - Default: `{ Pool: [] }` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). + +## Instance Properties + +### `Pool.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `Pool.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `Pool.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Pool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Pool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Pool.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Pool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Pool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Pool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Pool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/api/PoolStats.md b/node_modules/undici/docs/api/PoolStats.md new file mode 100644 index 0000000..16b6dc2 --- /dev/null +++ b/node_modules/undici/docs/api/PoolStats.md @@ -0,0 +1,35 @@ +# Class: PoolStats + +Aggregate stats for a [Pool](Pool.md) or [BalancedPool](BalancedPool.md). + +## `new PoolStats(pool)` + +Arguments: + +* **pool** `Pool` - Pool or BalancedPool from which to return stats. + +## Instance Properties + +### `PoolStats.connected` + +Number of open socket connections in this pool. + +### `PoolStats.free` + +Number of open socket connections in this pool that do not have an active request. + +### `PoolStats.pending` + +Number of pending requests across all clients in this pool. + +### `PoolStats.queued` + +Number of queued requests across all clients in this pool. + +### `PoolStats.running` + +Number of currently active requests across all clients in this pool. + +### `PoolStats.size` + +Number of active, pending, or queued requests across all clients in this pool. diff --git a/node_modules/undici/docs/api/ProxyAgent.md b/node_modules/undici/docs/api/ProxyAgent.md new file mode 100644 index 0000000..cebfe68 --- /dev/null +++ b/node_modules/undici/docs/api/ProxyAgent.md @@ -0,0 +1,126 @@ +# Class: ProxyAgent + +Extends: `undici.Dispatcher` + +A Proxy Agent class that implements the Agent API. It allows the connection through proxy in a simple way. + +## `new ProxyAgent([options])` + +Arguments: + +* **options** `ProxyAgentOptions` (required) - It extends the `Agent` options. + +Returns: `ProxyAgent` + +### Parameter: `ProxyAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **uri** `string` (required) - It can be passed either by a string or a object containing `uri` as string. +* **token** `string` (optional) - It can be passed by a string of token for authentication. +* **auth** `string` (**deprecated**) - Use token. +* **clientFactory** `(origin: URL, opts: Object) => Dispatcher` (optional) - Default: `(origin, opts) => new Pool(origin, opts)` +* **requestTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the request. See [TLS](https://nodejs.org/api/tls.html#tlsconnectoptions-callback). +* **proxyTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the proxy server. See [TLS](https://nodejs.org/api/tls.html#tlsconnectoptions-callback). + +Examples: + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +// or +const proxyAgent = new ProxyAgent({ uri: 'my.proxy.server' }) +``` + +#### Example - Basic ProxyAgent instantiation + +This will instantiate the ProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { ProxyAgent, request } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: proxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with authentication + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici'; + +const proxyAgent = new ProxyAgent({ + uri: 'my.proxy.server', + // token: 'Bearer xxxx' + token: `Basic ${Buffer.from('username:password').toString('base64')}` +}); +setGlobalDispatcher(proxyAgent); + +const { statusCode, body } = await request('http://localhost:3000/foo'); + +console.log('response received', statusCode); // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')); // data foo +} +``` + +### `ProxyAgent.close()` + +Closes the proxy agent and waits for registered pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { ProxyAgent, setGlobalDispatcher } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +await proxyAgent.close() +``` + +### `ProxyAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](Agent.md#parameter-agentdispatchoptions). + +### `ProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). diff --git a/node_modules/undici/docs/api/WebSocket.md b/node_modules/undici/docs/api/WebSocket.md new file mode 100644 index 0000000..9d374f4 --- /dev/null +++ b/node_modules/undici/docs/api/WebSocket.md @@ -0,0 +1,43 @@ +# Class: WebSocket + +> ⚠️ Warning: the WebSocket API is experimental. + +Extends: [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) + +The WebSocket object provides a way to manage a WebSocket connection to a server, allowing bidirectional communication. The API follows the [WebSocket spec](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) and [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455). + +## `new WebSocket(url[, protocol])` + +Arguments: + +* **url** `URL | string` - The url's protocol *must* be `ws` or `wss`. +* **protocol** `string | string[] | WebSocketInit` (optional) - Subprotocol(s) to request the server use, or a [`Dispatcher`](./Dispatcher.md). + +### Example: + +This example will not work in browsers or other platforms that don't allow passing an object. + +```mjs +import { WebSocket, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const ws = new WebSocket('wss://echo.websocket.events', { + dispatcher: proxyAgent, + protocols: ['echo', 'chat'] +}) +``` + +If you do not need a custom Dispatcher, it's recommended to use the following pattern: + +```mjs +import { WebSocket } from 'undici' + +const ws = new WebSocket('wss://echo.websocket.events', ['echo', 'chat']) +``` + +## Read More + +- [MDN - WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +- [The WebSocket Specification](https://www.rfc-editor.org/rfc/rfc6455) +- [The WHATWG WebSocket Specification](https://websockets.spec.whatwg.org/) diff --git a/node_modules/undici/docs/api/api-lifecycle.md b/node_modules/undici/docs/api/api-lifecycle.md new file mode 100644 index 0000000..d158126 --- /dev/null +++ b/node_modules/undici/docs/api/api-lifecycle.md @@ -0,0 +1,62 @@ +# Client Lifecycle + +An Undici [Client](Client.md) can be best described as a state machine. The following list is a summary of the various state transitions the `Client` will go through in its lifecycle. This document also contains detailed breakdowns of each state. + +> This diagram is not a perfect representation of the undici Client. Since the Client class is not actually implemented as a state-machine, actual execution may deviate slightly from what is described below. Consider this as a general resource for understanding the inner workings of the Undici client rather than some kind of formal specification. + +## State Transition Overview + +* A `Client` begins in the **idle** state with no socket connection and no requests in queue. + * The *connect* event transitions the `Client` to the **pending** state where requests can be queued prior to processing. + * The *close* and *destroy* events transition the `Client` to the **destroyed** state. Since there are no requests in the queue, the *close* event immediately transitions to the **destroyed** state. +* The **pending** state indicates the underlying socket connection has been successfully established and requests are queueing. + * The *process* event transitions the `Client` to the **processing** state where requests are processed. + * If requests are queued, the *close* event transitions to the **processing** state; otherwise, it transitions to the **destroyed** state. + * The *destroy* event transitions to the **destroyed** state. +* The **processing** state initializes to the **processing.running** state. + * If the current request requires draining, the *needDrain* event transitions the `Client` into the **processing.busy** state which will return to the **processing.running** state with the *drainComplete* event. + * After all queued requests are completed, the *keepalive* event transitions the `Client` back to the **pending** state. If no requests are queued during the timeout, the **close** event transitions the `Client` to the **destroyed** state. + * If the *close* event is fired while the `Client` still has queued requests, the `Client` transitions to the **process.closing** state where it will complete all existing requests before firing the *done* event. + * The *done* event gracefully transitions the `Client` to the **destroyed** state. + * At any point in time, the *destroy* event will transition the `Client` from the **processing** state to the **destroyed** state, destroying any queued requests. +* The **destroyed** state is a final state and the `Client` is no longer functional. + +![A state diagram representing an Undici Client instance](../assets/lifecycle-diagram.png) + +> The diagram was generated using Mermaid.js Live Editor. Modify the state diagram [here](https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoic3RhdGVEaWFncmFtLXYyXG4gICAgWypdIC0tPiBpZGxlXG4gICAgaWRsZSAtLT4gcGVuZGluZyA6IGNvbm5lY3RcbiAgICBpZGxlIC0tPiBkZXN0cm95ZWQgOiBkZXN0cm95L2Nsb3NlXG4gICAgXG4gICAgcGVuZGluZyAtLT4gaWRsZSA6IHRpbWVvdXRcbiAgICBwZW5kaW5nIC0tPiBkZXN0cm95ZWQgOiBkZXN0cm95XG5cbiAgICBzdGF0ZSBjbG9zZV9mb3JrIDw8Zm9yaz4-XG4gICAgcGVuZGluZyAtLT4gY2xvc2VfZm9yayA6IGNsb3NlXG4gICAgY2xvc2VfZm9yayAtLT4gcHJvY2Vzc2luZ1xuICAgIGNsb3NlX2ZvcmsgLS0-IGRlc3Ryb3llZFxuXG4gICAgcGVuZGluZyAtLT4gcHJvY2Vzc2luZyA6IHByb2Nlc3NcblxuICAgIHByb2Nlc3NpbmcgLS0-IHBlbmRpbmcgOiBrZWVwYWxpdmVcbiAgICBwcm9jZXNzaW5nIC0tPiBkZXN0cm95ZWQgOiBkb25lXG4gICAgcHJvY2Vzc2luZyAtLT4gZGVzdHJveWVkIDogZGVzdHJveVxuXG4gICAgc3RhdGUgcHJvY2Vzc2luZyB7XG4gICAgICAgIHJ1bm5pbmcgLS0-IGJ1c3kgOiBuZWVkRHJhaW5cbiAgICAgICAgYnVzeSAtLT4gcnVubmluZyA6IGRyYWluQ29tcGxldGVcbiAgICAgICAgcnVubmluZyAtLT4gWypdIDoga2VlcGFsaXZlXG4gICAgICAgIHJ1bm5pbmcgLS0-IGNsb3NpbmcgOiBjbG9zZVxuICAgICAgICBjbG9zaW5nIC0tPiBbKl0gOiBkb25lXG4gICAgICAgIFsqXSAtLT4gcnVubmluZ1xuICAgIH1cbiAgICAiLCJtZXJtYWlkIjp7InRoZW1lIjoiYmFzZSJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ) + +## State details + +### idle + +The **idle** state is the initial state of a `Client` instance. While an `origin` is required for instantiating a `Client` instance, the underlying socket connection will not be established until a request is queued using [`Client.dispatch()`](Client.md#clientdispatchoptions-handlers). By calling `Client.dispatch()` directly or using one of the multiple implementations ([`Client.connect()`](Client.md#clientconnectoptions-callback), [`Client.pipeline()`](Client.md#clientpipelineoptions-handler), [`Client.request()`](Client.md#clientrequestoptions-callback), [`Client.stream()`](Client.md#clientstreamoptions-factory-callback), and [`Client.upgrade()`](Client.md#clientupgradeoptions-callback)), the `Client` instance will transition from **idle** to [**pending**](#pending) and then most likely directly to [**processing**](#processing). + +Calling [`Client.close()`](Client.md#clientclosecallback) or [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](#destroyed) state since the `Client` instance will have no queued requests in this state. + +### pending + +The **pending** state signifies a non-processing `Client`. Upon entering this state, the `Client` establishes a socket connection and emits the [`'connect'`](Client.md#event-connect) event signalling a connection was successfully established with the `origin` provided during `Client` instantiation. The internal queue is initially empty, and requests can start queueing. + +Calling [`Client.close()`](Client.md#clientclosecallback) with queued requests, transitions the `Client` to the [**processing**](#processing) state. Without queued requests, it transitions to the [**destroyed**](#destroyed) state. + +Calling [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](#destroyed) state regardless of existing requests. + +### processing + +The **processing** state is a state machine within itself. It initializes to the [**processing.running**](#running) state. The [`Client.dispatch()`](Client.md#clientdispatchoptions-handlers), [`Client.close()`](Client.md#clientclosecallback), and [`Client.destroy()`](Client.md#clientdestroyerror-callback) can be called at any time while the `Client` is in this state. `Client.dispatch()` will add more requests to the queue while existing requests continue to be processed. `Client.close()` will transition to the [**processing.closing**](#closing) state. And `Client.destroy()` will transition to [**destroyed**](#destroyed). + +#### running + +In the **processing.running** sub-state, queued requests are being processed in a FIFO order. If a request body requires draining, the *needDrain* event transitions to the [**processing.busy**](#busy) sub-state. The *close* event transitions the Client to the [**process.closing**](#closing) sub-state. If all queued requests are processed and neither [`Client.close()`](Client.md#clientclosecallback) nor [`Client.destroy()`](Client.md#clientdestroyerror-callback) are called, then the [**processing**](#processing) machine will trigger a *keepalive* event transitioning the `Client` back to the [**pending**](#pending) state. During this time, the `Client` is waiting for the socket connection to timeout, and once it does, it triggers the *timeout* event and transitions to the [**idle**](#idle) state. + +#### busy + +This sub-state is only entered when a request body is an instance of [Stream](https://nodejs.org/api/stream.html) and requires draining. The `Client` cannot process additional requests while in this state and must wait until the currently processing request body is completely drained before transitioning back to [**processing.running**](#running). + +#### closing + +This sub-state is only entered when a `Client` instance has queued requests and the [`Client.close()`](Client.md#clientclosecallback) method is called. In this state, the `Client` instance continues to process requests as usual, with the one exception that no additional requests can be queued. Once all of the queued requests are processed, the `Client` will trigger the *done* event gracefully entering the [**destroyed**](#destroyed) state without an error. + +### destroyed + +The **destroyed** state is a final state for the `Client` instance. Once in this state, a `Client` is nonfunctional. Calling any other `Client` methods will result in an `ClientDestroyedError`. diff --git a/node_modules/undici/docs/assets/lifecycle-diagram.png b/node_modules/undici/docs/assets/lifecycle-diagram.png new file mode 100644 index 0000000..4ef17b5 Binary files /dev/null and b/node_modules/undici/docs/assets/lifecycle-diagram.png differ diff --git a/node_modules/undici/docs/best-practices/client-certificate.md b/node_modules/undici/docs/best-practices/client-certificate.md new file mode 100644 index 0000000..4fc84ec --- /dev/null +++ b/node_modules/undici/docs/best-practices/client-certificate.md @@ -0,0 +1,64 @@ +# Client certificate + +Client certificate authentication can be configured with the `Client`, the required options are passed along through the `connect` option. + +The client certificates must be signed by a trusted CA. The Node.js default is to trust the well-known CAs curated by Mozilla. + +Setting the server option `requestCert: true` tells the server to request the client certificate. + +The server option `rejectUnauthorized: false` allows us to handle any invalid certificate errors in client code. The `authorized` property on the socket of the incoming request will show if the client certificate was valid. The `authorizationError` property will give the reason if the certificate was not valid. + +### Client Certificate Authentication + +```js +const { readFileSync } = require('fs') +const { join } = require('path') +const { createServer } = require('https') +const { Client } = require('undici') + +const serverOptions = { + ca: [ + readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'), + requestCert: true, + rejectUnauthorized: false +} + +const server = createServer(serverOptions, (req, res) => { + // true if client cert is valid + if(req.client.authorized === true) { + console.log('valid') + } else { + console.error(req.client.authorizationError) + } + res.end() +}) + +server.listen(0, function () { + const tls = { + ca: [ + readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'), + rejectUnauthorized: false, + servername: 'agent1' + } + const client = new Client(`https://localhost:${server.address().port}`, { + connect: tls + }) + + client.request({ + path: '/', + method: 'GET' + }, (err, { body }) => { + body.on('data', (buf) => {}) + body.on('end', () => { + client.close() + server.close() + }) + }) +}) +``` diff --git a/node_modules/undici/docs/best-practices/mocking-request.md b/node_modules/undici/docs/best-practices/mocking-request.md new file mode 100644 index 0000000..6954392 --- /dev/null +++ b/node_modules/undici/docs/best-practices/mocking-request.md @@ -0,0 +1,136 @@ +# Mocking Request + +Undici has its own mocking [utility](../api/MockAgent.md). It allow us to intercept undici HTTP requests and return mocked values instead. It can be useful for testing purposes. + +Example: + +```js +// bank.mjs +import { request } from 'undici' + +export async function bankTransfer(recipient, amount) { + const { body } = await request('http://localhost:3000/bank-transfer', + { + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient, + amount + }) + } + ) + return await body.json() +} +``` + +And this is what the test file looks like: + +```js +// index.test.mjs +import { strict as assert } from 'assert' +import { MockAgent, setGlobalDispatcher, } from 'undici' +import { bankTransfer } from './bank.mjs' + +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +// intercept the request +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, { + message: 'transaction processed' +}) + +const success = await bankTransfer('1234567890', '100') + +assert.deepEqual(success, { message: 'transaction processed' }) + +// if you dont want to check whether the body or the headers contain the same value +// just remove it from interceptor +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(400, { + message: 'bank account not found' +}) + +const badRequest = await bankTransfer('1234567890', '100') + +assert.deepEqual(badRequest, { message: 'bank account not found' }) +``` + +Explore other MockAgent functionality [here](../api/MockAgent.md) + +## Debug Mock Value + +When the interceptor and the request options are not the same, undici will automatically make a real HTTP request. To prevent real requests from being made, use `mockAgent.disableNetConnect()`: + +```js +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); +mockAgent.disableNetConnect() + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(200, { + message: 'transaction processed' +}) + +const badRequest = await bankTransfer('1234567890', '100') +// Will throw an error +// MockNotMatchedError: Mock dispatch not matched for path '/bank-transfer': +// subsequent request to origin http://localhost:3000 was not allowed (net.connect disabled) +``` + +## Reply with data based on request + +If the mocked response needs to be dynamically derived from the request parameters, you can provide a function instead of an object to `reply`: + +```js +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, (opts) => { + // do something with opts + + return { message: 'transaction processed' } +}) +``` + +in this case opts will be + +``` +{ + method: 'POST', + headers: { 'X-TOKEN-SECRET': 'SuperSecretToken' }, + body: '{"recipient":"1234567890","amount":"100"}', + origin: 'http://localhost:3000', + path: '/bank-transfer' +} +``` diff --git a/node_modules/undici/docs/best-practices/proxy.md b/node_modules/undici/docs/best-practices/proxy.md new file mode 100644 index 0000000..bf10295 --- /dev/null +++ b/node_modules/undici/docs/best-practices/proxy.md @@ -0,0 +1,127 @@ +# Connecting through a proxy + +Connecting through a proxy is possible by: + +- Using [AgentProxy](../api/ProxyAgent.md). +- Configuring `Client` or `Pool` constructor. + +The proxy url should be passed to the `Client` or `Pool` constructor, while the upstream server url +should be added to every request call in the `path`. +For instance, if you need to send a request to the `/hello` route of your upstream server, +the `path` should be `path: 'http://upstream.server:port/hello?foo=bar'`. + +If you proxy requires basic authentication, you can send it via the `proxy-authorization` header. + +### Connect without authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import proxy from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar' +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = proxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + +### Connect with authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import proxy from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +proxyServer.authenticate = function (req, fn) { + fn(null, req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}`) +} + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar', + headers: { + 'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}` + } +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = proxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + diff --git a/node_modules/undici/docs/best-practices/writing-tests.md b/node_modules/undici/docs/best-practices/writing-tests.md new file mode 100644 index 0000000..57549de --- /dev/null +++ b/node_modules/undici/docs/best-practices/writing-tests.md @@ -0,0 +1,20 @@ +# Writing tests + +Undici is tuned for a production use case and its default will keep +a socket open for a few seconds after an HTTP request is completed to +remove the overhead of opening up a new socket. These settings that makes +Undici shine in production are not a good fit for using Undici in automated +tests, as it will result in longer execution times. + +The following are good defaults that will keep the socket open for only 10ms: + +```js +import { request, setGlobalDispatcher, Agent } from 'undici' + +const agent = new Agent({ + keepAliveTimeout: 10, // milliseconds + keepAliveMaxTimeout: 10 // milliseconds +}) + +setGlobalDispatcher(agent) +``` diff --git a/node_modules/undici/index-fetch.js b/node_modules/undici/index-fetch.js new file mode 100644 index 0000000..ba31a65 --- /dev/null +++ b/node_modules/undici/index-fetch.js @@ -0,0 +1,15 @@ +'use strict' + +const fetchImpl = require('./lib/fetch').fetch + +module.exports.fetch = function fetch (resource, init = undefined) { + return fetchImpl(resource, init).catch((err) => { + Error.captureStackTrace(err, this) + throw err + }) +} +module.exports.FormData = require('./lib/fetch/formdata').FormData +module.exports.Headers = require('./lib/fetch/headers').Headers +module.exports.Response = require('./lib/fetch/response').Response +module.exports.Request = require('./lib/fetch/request').Request +module.exports.WebSocket = require('./lib/websocket/websocket').WebSocket diff --git a/node_modules/undici/index.d.ts b/node_modules/undici/index.d.ts new file mode 100644 index 0000000..83a786d --- /dev/null +++ b/node_modules/undici/index.d.ts @@ -0,0 +1,3 @@ +export * from './types/index' +import Undici from './types/index' +export default Undici diff --git a/node_modules/undici/index.js b/node_modules/undici/index.js new file mode 100644 index 0000000..7c0c8ad --- /dev/null +++ b/node_modules/undici/index.js @@ -0,0 +1,165 @@ +'use strict' + +const Client = require('./lib/client') +const Dispatcher = require('./lib/dispatcher') +const errors = require('./lib/core/errors') +const Pool = require('./lib/pool') +const BalancedPool = require('./lib/balanced-pool') +const Agent = require('./lib/agent') +const util = require('./lib/core/util') +const { InvalidArgumentError } = errors +const api = require('./lib/api') +const buildConnector = require('./lib/core/connect') +const MockClient = require('./lib/mock/mock-client') +const MockAgent = require('./lib/mock/mock-agent') +const MockPool = require('./lib/mock/mock-pool') +const mockErrors = require('./lib/mock/mock-errors') +const ProxyAgent = require('./lib/proxy-agent') +const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global') +const DecoratorHandler = require('./lib/handler/DecoratorHandler') +const RedirectHandler = require('./lib/handler/RedirectHandler') +const createRedirectInterceptor = require('./lib/interceptor/redirectInterceptor') + +let hasCrypto +try { + require('crypto') + hasCrypto = true +} catch { + hasCrypto = false +} + +Object.assign(Dispatcher.prototype, api) + +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent + +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor + +module.exports.buildConnector = buildConnector +module.exports.errors = errors + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } + + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } + + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } + + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } + + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } + + url = util.parseURL(url) + } + + const { agent, dispatcher = getGlobalDispatcher() } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } + + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } +} + +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher + +if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { + let fetchImpl = null + module.exports.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = require('./lib/fetch').fetch + } + + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) + } + + throw err + } + } + module.exports.Headers = require('./lib/fetch/headers').Headers + module.exports.Response = require('./lib/fetch/response').Response + module.exports.Request = require('./lib/fetch/request').Request + module.exports.FormData = require('./lib/fetch/formdata').FormData + module.exports.File = require('./lib/fetch/file').File + module.exports.FileReader = require('./lib/fileapi/filereader').FileReader + + const { setGlobalOrigin, getGlobalOrigin } = require('./lib/fetch/global') + + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin + + const { CacheStorage } = require('./lib/cache/cachestorage') + const { kConstruct } = require('./lib/cache/symbols') + + // Cache & CacheStorage are tightly coupled with fetch. Even if it may run + // in an older version of Node, it doesn't have any use without fetch. + module.exports.caches = new CacheStorage(kConstruct) +} + +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = require('./lib/cookies') + + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie + + const { parseMIMEType, serializeAMimeType } = require('./lib/fetch/dataURL') + + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType +} + +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = require('./lib/websocket/websocket') + + module.exports.WebSocket = WebSocket +} + +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) + +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors diff --git a/node_modules/undici/lib/agent.js b/node_modules/undici/lib/agent.js new file mode 100644 index 0000000..0b18f2a --- /dev/null +++ b/node_modules/undici/lib/agent.js @@ -0,0 +1,148 @@ +'use strict' + +const { InvalidArgumentError } = require('./core/errors') +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('./core/symbols') +const DispatcherBase = require('./dispatcher-base') +const Pool = require('./pool') +const Client = require('./client') +const util = require('./core/util') +const createRedirectInterceptor = require('./interceptor/redirectInterceptor') +const { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')() + +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kMaxRedirections = Symbol('maxRedirections') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kFinalizer = Symbol('finalizer') +const kOptions = Symbol('options') + +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} + +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super() + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } + + this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] + + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kMaxRedirections] = maxRedirections + this[kFactory] = factory + this[kClients] = new Map() + this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { + const ref = this[kClients].get(key) + if (ref !== undefined && ref.deref() === undefined) { + this[kClients].delete(key) + } + }) + + const agent = this + + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) + } + + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } + } + + get [kRunning] () { + let ret = 0 + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore next: gc is undeterministic */ + if (client) { + ret += client[kRunning] + } + } + return ret + } + + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } + + const ref = this[kClients].get(key) + + let dispatcher = ref ? ref.deref() : null + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) + } + + return dispatcher.dispatch(opts, handler) + } + + async [kClose] () { + const closePromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + closePromises.push(client.close()) + } + } + + await Promise.all(closePromises) + } + + async [kDestroy] (err) { + const destroyPromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + destroyPromises.push(client.destroy(err)) + } + } + + await Promise.all(destroyPromises) + } +} + +module.exports = Agent diff --git a/node_modules/undici/lib/api/abort-signal.js b/node_modules/undici/lib/api/abort-signal.js new file mode 100644 index 0000000..2985c1e --- /dev/null +++ b/node_modules/undici/lib/api/abort-signal.js @@ -0,0 +1,54 @@ +const { addAbortListener } = require('../core/util') +const { RequestAbortedError } = require('../core/errors') + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) + } +} + +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self) + return + } + + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } + + addAbortListener(self[kSignal], self[kListener]) +} + +function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } + + self[kSignal] = null + self[kListener] = null +} + +module.exports = { + addSignal, + removeSignal +} diff --git a/node_modules/undici/lib/api/api-connect.js b/node_modules/undici/lib/api/api-connect.js new file mode 100644 index 0000000..fd2b6ad --- /dev/null +++ b/node_modules/undici/lib/api/api-connect.js @@ -0,0 +1,104 @@ +'use strict' + +const { AsyncResource } = require('async_hooks') +const { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = connect diff --git a/node_modules/undici/lib/api/api-pipeline.js b/node_modules/undici/lib/api/api-pipeline.js new file mode 100644 index 0000000..af4a180 --- /dev/null +++ b/node_modules/undici/lib/api/api-pipeline.js @@ -0,0 +1,249 @@ +'use strict' + +const { + Readable, + Duplex, + PassThrough +} = require('stream') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') +const assert = require('assert') + +const kResume = Symbol('resume') + +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) + + this[kResume] = null + } + + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() + } + } + + _destroy (err, callback) { + this._read() + + callback(err) + } +} + +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } + + _read () { + this[kResume]() + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + callback(err) + } +} + +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_PIPELINE') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null + + this.req = new PipelineRequest().on('error', util.nop) + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this + + if (body && body.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (abort && err) { + abort() + } + + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) + + removeSignal(this) + + callback(err) + } + }).on('prefinish', () => { + const { req } = this + + // Node < 15 does not call _final in same tick. + req.push(null) + }) + + this.res = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + const { ret, res } = this + + assert(!res, 'pipeline cannot be retried') + + if (ret.destroyed) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + this.res = new PipelineResponse(resume) + + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', util.nop) + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this + + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + res.push(null) + } + + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} + +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } +} + +module.exports = pipeline diff --git a/node_modules/undici/lib/api/api-request.js b/node_modules/undici/lib/api/api-request.js new file mode 100644 index 0000000..f130ecc --- /dev/null +++ b/node_modules/undici/lib/api/api-request.js @@ -0,0 +1,179 @@ +'use strict' + +const Readable = require('./readable') +const { + InvalidArgumentError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { getResolveErrorBodyCallback } = require('./util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.throwOnError = throwOnError + this.highWaterMark = highWaterMark + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const body = new Readable({ resume, abort, contentType, highWaterMark }) + + this.callback = null + this.res = body + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body, contentType, statusCode, statusMessage, headers } + ) + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body, + context + }) + } + } + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + util.parseHeaders(trailers, this.trailers) + + res.push(null) + } + + onError (err) { + const { res, callback, body, opaque } = this + + removeSignal(this) + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = request diff --git a/node_modules/undici/lib/api/api-stream.js b/node_modules/undici/lib/api/api-stream.js new file mode 100644 index 0000000..c571a6f --- /dev/null +++ b/node_modules/undici/lib/api/api-stream.js @@ -0,0 +1,220 @@ +'use strict' + +const { finished, PassThrough } = require('stream') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { getResolveErrorBodyCallback } = require('./util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + this.throwOnError = throwOnError || false + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + this.factory = null + + let res + + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() + + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + if (factory === null) { + return + } + + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this + + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } + + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + } + + res.on('drain', resume) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain + + return needDrain !== true + } + + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + if (!res) { + return + } + + this.trailers = util.parseHeaders(trailers) + + res.end() + } + + onError (err) { + const { res, callback, opaque, body } = this + + removeSignal(this) + + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream diff --git a/node_modules/undici/lib/api/api-upgrade.js b/node_modules/undici/lib/api/api-upgrade.js new file mode 100644 index 0000000..ef783e8 --- /dev/null +++ b/node_modules/undici/lib/api/api-upgrade.js @@ -0,0 +1,105 @@ +'use strict' + +const { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors') +const { AsyncResource } = require('async_hooks') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') +const assert = require('assert') + +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = null + } + + onHeaders () { + throw new SocketError('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + assert.strictEqual(statusCode, 101) + + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = upgrade diff --git a/node_modules/undici/lib/api/index.js b/node_modules/undici/lib/api/index.js new file mode 100644 index 0000000..8983a5e --- /dev/null +++ b/node_modules/undici/lib/api/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports.request = require('./api-request') +module.exports.stream = require('./api-stream') +module.exports.pipeline = require('./api-pipeline') +module.exports.upgrade = require('./api-upgrade') +module.exports.connect = require('./api-connect') diff --git a/node_modules/undici/lib/api/readable.js b/node_modules/undici/lib/api/readable.js new file mode 100644 index 0000000..d106568 --- /dev/null +++ b/node_modules/undici/lib/api/readable.js @@ -0,0 +1,307 @@ +// Ported from https://github.com/nodejs/undici/pull/907 + +'use strict' + +const assert = require('assert') +const { Readable } = require('stream') +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = require('../core/errors') +const util = require('../core/util') +const { ReadableStreamFrom, toUSVString } = require('../core/util') + +let Blob + +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') + +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) + + this._readableState.dataEmitted = false + + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false + } + + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this + } + + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (err) { + this[kAbort]() + } + + return super.destroy(err) + } + + emit (ev, ...args) { + if (ev === 'data') { + // Node < 16.7 + this._readableState.dataEmitted = true + } else if (ev === 'error') { + // Node < 16 + this._readableState.errorEmitted = true + } + return super.emit(ev, ...args) + } + + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true + } + return super.on(ev, ...args) + } + + addListener (ev, ...args) { + return this.on(ev, ...args) + } + + off (ev, ...args) { + const ret = super.off(ev, ...args) + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) + } + return ret + } + + removeListener (ev, ...args) { + return this.off(ev, ...args) + } + + push (chunk) { + if (this[kConsume] && chunk !== null && this.readableLength === 0) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } + + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } + + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } + + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } + + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } + + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } + } + return this[kBody] + } + + async dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal + const abortFn = () => { + this.destroy() + } + let signalListenerCleanup + if (signal) { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + util.throwIfAborted(signal) + signalListenerCleanup = util.addAbortListener(signal, abortFn) + } + try { + for await (const chunk of this) { + util.throwIfAborted(signal) + limit -= Buffer.byteLength(chunk) + if (limit < 0) { + return + } + } + } catch { + util.throwIfAborted(signal) + } finally { + if (typeof signalListenerCleanup === 'function') { + signalListenerCleanup() + } else if (signalListenerCleanup) { + signalListenerCleanup[Symbol.dispose]() + } + } + } +} + +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] +} + +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} + +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') + } + + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + process.nextTick(consumeStart, stream[kConsume]) + }) +} + +function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream + + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } + + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } + + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop + } +} + +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume + + try { + if (type === 'text') { + resolve(toUSVString(Buffer.concat(body))) + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))) + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length) + + let pos = 0 + for (const buf of body) { + dst.set(buf, pos) + pos += buf.byteLength + } + + resolve(dst.buffer) + } else if (type === 'blob') { + if (!Blob) { + Blob = require('buffer').Blob + } + resolve(new Blob(body, { type: stream[kContentType] })) + } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) + } +} + +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} + +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err) + } else { + consume.resolve() + } + + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} diff --git a/node_modules/undici/lib/api/util.js b/node_modules/undici/lib/api/util.js new file mode 100644 index 0000000..bffd702 --- /dev/null +++ b/node_modules/undici/lib/api/util.js @@ -0,0 +1,46 @@ +const assert = require('assert') +const { + ResponseStatusCodeError +} = require('../core/errors') +const { toUSVString } = require('../core/util') + +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) + + let chunks = [] + let limit = 0 + + for await (const chunk of body) { + chunks.push(chunk) + limit += chunk.length + if (limit > 128 * 1024) { + chunks = null + break + } + } + + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return + } + + try { + if (contentType.startsWith('application/json')) { + const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + + if (contentType.startsWith('text/')) { + const payload = toUSVString(Buffer.concat(chunks)) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + } catch (err) { + // Process in a fallback if error + } + + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) +} + +module.exports = { getResolveErrorBodyCallback } diff --git a/node_modules/undici/lib/balanced-pool.js b/node_modules/undici/lib/balanced-pool.js new file mode 100644 index 0000000..10bc6a4 --- /dev/null +++ b/node_modules/undici/lib/balanced-pool.js @@ -0,0 +1,190 @@ +'use strict' + +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = require('./core/errors') +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = require('./pool-base') +const Pool = require('./pool') +const { kUrl, kInterceptors } = require('./core/symbols') +const { parseOrigin } = require('./core/util') +const kFactory = Symbol('factory') + +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') + +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() + + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory + + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) + + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } + + this._updateBalancedPoolStats() + + return this + } + + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) + } + + return this + } + + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) + + if (allClientsBusy) { + return + } + + let counter = 0 + + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) + + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] + } +} + +module.exports = BalancedPool diff --git a/node_modules/undici/lib/cache/cache.js b/node_modules/undici/lib/cache/cache.js new file mode 100644 index 0000000..9b31108 --- /dev/null +++ b/node_modules/undici/lib/cache/cache.js @@ -0,0 +1,838 @@ +'use strict' + +const { kConstruct } = require('./symbols') +const { urlEquals, fieldValues: getFieldValues } = require('./util') +const { kEnumerableProperty, isDisturbed } = require('../core/util') +const { kHeadersList } = require('../core/symbols') +const { webidl } = require('../fetch/webidl') +const { Response, cloneResponse } = require('../fetch/response') +const { Request } = require('../fetch/request') +const { kState, kHeaders, kGuard, kRealm } = require('../fetch/symbols') +const { fetching } = require('../fetch/index') +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util') +const assert = require('assert') +const { getGlobalDispatcher } = require('../global') + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../types/cache').CacheQueryOptions} options + */ + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ + +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList + + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() + } + + this.#relevantRequestResponseList = arguments[1] + } + + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + const p = await this.matchAll(request, options) + + if (p.length === 0) { + return + } + + return p[0] + } + + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + // 1. + let r = null + + // 2. + if (request !== undefined) { + if (request instanceof Request) { + // 2.1.1 + r = request[kState] + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = new Request(request)[kState] + } + } + + // 5. + // 5.1 + const responses = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } + } + + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! + + // 5.5.1 + const responseList = [] + + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = new Response(response.body?.source ?? null) + const body = responseObject[kState].body + responseObject[kState] = response + responseObject[kState].body = body + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + + responseList.push(responseObject) + } + + // 6. + return Object.freeze(responseList) + } + + async add (request) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) + + request = webidl.converters.RequestInfo(request) + + // 1. + const requests = [request] + + // 2. + const responseArrayPromise = this.addAll(requests) + + // 3. + return await responseArrayPromise + } + + async addAll (requests) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) + + requests = webidl.converters['sequence'](requests) + + // 1. + const responsePromises = [] + + // 2. + const requestList = [] + + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = request[kState] + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme when method is not GET.' + }) + } + } + + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] + + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme.' + }) + } + + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' + + // 5.5 + requestList.push(r) + + // 5.6 + const responsePromise = createDeferredPromise() + + // 5.7 + fetchControllers.push(fetching({ + request: r, + dispatcher: getGlobalDispatcher(), + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })) + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')) + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })) + + for (const controller of fetchControllers) { + controller.abort() + } + + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } + + // 2. + responsePromise.resolve(response) + } + })) + + // 5.8 + responsePromises.push(responsePromise.promise) + } + + // 6. + const p = Promise.all(responsePromises) + + // 7. + const responses = await p + + // 7.1 + const operations = [] + + // 7.2 + let index = 0 + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 + } + + operations.push(operation) // 7.3.5 + + index++ // 7.3.6 + } + + // 7.5 + const cacheJobPromise = createDeferredPromise() + + // 7.6.1 + let errorData = null + + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) + + // 7.7 + return cacheJobPromise.promise + } + + async put (request, response) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) + + request = webidl.converters.RequestInfo(request) + response = webidl.converters.Response(response) + + // 1. + let innerRequest = null + + // 2. + if (request instanceof Request) { + innerRequest = request[kState] + } else { // 3. + innerRequest = new Request(request)[kState] + } + + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Expected an http/s scheme when method is not GET' + }) + } + + // 5. + const innerResponse = response[kState] + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) + } + + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) + + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } + } + + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Response body is locked or disturbed' + }) + } + + // 9. + const clonedResponse = cloneResponse(innerResponse) + + // 10. + const bodyReadPromise = createDeferredPromise() + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream + + // 11.2 + const reader = stream.getReader() + + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) + } + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + } + + // 17. + operations.push(operation) + + // 19. + const bytes = await bodyReadPromise.promise + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } + + // 19.1 + const cacheJobPromise = createDeferredPromise() + + // 19.2.1 + let errorData = null + + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + /** + * @type {Request} + */ + let r = null + + if (request instanceof Request) { + r = request[kState] + + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string') + + r = new Request(request)[kState] + } + + /** @type {CacheBatchOperation[]} */ + const operations = [] + + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } + + operations.push(operation) + + const cacheJobPromise = createDeferredPromise() + + let errorData = null + let requestResponses + + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../types/cache').CacheQueryOptions} options + * @returns {readonly Request[]} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + // 1. + let r = null + + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } + } + + // 4. + const promise = createDeferredPromise() + + // 5. + // 5.1 + const requests = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } + } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] + + // 5.4.2 + for (const request of requests) { + const requestObject = new Request('https://a') + requestObject[kState] = request + requestObject[kHeaders][kHeadersList] = request.headersList + requestObject[kHeaders][kGuard] = 'immutable' + requestObject[kRealm] = request.client + + // 5.4.2.1 + requestList.push(requestObject) + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) + + return promise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList + + // 2. + const backupCache = [...cache] + + // 3. + const addedItems = [] + + // 4.1 + const resultList = [] + + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } + + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } + + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } + + // 4.2.4 + let requestResponses + + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) + + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } + + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.5.2.1 + cache.splice(idx, 1) + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } + + // 4.2.6.2 + const r = operation.request + + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } + + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } + + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } + + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) + + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.6.7.1 + cache.splice(idx, 1) + } + + // 4.2.6.8 + cache.push([operation.request, operation.response]) + + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } + + // 4.2.7 + resultList.push([operation.request, operation.response]) + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 + + // 5.2 + this.#relevantRequestResponseList = backupCache + + // 5.3 + throw e + } + } + + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = [] + + const storage = targetStorage ?? this.#relevantRequestResponseList + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } + } + + return resultList + } + + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } + + const queryURL = new URL(requestQuery.url) + + const cachedURL = new URL(request.url) + + if (options?.ignoreSearch) { + cachedURL.search = '' + + queryURL.search = '' + } + + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } + + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } + + const fieldValues = getFieldValues(response.headersList.get('vary')) + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } + } + + return true + } +} + +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: false + } +] + +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) + +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } +]) + +webidl.converters.Response = webidl.interfaceConverter(Response) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) + +module.exports = { + Cache +} diff --git a/node_modules/undici/lib/cache/cachestorage.js b/node_modules/undici/lib/cache/cachestorage.js new file mode 100644 index 0000000..7e7f0cf --- /dev/null +++ b/node_modules/undici/lib/cache/cachestorage.js @@ -0,0 +1,144 @@ +'use strict' + +const { kConstruct } = require('./symbols') +const { Cache } = require('./cache') +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../core/util') + +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) + + cacheName = webidl.converters.DOMString(cacheName) + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) + + cacheName = webidl.converters.DOMString(cacheName) + + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) + } + + // 2.2 + const cache = [] + + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) + + cacheName = webidl.converters.DOMString(cacheName) + + return this.#caches.delete(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) + + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] + } +} + +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +module.exports = { + CacheStorage +} diff --git a/node_modules/undici/lib/cache/symbols.js b/node_modules/undici/lib/cache/symbols.js new file mode 100644 index 0000000..f9b1974 --- /dev/null +++ b/node_modules/undici/lib/cache/symbols.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports = { + kConstruct: Symbol('constructable') +} diff --git a/node_modules/undici/lib/cache/util.js b/node_modules/undici/lib/cache/util.js new file mode 100644 index 0000000..44d52b7 --- /dev/null +++ b/node_modules/undici/lib/cache/util.js @@ -0,0 +1,49 @@ +'use strict' + +const assert = require('assert') +const { URLSerializer } = require('../fetch/dataURL') +const { isValidHeaderName } = require('../fetch/util') + +/** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ +function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment) + + const serializedB = URLSerializer(B, excludeFragment) + + return serializedA === serializedB +} + +/** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ +function fieldValues (header) { + assert(header !== null) + + const values = [] + + for (let value of header.split(',')) { + value = value.trim() + + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue + } + + values.push(value) + } + + return values +} + +module.exports = { + urlEquals, + fieldValues +} diff --git a/node_modules/undici/lib/client.js b/node_modules/undici/lib/client.js new file mode 100644 index 0000000..968a7f9 --- /dev/null +++ b/node_modules/undici/lib/client.js @@ -0,0 +1,2287 @@ +// @ts-check + +'use strict' + +/* global WebAssembly */ + +const assert = require('assert') +const net = require('net') +const http = require('http') +const { pipeline } = require('stream') +const util = require('./core/util') +const timers = require('./timers') +const Request = require('./core/request') +const DispatcherBase = require('./dispatcher-base') +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError +} = require('./core/errors') +const buildConnector = require('./core/connect') +const { + kUrl, + kReset, + kServerName, + kClient, + kBusy, + kParser, + kConnect, + kBlocking, + kResuming, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize, + kHTTPConnVersion, + // HTTP2 + kHost, + kHTTP2Session, + kHTTP2SessionState, + kHTTP2BuildRequest, + kHTTP2CopyHeaders, + kHTTP1BuildRequest +} = require('./core/symbols') + +/** @type {import('http2')} */ +let http2 +try { + http2 = require('http2') +} catch { + // @ts-ignore + http2 = { constants: {} } +} + +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS + } +} = http2 + +// Experimental +let h2ExperimentalWarned = false + +const FastBuffer = Buffer[Symbol.species] + +const kClosedResolve = Symbol('kClosedResolve') + +const channels = {} + +try { + const diagnosticsChannel = require('diagnostics_channel') + channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') + channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') + channels.connectError = diagnosticsChannel.channel('undici:client:connectError') + channels.connected = diagnosticsChannel.channel('undici:client:connected') +} catch { + channels.sendHeaders = { hasSubscribers: false } + channels.beforeConnect = { hasSubscribers: false } + channels.connectError = { hasSubscribers: false } + channels.connected = { hasSubscribers: false } +} + +/** + * @type {import('../types/client').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../types/client').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + allowH2, + maxConcurrentStreams + } = {}) { + super() + + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) + ? interceptors.Client + : [createRedirectInterceptor({ maxRedirections })] + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kSocket] = null + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRedirections] = maxRedirections + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + this[kHTTPConnVersion] = 'h1' + + // HTTP/2 + this[kHTTP2Session] = null + this[kHTTP2SessionState] = !allowH2 + ? null + : { + // streams: null, // Fixed queue of streams - For future support of `push` + openStreams: 0, // Keep track of them to decide wether or not unref the session + maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + } + this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value + resume(this, true) + } + + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } + + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } + + get [kConnected] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed + } + + get [kBusy] () { + const socket = this[kSocket] + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize] >= (this[kPipelining] || 1)) || + this[kPending] > 0 + ) + } + + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } + + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin + + const request = this[kHTTPConnVersion] === 'h2' + ? Request[kHTTP2BuildRequest](origin, opts, handler) + : Request[kHTTP1BuildRequest](origin, opts, handler) + + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + process.nextTick(resume, this) + } else { + resume(this, true) + } + + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } + + return this[kNeedDrain] < 2 + } + + async [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (!this[kSize]) { + resolve(null) + } else { + this[kClosedResolve] = resolve + } + }) + } + + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) + } + + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve() + } + + if (this[kHTTP2Session] != null) { + util.destroy(this[kHTTP2Session], err) + this[kHTTP2Session] = null + this[kHTTP2SessionState] = null + } + + if (!this[kSocket]) { + queueMicrotask(callback) + } else { + util.destroy(this[kSocket].on('close', callback), err) + } + + resume(this) + }) + } +} + +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kSocket][kError] = err + + onError(this[kClient], err) +} + +function onHttp2FrameError (type, code, id) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + + if (id === 0) { + this[kSocket][kError] = err + onError(this[kClient], err) + } +} + +function onHttp2SessionEnd () { + util.destroy(this, new SocketError('other side closed')) + util.destroy(this[kSocket], new SocketError('other side closed')) +} + +function onHTTP2GoAway (code) { + const client = this[kClient] + const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) + client[kSocket] = null + client[kHTTP2Session] = null + + if (client.destroyed) { + assert(this[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) + } + } else if (client[kRunning] > 0) { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', + client[kUrl], + [client], + err + ) + + resume(client) +} + +const constants = require('./llhttp/constants') +const createRedirectInterceptor = require('./interceptor/redirectInterceptor') +const EMPTY_BUF = Buffer.alloc(0) + +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? require('./llhttp/llhttp-wasm.js') : undefined + + let mod + try { + mod = await WebAssembly.compile(Buffer.from(require('./llhttp/llhttp_simd-wasm.js'), 'base64')) + } catch (e) { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || require('./llhttp/llhttp-wasm.js'), 'base64')) + } + + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ + + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageComplete() || 0 + } + + /* eslint-enable camelcase */ + } + }) +} + +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() + +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null + +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 + +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) + + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = null + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (value, type) { + this.timeoutType = type + if (value !== this.timeoutValue) { + timers.clearTimeout(this.timeout) + if (value) { + this.timeout = timers.setTimeout(onParserTimeout, value, this) + // istanbul ignore else: only for jest + if (this.timeout.unref) { + this.timeout.unref() + } + } else { + this.timeout = null + } + this.timeoutValue = value + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_resume(this.ptr) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } + + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) + + const { socket, llhttp } = this + + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret + + try { + currentBufferRef = data + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(data.slice(offset)) + } else if (ret !== constants.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + /* istanbul ignore else: difficult to make a test case for */ + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')' + } + throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) + } + } catch (err) { + util.destroy(socket, err) + } + } + + destroy () { + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_free(this.ptr) + this.ptr = null + + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + + this.paused = false + } + + onStatus (buf) { + this.statusText = buf.toString() + } + + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 + } + } + + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + this.trackHeader(buf.length) + } + + onHeaderValue (buf) { + let len = this.headers.length + + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + const key = this.headers[len - 2] + if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { + this.connection += buf.toString() + } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { + this.contentLength += buf.toString() + } + + this.trackHeader(buf.length) + } + + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } + + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this + + assert(upgrade) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') + + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + socket.unshift(head) + + socket[kParser].destroy() + socket[kParser] = null + + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) + + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } + + resume(client) + } + + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert(!this.upgrade) + assert(this.statusCode < 200) + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } + + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) + + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true + } + + let pause + try { + pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + } catch (err) { + util.destroy(socket, err) + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) + } + + return pause ? constants.ERROR.PAUSED : 0 + } + + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert.strictEqual(this.timeoutType, TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } + + this.bytesRead += buf.length + + try { + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } catch (err) { + util.destroy(socket, err) + return -1 + } + } + + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(statusCode >= 100) + + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (statusCode < 200) { + return + } + + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + try { + request.onComplete(headers) + } catch (err) { + errorRequest(client, request, err) + } + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert.strictEqual(client[kRunning], 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(resume, client) + } else { + resume(client) + } + } +} + +function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!parser.paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!parser.paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_IDLE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) + } +} + +function onSocketReadable () { + const { [kParser]: parser } = this + if (parser) { + parser.readMore() + } +} + +function onSocketError (err) { + const { [kClient]: client, [kParser]: parser } = this + + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + if (client[kHTTPConnVersion] !== 'h2') { + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete() + return + } + } + + this[kError] = err + + onError(this[kClient], err) +} + +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + assert(client[kSize] === 0) + } +} + +function onSocketEnd () { + const { [kParser]: parser, [kClient]: client } = this + + if (client[kHTTPConnVersion] !== 'h2') { + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return + } + } + + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onSocketClose () { + const { [kClient]: client, [kParser]: parser } = this + + if (client[kHTTPConnVersion] === 'h1' && parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + } + + this[kParser].destroy() + this[kParser] = null + } + + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + client[kSocket] = null + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + resume(client) +} + +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) + + let { host, hostname, protocol, port } = client[kUrl] + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') + + assert(idx !== -1) + const ip = hostname.substr(1, idx - 1) + + assert(net.isIP(ip)) + hostname = ip + } + + client[kConnecting] = true + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err) + } else { + resolve(socket) + } + }) + }) + + if (client.destroyed) { + util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) + return + } + + client[kConnecting] = false + + assert(socket) + + const isH2 = socket.alpnProtocol === 'h2' + if (isH2) { + if (!h2ExperimentalWarned) { + h2ExperimentalWarned = true + process.emitWarning('H2 support is experimental, expect them to change at any time.', { + code: 'UNDICI-H2' + }) + } + + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }) + + client[kHTTPConnVersion] = 'h2' + session[kClient] = client + session[kSocket] = socket + session.on('error', onHttp2SessionError) + session.on('frameError', onHttp2FrameError) + session.on('end', onHttp2SessionEnd) + session.on('goaway', onHTTP2GoAway) + session.on('close', onSocketClose) + session.unref() + + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + } else { + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = null + } + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) + } + + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null + + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) + + client[kSocket] = socket + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) + } + client.emit('connect', client[kUrl], [client]) + } catch (err) { + if (client.destroyed) { + return + } + + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + errorRequest(client, request, err) + } + } else { + onError(client, err) + } + + client.emit('connectionError', client[kUrl], [client], err) + } + + resume(client) +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } + + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } + + const socket = client[kSocket] + + if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) + } + } + } + + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) + } else { + emitDrain(client) + } + continue + } + + if (client[kPending] === 0) { + return + } + + if (client[kRunning] >= (client[kPipelining] || 1)) { + return + } + + const request = client[kQueue][client[kPendingIdx]] + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } + + client[kServerName] = request.servername + + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return + } + } + + if (client[kConnecting]) { + return + } + + if (!socket && !client[kHTTP2Session]) { + connect(client) + return + } + + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return + } + + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return + } + + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } + } +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +function write (client, request) { + if (client[kHTTPConnVersion] === 'h2') { + writeH2(client, client[kHTTP2Session], request) + return + } + + const { body, method, path, host, upgrade, headers, blocking, reset } = request + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + const bodyLength = util.bodyLength(body) + + let contentLength = bodyLength + + if (contentLength === null) { + contentLength = request.contentLength + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + const socket = client[kSocket] + + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError()) + + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true + } + + if (reset != null) { + socket[kReset] = reset + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } + + if (blocking) { + socket[kBlocking] = true + } + + let header = `${method} ${path} HTTP/1.1\r\n` + + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } + + if (headers) { + header += headers + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + /* istanbul ignore else: assertion */ + if (!body || bodyLength === 0) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'latin1') + } + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(body) + socket.uncork() + request.onBodySent(body) + request.onRequestSent() + if (!expectsPayload) { + socket[kReset] = true + } + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) + } else { + writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) + } + } else if (util.isStream(body)) { + writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) + } else if (util.isIterable(body)) { + writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) + } else { + assert(false) + } + + return true +} + +function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request + + let headers + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) + else headers = reqHeaders + + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } + + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError()) + }) + } catch (err) { + errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + let stream + const h2State = client[kHTTP2SessionState] + + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] + headers[HTTP2_HEADER_METHOD] = method + + if (method === 'CONNECT') { + session.ref() + // we are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }) + + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + }) + } + + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref() + }) + + return true + } + + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT + + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + let contentLength = util.bodyLength(body) + + if (contentLength == null) { + contentLength = request.contentLength + } + + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } + + session.ref() + + const shouldEndStream = method === 'GET' || method === 'HEAD' + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + /** + * @type {import('node:http2').ClientHttp2Stream} + */ + stream = session.request(headers, { endStream: shouldEndStream, signal }) + + stream.once('continue', writeBodyH2) + } else { + /** @type {import('node:http2').ClientHttp2Stream} */ + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + writeBodyH2() + } + + // Increment counter as we have new several streams open + ++h2State.openStreams + + stream.once('response', headers => { + if (request.onHeaders(Number(headers[HTTP2_HEADER_STATUS]), headers, stream.resume.bind(stream), '') === false) { + stream.pause() + } + }) + + stream.once('end', () => { + request.onComplete([]) + }) + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) stream.pause() + }) + + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref() + }) + + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) + + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + errorRequest(client, request, err) + + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) + + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) + + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) + + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) + + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) + + return true + + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body) { + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + stream.cork() + stream.write(body) + stream.uncork() + stream.end() + request.onBodySent(body) + request.onRequestSent() + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ + client, + request, + contentLength, + h2stream: stream, + expectsPayload, + body: body.stream(), + socket: client[kSocket], + header: '' + }) + } else { + writeBlob({ + body, + client, + request, + contentLength, + expectsPayload, + h2stream: stream, + header: '', + socket: client[kSocket] + }) + } + } else if (util.isStream(body)) { + writeStream({ + body, + client, + request, + contentLength, + expectsPayload, + socket: client[kSocket], + h2stream: stream, + header: '' + }) + } else if (util.isIterable(body)) { + writeIterable({ + body, + client, + request, + contentLength, + expectsPayload, + header: '', + h2stream: stream, + socket: client[kSocket] + }) + } else { + assert(false) + } + } +} + +function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + if (client[kHTTPConnVersion] === 'h2') { + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(body, err) + util.destroy(h2stream, err) + } else { + request.onRequestSent() + } + } + ) + + pipe.on('data', onPipeData) + pipe.once('end', () => { + pipe.removeListener('data', onPipeData) + util.destroy(pipe) + }) + + function onPipeData (chunk) { + request.onBodySent(chunk) + } + + return + } + + let finished = false + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } + } + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume() + } + } + const onAbort = function () { + onFinished(new RequestAbortedError()) + } + const onFinished = function (err) { + if (finished) { + return + } + + finished = true + + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + + socket + .off('drain', onDrain) + .off('error', onFinished) + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) + + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } + + writer.destroy(err) + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) + + if (body.resume) { + body.resume() + } + + socket + .on('drain', onDrain) + .on('error', onFinished) +} + +async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') + + const isH2 = client[kHTTPConnVersion] === 'h2' + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + if (isH2) { + h2stream.cork() + h2stream.write(buffer) + h2stream.uncork() + } else { + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(buffer) + socket.uncork() + } + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + resume(client) + } catch (err) { + util.destroy(isH2 ? h2stream : socket, err) + } +} + +async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain) + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { + await waitForDrain() + } + } + } catch (err) { + h2stream.destroy(err) + } finally { + request.onRequestSent() + h2stream.end() + h2stream + .off('close', onDrain) + .off('drain', onDrain) + } + + return + } + + socket + .on('close', onDrain) + .on('drain', onDrain) + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain() + } + } + + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} + +class AsyncWriter { + constructor ({ socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header + + socket[kWriting] = true + } + + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + socket.cork() + + if (bytesWritten === 0) { + if (!expectsPayload) { + socket[kReset] = true + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } + + this.bytesWritten += len + + const ret = socket.write(chunk) + + socket.uncork() + + request.onBodySent(chunk) + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + } + + return ret + } + + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() + + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + socket.write(`${header}\r\n`, 'latin1') + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1') + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + + resume(client) + } + + destroy (err) { + const { socket, client } = this + + socket[kWriting] = false + + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + util.destroy(socket, err) + } + } +} + +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} + +module.exports = Client diff --git a/node_modules/undici/lib/compat/dispatcher-weakref.js b/node_modules/undici/lib/compat/dispatcher-weakref.js new file mode 100644 index 0000000..8cb99e2 --- /dev/null +++ b/node_modules/undici/lib/compat/dispatcher-weakref.js @@ -0,0 +1,48 @@ +'use strict' + +/* istanbul ignore file: only for Node 12 */ + +const { kConnected, kSize } = require('../core/symbols') + +class CompatWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} + +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer + } + + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } + } +} + +module.exports = function () { + // FIXME: remove workaround when the Node bug is fixed + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (process.env.NODE_V8_COVERAGE) { + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + } + } + return { + WeakRef: global.WeakRef || CompatWeakRef, + FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer + } +} diff --git a/node_modules/undici/lib/cookies/constants.js b/node_modules/undici/lib/cookies/constants.js new file mode 100644 index 0000000..85f1fec --- /dev/null +++ b/node_modules/undici/lib/cookies/constants.js @@ -0,0 +1,12 @@ +'use strict' + +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 + +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} diff --git a/node_modules/undici/lib/cookies/index.js b/node_modules/undici/lib/cookies/index.js new file mode 100644 index 0000000..c9c1f28 --- /dev/null +++ b/node_modules/undici/lib/cookies/index.js @@ -0,0 +1,184 @@ +'use strict' + +const { parseSetCookie } = require('./parse') +const { stringify, getHeadersList } = require('./util') +const { webidl } = require('../fetch/webidl') +const { Headers } = require('../fetch/headers') + +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ + +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookie = headers.get('cookie') + const out = {} + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') + + out[name.trim()] = value.join('=') + } + + return out +} + +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + name = webidl.converters.DOMString(name) + attributes = webidl.converters.DeleteCookieAttributes(attributes) + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} + +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookies = getHeadersList(headers).cookies + + if (!cookies) { + return [] + } + + // In older versions of undici, cookies is a list of name:value. + return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair)) +} + +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + cookie = webidl.converters.Cookie(cookie) + + const str = stringify(cookie) + + if (str) { + headers.append('Set-Cookie', stringify(cookie)) + } +} + +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + } +]) + +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: [] + } +]) + +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie +} diff --git a/node_modules/undici/lib/cookies/parse.js b/node_modules/undici/lib/cookies/parse.js new file mode 100644 index 0000000..aae2750 --- /dev/null +++ b/node_modules/undici/lib/cookies/parse.js @@ -0,0 +1,317 @@ +'use strict' + +const { maxNameValuePairSize, maxAttributeValueSize } = require('./constants') +const { isCTLExcludingHtab } = require('./util') +const { collectASequenceOfCodePointsFast } = require('../fetch/dataURL') +const assert = require('assert') + +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } +} + +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = '' + let attributeValue = '' + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} + +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} diff --git a/node_modules/undici/lib/cookies/util.js b/node_modules/undici/lib/cookies/util.js new file mode 100644 index 0000000..2290329 --- /dev/null +++ b/node_modules/undici/lib/cookies/util.js @@ -0,0 +1,291 @@ +'use strict' + +const assert = require('assert') +const { kHeadersList } = require('../core/symbols') + +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } + + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false + } + } +} + +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) + + if ( + (code <= 0x20 || code > 0x7F) || + char === '(' || + char === ')' || + char === '>' || + char === '<' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' + ) { + throw new Error('Invalid cookie name') + } + } +} + +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || // exclude CTLs (0-31) + code === 0x22 || + code === 0x2C || + code === 0x3B || + code === 0x5C || + code > 0x7E // non-ascii + ) { + throw new Error('Invalid header value') + } + } +} + +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) + + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') + } + } +} + +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } + + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ] + + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ] + + const dayName = days[date.getUTCDay()] + const day = date.getUTCDate().toString().padStart(2, '0') + const month = months[date.getUTCMonth()] + const year = date.getUTCFullYear() + const hour = date.getUTCHours().toString().padStart(2, '0') + const minute = date.getUTCMinutes().toString().padStart(2, '0') + const second = date.getUTCSeconds().toString().padStart(2, '0') + + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name) + validateCookieValue(cookie.value) + + const out = [`${cookie.name}=${cookie.value}`] + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } + + if (cookie.secure) { + out.push('Secure') + } + + if (cookie.httpOnly) { + out.push('HttpOnly') + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } + + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('=') + + out.push(`${key.trim()}=${value.join('=')}`) + } + + return out.join('; ') +} + +let kHeadersListNode + +function getHeadersList (headers) { + if (headers[kHeadersList]) { + return headers[kHeadersList] + } + + if (!kHeadersListNode) { + kHeadersListNode = Object.getOwnPropertySymbols(headers).find( + (symbol) => symbol.description === 'headers list' + ) + + assert(kHeadersListNode, 'Headers cannot be parsed') + } + + const headersList = headers[kHeadersListNode] + assert(headersList) + + return headersList +} + +module.exports = { + isCTLExcludingHtab, + stringify, + getHeadersList +} diff --git a/node_modules/undici/lib/core/connect.js b/node_modules/undici/lib/core/connect.js new file mode 100644 index 0000000..3309117 --- /dev/null +++ b/node_modules/undici/lib/core/connect.js @@ -0,0 +1,189 @@ +'use strict' + +const net = require('net') +const assert = require('assert') +const util = require('./util') +const { InvalidArgumentError, ConnectTimeoutError } = require('./errors') + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +let SessionCache +// FIXME: remove workaround when the Node bug is fixed +// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 +if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new global.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } + } +} else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + } + + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } + + this._sessionCache.set(sessionKey, session) + } + } +} + +function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = require('tls') + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null + + assert(sessionKey) + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + // TODO(HTTP/2): Add support for h2c + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port: port || 443, + host: hostname + }) + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port: port || 80, + host: hostname + }) + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket + } +} + +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} + } + + let s1 = null + let s2 = null + const timeoutId = setTimeout(() => { + // setImmediate is added to make sure that we priotorise socket error events over timeouts + s1 = setImmediate(() => { + if (process.platform === 'win32') { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout()) + } else { + onConnectTimeout() + } + }) + }, timeout) + return () => { + clearTimeout(timeoutId) + clearImmediate(s1) + clearImmediate(s2) + } +} + +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) +} + +module.exports = buildConnector diff --git a/node_modules/undici/lib/core/errors.js b/node_modules/undici/lib/core/errors.js new file mode 100644 index 0000000..653782d --- /dev/null +++ b/node_modules/undici/lib/core/errors.js @@ -0,0 +1,216 @@ +'use strict' + +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } +} + +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ConnectTimeoutError) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' + } +} + +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersTimeoutError) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' + } +} + +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersOverflowError) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } +} + +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, BodyTimeoutError) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } +} + +class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message) + Error.captureStackTrace(this, ResponseStatusCodeError) + this.name = 'ResponseStatusCodeError' + this.message = message || 'Response Status Code Error' + this.code = 'UND_ERR_RESPONSE_STATUS_CODE' + this.body = body + this.status = statusCode + this.statusCode = statusCode + this.headers = headers + } +} + +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidArgumentError) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } +} + +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidReturnValueError) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } +} + +class RequestAbortedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestAbortedError) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } +} + +class InformationalError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InformationalError) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } +} + +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestContentLengthMismatchError) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } +} + +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseContentLengthMismatchError) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } +} + +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientDestroyedError) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } +} + +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientClosedError) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' + } +} + +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + Error.captureStackTrace(this, SocketError) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } +} + +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } +} + +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } +} + +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + Error.captureStackTrace(this, HTTPParserError) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } +} + +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseExceededMaxSizeError) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } +} + +module.exports = { + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError +} diff --git a/node_modules/undici/lib/core/request.js b/node_modules/undici/lib/core/request.js new file mode 100644 index 0000000..7db05ce --- /dev/null +++ b/node_modules/undici/lib/core/request.js @@ -0,0 +1,483 @@ +'use strict' + +const { + InvalidArgumentError, + NotSupportedError +} = require('./errors') +const assert = require('assert') +const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = require('./symbols') +const util = require('./util') + +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js + +/** + * Verifies that the given val is a valid HTTP token + * per the rules defined in RFC 7230 + * See https://tools.ietf.org/html/rfc7230#section-3.2.6 + */ +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ + +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ + +const kHandler = Symbol('handler') + +const channels = {} + +let extractBody + +try { + const diagnosticsChannel = require('diagnostics_channel') + channels.create = diagnosticsChannel.channel('undici:request:create') + channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') + channels.headers = diagnosticsChannel.channel('undici:request:headers') + channels.trailers = diagnosticsChannel.channel('undici:request:trailers') + channels.error = diagnosticsChannel.channel('undici:request:error') +} catch { + channels.create = { hasSubscribers: false } + channels.bodySent = { hasSubscribers: false } + channels.headers = { hasSubscribers: false } + channels.trailers = { hasSubscribers: false } + channels.error = { hasSubscribers: false } +} + +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError, + expectContinue + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.exec(path) !== null) { + throw new InvalidArgumentError('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + + this.headersTimeout = headersTimeout + + this.bodyTimeout = bodyTimeout + + this.throwOnError = throwOnError === true + + this.method = method + + this.abort = null + + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body + + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + util.destroy(this) + } + this.body.on('end', this.endHandler) + } + + this.errorHandler = err => { + if (this.abort) { + this.abort(err) + } else { + this.error = err + } + } + this.body.on('error', this.errorHandler) + } else if (util.isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false + + this.aborted = false + + this.upgrade = upgrade || null + + this.path = query ? util.buildURL(path, query) : path + + this.origin = origin + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent + + this.blocking = blocking == null ? false : blocking + + this.reset = reset == null ? null : reset + + this.host = null + + this.contentLength = null + + this.contentType = null + + this.headers = '' + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(this, key, headers[key]) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + if (util.isFormDataLike(this.body)) { + if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { + throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') + } + + if (!extractBody) { + extractBody = require('../fetch/body.js').extractBody + } + + const [bodyStream, contentType] = extractBody(body) + if (this.contentType == null) { + this.contentType = contentType + this.headers += `content-type: ${contentType}\r\n` + } + this.body = bodyStream.stream + this.contentLength = bodyStream.length + } else if (util.isBlobLike(body) && this.contentType == null && body.type) { + this.contentType = body.type + this.headers += `content-type: ${body.type}\r\n` + } + + util.validateHandler(handler, method, upgrade) + + this.servername = util.getServerName(this.host) + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } + + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + this[kHandler].onBodySent(chunk) + } catch (err) { + this.onError(err) + } + } + } + + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } + + if (this[kHandler].onRequestSent) { + try { + this[kHandler].onRequestSent() + } catch (err) { + this.onError(err) + } + } + } + + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) + + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } + } + + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } + + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onData(chunk) + } + + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + this.onFinally() + + assert(!this.aborted) + + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } + return this[kHandler].onComplete(trailers) + } + + onError (error) { + this.onFinally() + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + + if (this.aborted) { + return + } + this.aborted = true + return this[kHandler].onError(error) + } + + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } + + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } + } + + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value) + return this + } + + static [kHTTP1BuildRequest] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } + + static [kHTTP2BuildRequest] (origin, opts, handler) { + const headers = opts.headers + opts = { ...opts, headers: null } + + const request = new Request(origin, opts, handler) + + request.headers = {} + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(request, headers[i], headers[i + 1], true) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(request, key, headers[key], true) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + return request + } + + static [kHTTP2CopyHeaders] (raw) { + const rawHeaders = raw.split('\r\n') + const headers = {} + + for (const header of rawHeaders) { + const [key, value] = header.split(': ') + + if (value == null || value.length === 0) continue + + if (headers[key]) headers[key] += `,${value}` + else headers[key] = value + } + + return headers + } +} + +function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + val = val != null ? `${val}` : '' + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + return skipAppend ? val : `${key}: ${val}\r\n` +} + +function processHeader (request, key, val, skipAppend = false) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + if ( + request.host === null && + key.length === 4 && + key.toLowerCase() === 'host' + ) { + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + // Consumed by Client + request.host = val + } else if ( + request.contentLength === null && + key.length === 14 && + key.toLowerCase() === 'content-length' + ) { + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if ( + request.contentType === null && + key.length === 12 && + key.toLowerCase() === 'content-type' + ) { + request.contentType = val + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } else if ( + key.length === 17 && + key.toLowerCase() === 'transfer-encoding' + ) { + throw new InvalidArgumentError('invalid transfer-encoding header') + } else if ( + key.length === 10 && + key.toLowerCase() === 'connection' + ) { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } else if (value === 'close') { + request.reset = true + } + } else if ( + key.length === 10 && + key.toLowerCase() === 'keep-alive' + ) { + throw new InvalidArgumentError('invalid keep-alive header') + } else if ( + key.length === 7 && + key.toLowerCase() === 'upgrade' + ) { + throw new InvalidArgumentError('invalid upgrade header') + } else if ( + key.length === 6 && + key.toLowerCase() === 'expect' + ) { + throw new NotSupportedError('expect header not supported') + } else if (tokenRegExp.exec(key) === null) { + throw new InvalidArgumentError('invalid header key') + } else { + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (skipAppend) { + if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` + else request.headers[key] = processHeaderValue(key, val[i], skipAppend) + } else { + request.headers += processHeaderValue(key, val[i]) + } + } + } else { + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } + } +} + +module.exports = Request diff --git a/node_modules/undici/lib/core/symbols.js b/node_modules/undici/lib/core/symbols.js new file mode 100644 index 0000000..c2492f4 --- /dev/null +++ b/node_modules/undici/lib/core/symbols.js @@ -0,0 +1,61 @@ +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kHeadersList: Symbol('headers list'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kHTTP2BuildRequest: Symbol('http2 build request'), + kHTTP1BuildRequest: Symbol('http1 build request'), + kHTTP2CopyHeaders: Symbol('http2 copy headers'), + kHTTPConnVersion: Symbol('http connection version') +} diff --git a/node_modules/undici/lib/core/util.js b/node_modules/undici/lib/core/util.js new file mode 100644 index 0000000..f2ead03 --- /dev/null +++ b/node_modules/undici/lib/core/util.js @@ -0,0 +1,503 @@ +'use strict' + +const assert = require('assert') +const { kDestroyed, kBodyUsed } = require('./symbols') +const { IncomingMessage } = require('http') +const stream = require('stream') +const net = require('net') +const { InvalidArgumentError } = require('./errors') +const { Blob } = require('buffer') +const nodeUtil = require('util') +const { stringify } = require('querystring') + +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + +function nop () {} + +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} + +// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) +function isBlobLike (object) { + return (Blob && object instanceof Blob) || ( + object && + typeof object === 'object' && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) +} + +function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified + } + + return url +} + +function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url) + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } + + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol}//${url.hostname}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` + + if (origin.endsWith('/')) { + origin = origin.substring(0, origin.length - 1) + } + + if (path && !path.startsWith('/')) { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + url = new URL(origin + path) + } + + return url +} + +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url +} + +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substr(1, idx - 1) + } + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substr(0, idx) +} + +// IP addresses are not valid server names per RFC6066 +// > Currently, the only server names supported are DNS hostnames +function getServerName (host) { + if (!host) { + return null + } + + assert.strictEqual(typeof host, 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } + + return servername +} + +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} + +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} + +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} + +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null +} + +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) +} + +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted +} + +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } + + stream.destroy(err) + } else if (err) { + process.nextTick((stream, err) => { + stream.emit('error', err) + }, stream, err) + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } +} + +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} + +function parseHeaders (headers, obj = {}) { + // For H2 support + if (!Array.isArray(headers)) return headers + + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase() + let val = obj[key] + + if (!val) { + if (Array.isArray(headers[i + 1])) { + obj[key] = headers[i + 1] + } else { + obj[key] = headers[i + 1].toString('utf8') + } + } else { + if (!Array.isArray(val)) { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) + } + } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') + } + + return obj +} + +function parseRawHeaders (headers) { + const ret = [] + let hasContentLength = false + let contentDispositionIdx = -1 + + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString() + const val = headers[n + 1].toString('utf8') + + if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + ret.push(key, val) + hasContentLength = true + } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = ret.push(key, val) - 1 + } else { + ret.push(key, val) + } + } + + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } + + return ret +} + +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} + +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } + } +} + +// A body is disturbed if it has been read from and it cannot +// be re-used without losing state or data. +function isDisturbed (body) { + return !!(body && ( + stream.isDisturbed + ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? + : body[kBodyUsed] || + body.readableDidRead || + (body._readableState && body._readableState.dataEmitted) || + isReadableAborted(body) + )) +} + +function isErrored (body) { + return !!(body && ( + stream.isErrored + ? stream.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) +} + +function isReadable (body) { + return !!(body && ( + stream.isReadable + ? stream.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) +} + +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} + +async function * convertIterableToBuffer (iterable) { + for await (const chunk of iterable) { + yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + } +} + +let ReadableStream +function ReadableStreamFrom (iterable) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + if (ReadableStream.from) { + return ReadableStream.from(convertIterableToBuffer(iterable)) + } + + let iterator + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator]() + }, + async pull (controller) { + const { done, value } = await iterator.next() + if (done) { + queueMicrotask(() => { + controller.close() + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + controller.enqueue(new Uint8Array(buf)) + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + } + }, + 0 + ) +} + +// The chunk should be a FormData instance and contains +// all the required methods. +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function throwIfAborted (signal) { + if (!signal) { return } + if (typeof signal.throwIfAborted === 'function') { + signal.throwIfAborted() + } else { + if (signal.aborted) { + // DOMException not available < v17.0.0 + const err = new Error('The operation was aborted') + err.name = 'AbortError' + throw err + } + } +} + +let events +function addAbortListener (signal, listener) { + if (typeof Symbol.dispose === 'symbol') { + if (!events) { + events = require('events') + } + if (typeof events.addAbortListener === 'function' && 'aborted' in signal) { + return events.addAbortListener(signal, listener) + } + } + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener) + return () => signal.removeListener('abort', listener) +} + +const hasToWellFormed = !!String.prototype.toWellFormed + +/** + * @param {string} val + */ +function toUSVString (val) { + if (hasToWellFormed) { + return `${val}`.toWellFormed() + } else if (nodeUtil.toUSVString) { + return nodeUtil.toUSVString(val) + } + + return `${val}` +} + +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true + +module.exports = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString, + isReadableAborted, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + throwIfAborted, + addAbortListener, + nodeMajor, + nodeMinor, + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13) +} diff --git a/node_modules/undici/lib/dispatcher-base.js b/node_modules/undici/lib/dispatcher-base.js new file mode 100644 index 0000000..5c0220b --- /dev/null +++ b/node_modules/undici/lib/dispatcher-base.js @@ -0,0 +1,192 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = require('./core/errors') +const { kDestroy, kClose, kDispatch, kInterceptors } = require('./core/symbols') + +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') + +class DispatcherBase extends Dispatcher { + constructor () { + super() + + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] + } + + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + get interceptors () { + return this[kInterceptors] + } + + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors][i] + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError('interceptor must be an function') + } + } + } + + this[kInterceptors] = newInterceptors + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + this[kClosed] = true + this[kOnClosed].push(callback) + + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + if (!err) { + err = new ClientDestroyedError() + } + + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) + } + + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) + } + + let dispatch = this[kDispatch].bind(this) + for (let i = this[kInterceptors].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors][i](dispatch) + } + this[kInterceptedDispatch] = dispatch + return dispatch(opts, handler) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } + + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err) + + return false + } + } +} + +module.exports = DispatcherBase diff --git a/node_modules/undici/lib/dispatcher.js b/node_modules/undici/lib/dispatcher.js new file mode 100644 index 0000000..9b809d8 --- /dev/null +++ b/node_modules/undici/lib/dispatcher.js @@ -0,0 +1,19 @@ +'use strict' + +const EventEmitter = require('events') + +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } +} + +module.exports = Dispatcher diff --git a/node_modules/undici/lib/fetch/LICENSE b/node_modules/undici/lib/fetch/LICENSE new file mode 100644 index 0000000..2943500 --- /dev/null +++ b/node_modules/undici/lib/fetch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Ethan Arrowood + +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/undici/lib/fetch/body.js b/node_modules/undici/lib/fetch/body.js new file mode 100644 index 0000000..fd8481b --- /dev/null +++ b/node_modules/undici/lib/fetch/body.js @@ -0,0 +1,605 @@ +'use strict' + +const Busboy = require('@fastify/busboy') +const util = require('../core/util') +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = require('./util') +const { FormData } = require('./formdata') +const { kState } = require('./symbols') +const { webidl } = require('./webidl') +const { DOMException, structuredClone } = require('./constants') +const { Blob, File: NativeFile } = require('buffer') +const { kBodyUsed } = require('../core/symbols') +const assert = require('assert') +const { isErrored } = require('../core/util') +const { isUint8Array, isArrayBuffer } = require('util/types') +const { File: UndiciFile } = require('./file') +const { parseMIMEType, serializeAMimeType } = require('./dataURL') + +let ReadableStream = globalThis.ReadableStream + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() + +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream. + stream = new ReadableStream({ + async pull (controller) { + controller.enqueue( + typeof source === 'string' ? textEncoder.encode(source) : source + ) + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: undefined + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength + } else { + hasUnknownSizeValue = true + } + } + } + + const chunk = textEncoder.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = 'multipart/form-data; boundary=' + boundary + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + async pull (controller) { + const { value, done } = await iterator.next() + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + controller.enqueue(new Uint8Array(value)) + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: undefined + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = require('stream/web').ReadableStream + } + + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.') + // istanbul ignore next + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee() + const out2Clone = structuredClone(out2, { transfer: [out2] }) + // This, for whatever reasons, unrefs out2Clone which allows + // the process to exit by itself. + const [, finalClone] = out2Clone.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } +} + +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body + } else { + const stream = body.stream + + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } + + if (stream.locked) { + throw new TypeError('The stream is locked.') + } + + // Compat. + stream[kBodyUsed] = true + + yield * stream + } + } +} + +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } +} + +function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return specConsumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this) + + if (mimeType === 'failure') { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return specConsumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return specConsumeBody(this, utf8DecodeBytes, instance) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return specConsumeBody(this, parseJSONFromBytes, instance) + }, + + async formData () { + webidl.brandCheck(this, instance) + + throwIfAborted(this[kState]) + + const contentType = this.headers.get('Content-Type') + + // If mimeType’s essence is "multipart/form-data", then: + if (/multipart\/form-data/.test(contentType)) { + const headers = {} + for (const [key, value] of this.headers) headers[key.toLowerCase()] = value + + const responseFormData = new FormData() + + let busboy + + try { + busboy = new Busboy({ + headers, + preservePath: true + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') + } + + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = [] + + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' + + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') + + const end = base64chunk.length - base64chunk.length % 4 + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) + + base64chunk = base64chunk.slice(end) + }) + value.on('end', () => { + chunks.push(Buffer.from(base64chunk, 'base64')) + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } else { + value.on('data', (chunk) => { + chunks.push(chunk) + }) + value.on('end', () => { + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } + }) + + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve) + busboy.on('error', (err) => reject(new TypeError(err))) + }) + + if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) + busboy.end() + await busboyResolve + + return responseFormData + } else if (/application\/x-www-form-urlencoded/.test(contentType)) { + // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: + + // 1. Let entries be the result of parsing bytes. + let entries + try { + let text = '' + // application/x-www-form-urlencoded parser will keep the BOM. + // https://url.spec.whatwg.org/#concept-urlencoded-parser + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) + + for await (const chunk of consumeBody(this[kState].body)) { + if (!isUint8Array(chunk)) { + throw new TypeError('Expected Uint8Array chunk') + } + text += streamingDecoder.decode(chunk, { stream: true }) + } + text += streamingDecoder.decode() + entries = new URLSearchParams(text) + } catch (err) { + // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. + // 2. If entries is failure, then throw a TypeError. + throw Object.assign(new TypeError(), { cause: err }) + } + + // 3. Return a new FormData object whose entries are entries. + const formData = new FormData() + for (const [name, value] of entries) { + formData.append(name, value) + } + return formData + } else { + // Wait a tick before checking if the request has been aborted. + // Otherwise, a TypeError can be thrown when an AbortError should. + await Promise.resolve() + + throwIfAborted(this[kState]) + + // Otherwise, throw a TypeError. + throw webidl.errors.exception({ + header: `${instance.name}.formData`, + message: 'Could not parse content as FormData.' + }) + } + } + } + + return methods +} + +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ +async function specConsumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance) + + throwIfAborted(object[kState]) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') + } + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error) + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) + } + } + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(new Uint8Array()) + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +// https://fetch.spec.whatwg.org/#body-unusable +function bodyUnusable (body) { + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) + + // 4. Return output. + return output +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} object + */ +function bodyMimeType (object) { + const { headersList } = object[kState] + const contentType = headersList.get('content-type') + + if (contentType === null) { + return 'failure' + } + + return parseMIMEType(contentType) +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody +} diff --git a/node_modules/undici/lib/fetch/constants.js b/node_modules/undici/lib/fetch/constants.js new file mode 100644 index 0000000..218fcbe --- /dev/null +++ b/node_modules/undici/lib/fetch/constants.js @@ -0,0 +1,151 @@ +'use strict' + +const { MessageChannel, receiveMessageOnPort } = require('worker_threads') + +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + +const nullBodyStatus = [101, 204, 205, 304] + +const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) + +// https://fetch.spec.whatwg.org/#block-bad-port +const badPorts = [ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', + '10080' +] + +const badPortsSet = new Set(badPorts) + +// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies +const referrerPolicy = [ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +] +const referrerPolicySet = new Set(referrerPolicy) + +const requestRedirect = ['follow', 'manual', 'error'] + +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) + +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + +const requestCredentials = ['omit', 'same-origin', 'include'] + +const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +] + +// https://fetch.spec.whatwg.org/#request-body-header-name +const requestBodyHeader = [ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' +] + +// https://fetch.spec.whatwg.org/#enumdef-requestduplex +const requestDuplex = [ + 'half' +] + +// http://fetch.spec.whatwg.org/#forbidden-method +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) + +const subresource = [ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +] +const subresourceSet = new Set(subresource) + +/** @type {globalThis['DOMException']} */ +const DOMException = globalThis.DOMException ?? (() => { + // DOMException was only made a global in Node v17.0.0, + // but fetch supports >= v16.8. + try { + atob('~') + } catch (err) { + return Object.getPrototypeOf(err).constructor + } +})() + +let channel + +/** @type {globalThis['structuredClone']} */ +const structuredClone = + globalThis.structuredClone ?? + // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js + // structuredClone was added in v17.0.0, but fetch supports v16.8 + function structuredClone (value, options = undefined) { + if (arguments.length === 0) { + throw new TypeError('missing argument') + } + + if (!channel) { + channel = new MessageChannel() + } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message + } + +module.exports = { + DOMException, + structuredClone, + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet +} diff --git a/node_modules/undici/lib/fetch/dataURL.js b/node_modules/undici/lib/fetch/dataURL.js new file mode 100644 index 0000000..6df4fcc --- /dev/null +++ b/node_modules/undici/lib/fetch/dataURL.js @@ -0,0 +1,630 @@ +const assert = require('assert') +const { atob } = require('buffer') +const { isomorphicDecode } = require('./util') + +const encoder = new TextEncoder() + +/** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ +const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ +const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line +/** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ +const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line + +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) + + // 3. Remove the leading "data:" string from input. + input = input.slice(5) + + // 4. Let position point at the start of input. + const position = { position: 0 } + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = removeASCIIWhitespace(mimeType, true, true) + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++ + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} + +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + const href = url.href + + if (!excludeFragment) { + return href + } + + const hash = href.lastIndexOf('#') + if (hash === -1) { + return href + } + return href.slice(0, hash) +} + +// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] + + // 2. Advance position by 1. + position.position++ + } + + // 3. Return result. + return result +} + +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position + + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + // 1. Let output be an empty byte sequence. + /** @type {number[]} */ + const output = [] + + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) + ) { + output.push(0x25) + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) + const bytePoint = Number.parseInt(nextTwoBytes, 16) + + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) + + // 3. Skip the next two bytes in input. + i += 2 + } + } + + // 3. Return output. + return Uint8Array.from(output) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true) + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } + } + + // 12. Return mimeType. + return mimeType +} + +// https://infra.spec.whatwg.org/#forgiving-base64-decode +/** @param {string} data */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line + + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (data.length % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + data = data.replace(/=?=$/, '') + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (data.length % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data)) { + return 'failure' + } + + const binary = atob(data) + const bytes = new Uint8Array(binary.length) + + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) + } + + return bytes +} + +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ +function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position + + // 2. Let value be the empty string. + let value = '' + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + + // 4. Advance position by 1. + position.position++ + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] + + // 4. Advance position by 1. + position.position++ + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position] + + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} + +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' + + // 2. Append name to serialization. + serialization += name + + // 3. Append U+003D (=) to serialization. + serialization += '=' + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value + } + + // 3. Return serialization. + return serialization +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} char + */ +function isHTTPWhiteSpace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === ' ' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + */ +function removeHTTPWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) +} + +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {string} char + */ +function isASCIIWhitespace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' +} + +/** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + */ +function removeASCIIWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) +} + +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} diff --git a/node_modules/undici/lib/fetch/file.js b/node_modules/undici/lib/fetch/file.js new file mode 100644 index 0000000..3133d25 --- /dev/null +++ b/node_modules/undici/lib/fetch/file.js @@ -0,0 +1,344 @@ +'use strict' + +const { Blob, File: NativeFile } = require('buffer') +const { types } = require('util') +const { kState } = require('./symbols') +const { isBlobLike } = require('./util') +const { webidl } = require('./webidl') +const { parseMIMEType, serializeAMimeType } = require('./dataURL') +const { kEnumerableProperty } = require('../core/util') +const encoder = new TextEncoder() + +class File extends Blob { + constructor (fileBits, fileName, options = {}) { + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) + + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // 2. Convert every character in t to ASCII lowercase. + let t = options.type + let d + + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) + + if (t === 'failure') { + t = '' + // eslint-disable-next-line no-labels + break substep + } + + t = serializeAMimeType(t).toLowerCase() + } + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + d = options.lastModified + } + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t + } + } + + get name () { + webidl.brandCheck(this, File) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, File) + + return this[kState].lastModified + } + + get type () { + webidl.brandCheck(this, File) + + return this[kState].type + } +} + +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check + + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type + + // 2. Convert every character in t to ASCII lowercase. + // TODO + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now() + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } + + stream (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.stream(...args) + } + + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.arrayBuffer(...args) + } + + slice (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.slice(...args) + } + + text (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.text(...args) + } + + get size () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.size + } + + get type () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.type + } + + get name () { + webidl.brandCheck(this, FileLike) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, FileLike) + + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } +} + +Object.defineProperties(File.prototype, { + [Symbol.toStringTag]: { + value: 'File', + configurable: true + }, + name: kEnumerableProperty, + lastModified: kEnumerableProperty +}) + +webidl.converters.Blob = webidl.interfaceConverter(Blob) + +webidl.converters.BlobPart = function (V, opts) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) + ) { + return webidl.converters.BufferSource(V, opts) + } + } + + return webidl.converters.USVString(V, opts) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.BlobPart +) + +// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag +webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ + { + key: 'lastModified', + converter: webidl.converters['long long'], + get defaultValue () { + return Date.now() + } + }, + { + key: 'type', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'endings', + converter: (value) => { + value = webidl.converters.DOMString(value) + value = value.toLowerCase() + + if (value !== 'native') { + value = 'transparent' + } + + return value + }, + defaultValue: 'transparent' + } +]) + +/** + * @see https://www.w3.org/TR/FileAPI/#process-blob-parts + * @param {(NodeJS.TypedArray|Blob|string)[]} parts + * @param {{ type: string, endings: string }} options + */ +function processBlobParts (parts, options) { + // 1. Let bytes be an empty sequence of bytes. + /** @type {NodeJS.TypedArray[]} */ + const bytes = [] + + // 2. For each element in parts: + for (const element of parts) { + // 1. If element is a USVString, run the following substeps: + if (typeof element === 'string') { + // 1. Let s be element. + let s = element + + // 2. If the endings member of options is "native", set s + // to the result of converting line endings to native + // of element. + if (options.endings === 'native') { + s = convertLineEndingsNative(s) + } + + // 3. Append the result of UTF-8 encoding s to bytes. + bytes.push(encoder.encode(s)) + } else if ( + types.isAnyArrayBuffer(element) || + types.isTypedArray(element) + ) { + // 2. If element is a BufferSource, get a copy of the + // bytes held by the buffer source, and append those + // bytes to bytes. + if (!element.buffer) { // ArrayBuffer + bytes.push(new Uint8Array(element)) + } else { + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ) + } + } else if (isBlobLike(element)) { + // 3. If element is a Blob, append the bytes it represents + // to bytes. + bytes.push(element) + } + } + + // 3. Return bytes. + return bytes +} + +/** + * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native + * @param {string} s + */ +function convertLineEndingsNative (s) { + // 1. Let native line ending be be the code point U+000A LF. + let nativeLineEnding = '\n' + + // 2. If the underlying platform’s conventions are to + // represent newlines as a carriage return and line feed + // sequence, set native line ending to the code point + // U+000D CR followed by the code point U+000A LF. + if (process.platform === 'win32') { + nativeLineEnding = '\r\n' + } + + return s.replace(/\r?\n/g, nativeLineEnding) +} + +// If this function is moved to ./util.js, some tools (such as +// rollup) will warn about circular dependencies. See: +// https://github.com/nodejs/undici/issues/1629 +function isFileLike (object) { + return ( + (NativeFile && object instanceof NativeFile) || + object instanceof File || ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) +} + +module.exports = { File, FileLike, isFileLike } diff --git a/node_modules/undici/lib/fetch/formdata.js b/node_modules/undici/lib/fetch/formdata.js new file mode 100644 index 0000000..5975e26 --- /dev/null +++ b/node_modules/undici/lib/fetch/formdata.js @@ -0,0 +1,265 @@ +'use strict' + +const { isBlobLike, toUSVString, makeIterator } = require('./util') +const { kState } = require('./symbols') +const { File: UndiciFile, FileLike, isFileLike } = require('./file') +const { webidl } = require('./webidl') +const { Blob, File: NativeFile } = require('buffer') + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile + +// https://xhr.spec.whatwg.org/#formdata +class FormData { + constructor (form) { + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + + this[kState] = [] + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? webidl.converters.USVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) + + // 3. Append entry to this’s entry list. + this[kState].push(entry) + } + + delete (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) + + name = webidl.converters.USVString(name) + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this[kState] = this[kState].filter(entry => entry.name !== name) + } + + get (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) + + name = webidl.converters.USVString(name) + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? toUSVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry) + } + } + + entries () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) + } + + keys () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key' + ) + } + + values () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' + ) + } + + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } +} + +FormData.prototype[Symbol.iterator] = FormData.prototype.entries + +Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // "To convert a string into a scalar value string, replace any surrogates + // with U+FFFD." + // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end + name = Buffer.from(name).toString('utf8') + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + value = Buffer.from(value).toString('utf8') + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }) + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + } + + value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile + ? new File([value], filename, options) + : new FileLike(value, filename, options) + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} + +module.exports = { FormData } diff --git a/node_modules/undici/lib/fetch/global.js b/node_modules/undici/lib/fetch/global.js new file mode 100644 index 0000000..1df6f12 --- /dev/null +++ b/node_modules/undici/lib/fetch/global.js @@ -0,0 +1,40 @@ +'use strict' + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return + } + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} + +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} diff --git a/node_modules/undici/lib/fetch/headers.js b/node_modules/undici/lib/fetch/headers.js new file mode 100644 index 0000000..aa5e73e --- /dev/null +++ b/node_modules/undici/lib/fetch/headers.js @@ -0,0 +1,552 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { kHeadersList } = require('../core/symbols') +const { kGuard } = require('./symbols') +const { kEnumerableProperty } = require('../core/util') +const { + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = require('./util') +const { webidl } = require('./webidl') +const assert = require('assert') + +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + + // Trimming the end with `.replace()` and a RegExp is typically subject to + // ReDoS. This is safer and faster. + let i = potentialValue.length + while (/[\r\n\t ]/.test(potentialValue.charAt(--i))); + return potentialValue.slice(0, i + 1).replace(/^[\r\n\t ]+/, '') +} + +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (const header of object) { + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + headers.append(header[0], header[1]) + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + for (const [key, value] of Object.entries(object)) { + headers.append(key, value) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } +} + +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]) + this[kHeadersSortedMap] = init[kHeadersSortedMap] + this.cookies = init.cookies + } else { + this[kHeadersMap] = new Map(init) + this[kHeadersSortedMap] = null + } + } + + // https://fetch.spec.whatwg.org/#header-list-contains + contains (name) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + name = name.toLowerCase() + + return this[kHeadersMap].has(name) + } + + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null + } + + // https://fetch.spec.whatwg.org/#concept-header-list-append + append (name, value) { + this[kHeadersSortedMap] = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = name.toLowerCase() + const exists = this[kHeadersMap].get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + this.cookies ??= [] + this.cookies.push(value) + } + } + + // https://fetch.spec.whatwg.org/#concept-header-list-set + set (name, value) { + this[kHeadersSortedMap] = null + const lowercaseName = name.toLowerCase() + + if (lowercaseName === 'set-cookie') { + this.cookies = [value] + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + return this[kHeadersMap].set(lowercaseName, { name, value }) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-delete + delete (name) { + this[kHeadersSortedMap] = null + + name = name.toLowerCase() + + if (name === 'set-cookie') { + this.cookies = null + } + + return this[kHeadersMap].delete(name) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-get + get (name) { + // 1. If list does not contain name, then return null. + if (!this.contains(name)) { + return null + } + + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return this[kHeadersMap].get(name.toLowerCase())?.value ?? null + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] + } + } + + get entries () { + const headers = {} + + if (this[kHeadersMap].size) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value + } + } + + return headers + } +} + +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + constructor (init = undefined) { + this[kHeadersList] = new HeadersList() + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this[kGuard] = 'none' + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init) + fill(this, init) + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers + return this[kHeadersList].append(name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + return this[kHeadersList].delete(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.get', + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.has', + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this[kHeadersList].contains(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + return this[kHeadersList].set(name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this[kHeadersList].cookies + + if (list) { + return [...list] + } + + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) + const cookies = this[kHeadersList].cookies + + // 3. For each name of names: + for (const [name, value] of names) { + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (const value of cookies) { + headers.push([name, value]) + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + assert(value !== null) + + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } + + this[kHeadersList][kHeadersSortedMap] = headers + + // 4. Return headers. + return headers + } + + keys () { + webidl.brandCheck(this, Headers) + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } + + values () { + webidl.brandCheck(this, Headers) + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } + + entries () { + webidl.brandCheck(this, Headers) + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) + } + + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } + + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) + + return this[kHeadersList] + } +} + +Headers.prototype[Symbol.iterator] = Headers.prototype.entries + +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + keys: kEnumerableProperty, + values: kEnumerableProperty, + entries: kEnumerableProperty, + forEach: kEnumerableProperty, + [Symbol.iterator]: { enumerable: false }, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + } +}) + +webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) + } + + return webidl.converters['record'](V) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} + +module.exports = { + fill, + Headers, + HeadersList +} diff --git a/node_modules/undici/lib/fetch/index.js b/node_modules/undici/lib/fetch/index.js new file mode 100644 index 0000000..298b3dd --- /dev/null +++ b/node_modules/undici/lib/fetch/index.js @@ -0,0 +1,2145 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = require('./response') +const { Headers } = require('./headers') +const { Request, makeRequest } = require('./request') +const zlib = require('zlib') +const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme +} = require('./util') +const { kState, kHeaders, kGuard, kRealm } = require('./symbols') +const assert = require('assert') +const { safelyExtractBody } = require('./body') +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet, + DOMException +} = require('./constants') +const { kHeadersList } = require('../core/symbols') +const EE = require('events') +const { Readable, pipeline } = require('stream') +const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = require('../core/util') +const { dataURLProcessor, serializeAMimeType } = require('./dataURL') +const { TransformStream } = require('stream/web') +const { getGlobalDispatcher } = require('../global') +const { webidl } = require('./webidl') +const { STATUS_CODES } = require('http') +const GET_OR_HEAD = ['GET', 'HEAD'] + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + // 2 terminated listeners get added per request, + // but only 1 gets removed. If there are 20 redirects, + // 21 listeners will be added. + // See https://github.com/nodejs/undici/issues/1711 + // TODO (fix): Find and fix root cause for leaked listener. + this.setMaxListeners(21) + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted' + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error + + this.connection?.destroy(error) + this.emit('terminated', error) + } +} + +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) + + // 1. Let p be a new promise. + const p = createDeferredPromise() + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject + + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = requestObject[kState] + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } + + // 7. Let responseObject be null. + let responseObject = null + + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null + + // 9. Let locallyAborted be false. + let locallyAborted = false + + // 10. Let controller be null. + let controller = null + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true + + // 2. Assert: controller is non-null. + assert(controller != null) + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason) + } + ) + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch') + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return Promise.resolve() + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject( + Object.assign(new TypeError('fetch failed'), { cause: response.error }) + ) + return Promise.resolve() + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new Response() + responseObject[kState] = response + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + + // 5. Resolve p with responseObject. + p.resolve(responseObject) + } + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) + + // 14. Return p. + return p.promise +} + +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!timingInfo.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { + if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { + performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) + } +} + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // Note: AbortSignal.reason was added in node v17.2.0 + // which would give us an undefined error to reject with. + // Remove this once node v16 is no longer supported. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 1. Reject promise with error. + p.reject(error) + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = responseObject[kState] + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } +} + +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher // undici +}) { + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currenTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + // TODO: What if request.client is null? + request.origin = request.client?.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value) + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language')) { + request.headersList.append('accept-language', '*') + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } + + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO + } + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) + + // 17. Return fetchParam's controller + return fetchParams.controller +} + +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only') + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request) + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } + + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } + + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' + + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' + + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range') + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } +} + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = require('buffer').resolveObjectURL + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) + + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] + + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) + + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' + + // 7. Return a new response whose status message is `OK`, header list is + // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. + const response = makeResponse({ + statusText: 'OK', + headersList: [ + ['content-length', { name: 'Content-Length', value: length }], + ['content-type', { name: 'Content-Type', value: type }] + ] + }) + + response.body = body + + return Promise.resolve(response) + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } +} + +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) + } +} + +// https://fetch.spec.whatwg.org/#fetch-finale +function fetchFinale (fetchParams, response) { + // 1. If response is a network error, then: + if (response.type === 'error') { + // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». + response.urlList = [fetchParams.request.urlList[0]] + + // 2. Set response’s timing info to the result of creating an opaque timing + // info for fetchParams’s timing info. + response.timingInfo = createOpaqueTimingInfo({ + startTime: fetchParams.timingInfo.startTime + }) + } + + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // If fetchParams’s process response end-of-body is not null, + // then queue a fetch task to run fetchParams’s process response + // end-of-body given response with fetchParams’s task destination. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + } + + // 3. If fetchParams’s process response is non-null, then queue a fetch task + // to run fetchParams’s process response given response, with fetchParams’s + // task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => fetchParams.processResponse(response)) + } + + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: + + // 1. Let transformStream be a new a TransformStream. + + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) + } + + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm + // and flushAlgorithm set to processResponseEndOfBody. + const transformStream = new TransformStream({ + start () {}, + transform: identityTransformAlgorithm, + flush: processResponseEndOfBody + }, { + size () { + return 1 + } + }, { + size () { + return 1 + } + }) + + // 4. Set response’s body to the result of piping response’s body through transformStream. + response.body = { stream: response.body.stream.pipeThrough(transformStream) } + } + + // 6. If fetchParams’s process response consume body is non-null, then: + if (fetchParams.processResponseConsumeBody != null) { + // 1. Let processBody given nullOrBytes be this step: run fetchParams’s + // process response consume body given response and nullOrBytes. + const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) + + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) + + // 3. If response’s body is null, then queue a fetch task to run processBody + // given null, with fetchParams’s task destination. + if (response.body == null) { + queueMicrotask(() => processBody(null)) + } else { + // 4. Otherwise, fully read response’s body given processBody, processBodyError, + // and fetchParams’s task destination. + return fullyReadBody(response.body, processBody, processBodyError) + } + return Promise.resolve() + } +} + +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let actualResponse be null. + let actualResponse = null + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy() + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization') + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null) + request.body = safelyExtractBody(request.body.source)[0] + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent')) { + httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since') || + httpRequest.headersList.contains('if-none-match') || + httpRequest.headersList.contains('if-unmodified-since') || + httpRequest.headersList.contains('if-match') || + httpRequest.headersList.contains('if-range')) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control') + ) { + httpRequest.headersList.append('cache-control', 'max-age=0') + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma')) { + httpRequest.headersList.append('pragma', 'no-cache') + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control')) { + httpRequest.headersList.append('cache-control', 'no-cache') + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range')) { + httpRequest.headersList.append('accept-encoding', 'identity') + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding')) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate') + } + } + + httpRequest.headersList.delete('host') + + // 20. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + // 2. If httpRequest’s header list does not contain `Authorization`, then: + // TODO: credentials + } + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache + } + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.mode === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } + + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err) { + if (!this.destroyed) { + this.destroyed = true + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) + } + } + } + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } + + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO + + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO + } + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) + } + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) + } + processEndOfBody() + } catch (err) { + processBodyError(err) + } + })() + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() + + response = makeResponse({ status, statusText, headersList }) + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() + } + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason) + } + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to + // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller + }, + async pull (controller) { + await pullAlgorithm(controller) + }, + async cancel (reason) { + await cancelAlgorithm(reason) + } + }, + { + highWaterMark: 0, + size () { + return 1 + } + } + ) + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream } + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.on('terminated', onAborted) + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + let isFailure + try { + const { done, value } = await fetchParams.controller.next() + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) + + finalizeResponse(fetchParams, response) + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } + } + } + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() + } + + // 20. Return response. + return response + + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + }, + + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } + + let codings = [] + let location = '' + + const headers = new Headers() + + // For H2, the headers are a plain JS object + // We distinguish between them and iterate accordingly + if (Array.isArray(headersList)) { + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()) + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers.append(key, val) + } + } else { + const keys = Object.keys(headersList) + for (const key of keys) { + const val = headersList[key] + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers.append(key, val) + } + } + + this.body = new Readable({ read: resume }) + + const decoders = [] + + const willFollow = request.redirect === 'follow' && + location && + redirectStatusSet.has(status) + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + for (const coding of codings) { + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'deflate') { + decoders.push(zlib.createInflate()) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress()) + } else { + decoders.length = 0 + break + } + } + } + + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + fetchParams.controller.ended = true + + this.body.push(null) + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + this.body?.destroy(error) + + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } + + const headers = new Headers() + + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + + headers.append(key, val) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }) + + return true + } + } + )) + } +} + +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming +} diff --git a/node_modules/undici/lib/fetch/request.js b/node_modules/undici/lib/fetch/request.js new file mode 100644 index 0000000..60e654e --- /dev/null +++ b/node_modules/undici/lib/fetch/request.js @@ -0,0 +1,944 @@ +/* globals AbortController */ + +'use strict' + +const { extractBody, mixinBody, cloneBody } = require('./body') +const { Headers, fill: fillHeaders, HeadersList } = require('./headers') +const { FinalizationRegistry } = require('../compat/dispatcher-weakref')() +const util = require('../core/util') +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer +} = require('./util') +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = require('./constants') +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = require('./symbols') +const { webidl } = require('./webidl') +const { getGlobalOrigin } = require('./global') +const { URLSerializer } = require('./dataURL') +const { kHeadersList } = require('../core/symbols') +const assert = require('assert') +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require('events') + +let TransformStream = globalThis.TransformStream + +const kInit = Symbol('init') +const kAbortController = Symbol('abortController') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) + +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kInit) { + return + } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) + + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) + + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() + } + } + + // 1. Let request be null. + let request = null + + // 2. Let fallbackMode be null. + let fallbackMode = null + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl + + // 4. Let signal be null. + let signal = null + + // 5. If input is a string, then: + if (typeof input === 'string') { + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request) + + // 8. Set request to input’s request. + request = input[kState] + + // 9. Set signal to input’s signal. + signal = input[kSignal] + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin + + // 8. Let window be "client". + let window = 'client' + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: this[kRealm].settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) + + // 13. If init is not empty, then: + if (Object.keys(init).length > 0) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false + + // 4. Set request’s origin to "client". + request.origin = 'client' + + // 5. Set request’s referrer to "client" + request.referrer = 'client' + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) + ) { + request.referrer = 'client' + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer + } + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity !== undefined && init.integrity != null) { + request.integrity = String(init.integrity) + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method + + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(init.method)) { + throw TypeError(`'${init.method}' is not a valid HTTP method.`) + } + + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw TypeError(`'${init.method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + method = normalizeMethod(init.method) + + // 4. Set request’s method to method. + request.method = method + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } + + // 27. Set this’s request to request. + this[kState] = request + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController() + this[kSignal] = ac.signal + this[kSignal][kRealm] = this[kRealm] + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } + + if (signal.aborted) { + ac.abort(signal.reason) + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac + + const acRef = new WeakRef(ac) + const abort = function () { + const ac = acRef.deref() + if (ac !== undefined) { + ac.abort(this.reason) + } + } + + // Third-party AbortControllers may not work with these. + // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. + try { + // If the max amount of listeners is equal to the default, increase it + // This is only available in node >= v19.9.0 + if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(100, signal) + } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(100, signal) + } + } catch {} + + util.addAbortListener(signal, abort) + requestFinalizer.register(ac, { signal, abort }) + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers() + this[kHeaders][kHeadersList] = request.headersList + this[kHeaders][kGuard] = 'request' + this[kHeaders][kRealm] = this[kRealm] + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' + } + + // 32. If init is not empty, then: + if (Object.keys(init).length !== 0) { + // 1. Let headers be a copy of this’s headers and its associated header + // list. + let headers = new Headers(this[kHeaders]) + + // 2. If init["headers"] exists, then set headers to init["headers"]. + if (init.headers !== undefined) { + headers = init.headers + } + + // 3. Empty this’s headers’s header list. + this[kHeaders][kHeadersList].clear() + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers.constructor.name === 'Headers') { + for (const [key, val] of headers) { + this[kHeaders].append(key, val) + } + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers) + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { + this[kHeaders].append('content-type', contentType) + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = require('stream/web').TransformStream + } + + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } + } + + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) + + // The method getter steps are to return this’s request’s method. + return this[kState].method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) + + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) + + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) + + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) + + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) + + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-foward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) + + // The signal getter steps are to return this’s signal. + return this[kSignal] + } + + get body () { + webidl.brandCheck(this, Request) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request) + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + const clonedRequestObject = new Request(kInit) + clonedRequestObject[kState] = clonedRequest + clonedRequestObject[kRealm] = this[kRealm] + clonedRequestObject[kHeaders] = new Headers() + clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList + clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + util.addAbortListener( + this.signal, + () => { + ac.abort(this.signal.reason) + } + ) + } + clonedRequestObject[kSignal] = ac.signal + + // 4. Return clonedRequestObject. + return clonedRequestObject + } +} + +mixinBody(Request) + +function makeRequest (init) { + // https://fetch.spec.whatwg.org/#requests + const request = { + method: 'GET', + localURLsOnly: false, + unsafeRequest: false, + body: null, + client: null, + reservedClient: null, + replacesClientId: '', + window: 'client', + keepalive: false, + serviceWorkers: 'all', + initiator: '', + destination: '', + priority: null, + origin: 'client', + policyContainer: 'client', + referrer: 'client', + referrerPolicy: '', + mode: 'no-cors', + useCORSPreflightFlag: false, + credentials: 'same-origin', + useCredentials: false, + cache: 'default', + redirect: 'follow', + integrity: '', + cryptoGraphicsNonceMetadata: '', + parserMetadata: '', + reloadNavigation: false, + historyNavigation: false, + userActivation: false, + taintedOrigin: false, + redirectCount: 0, + responseTainting: 'basic', + preventNoCacheCacheControlHeaderModification: false, + done: false, + timingAllowFailed: false, + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } + request.url = request.urlList[0] + return request +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body) + } + + // 3. Return newRequest. + return newRequest +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } +}) + +webidl.converters.Request = webidl.interfaceConverter( + Request +) + +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (V instanceof Request) { + return webidl.converters.Request(V) + } + + return webidl.converters.USVString(V) +} + +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) + +// https://fetch.spec.whatwg.org/#requestinit +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + } +]) + +module.exports = { Request, makeRequest } diff --git a/node_modules/undici/lib/fetch/response.js b/node_modules/undici/lib/fetch/response.js new file mode 100644 index 0000000..23cf55c --- /dev/null +++ b/node_modules/undici/lib/fetch/response.js @@ -0,0 +1,575 @@ +'use strict' + +const { Headers, HeadersList, fill } = require('./headers') +const { extractBody, cloneBody, mixinBody } = require('./body') +const util = require('../core/util') +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode +} = require('./util') +const { + redirectStatusSet, + nullBodyStatus, + DOMException +} = require('./constants') +const { kState, kHeaders, kGuard, kRealm } = require('./symbols') +const { webidl } = require('./webidl') +const { FormData } = require('./formdata') +const { getGlobalOrigin } = require('./global') +const { URLSerializer } = require('./dataURL') +const { kHeadersList } = require('../core/symbols') +const assert = require('assert') +const { types } = require('util') + +const ReadableStream = globalThis.ReadableStream || require('stream/web').ReadableStream +const textEncoder = new TextEncoder('utf-8') + +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} } + + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = new Response() + responseObject[kState] = makeNetworkError() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const relevantRealm = { settingsObject: {} } + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'response' + responseObject[kHeaders][kRealm] = relevantRealm + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + const relevantRealm = { settingsObject: {} } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) + + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, getGlobalOrigin()) + } catch (err) { + throw Object.assign(new TypeError('Failed to parse URL from ' + url), { + cause: err + }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError('Invalid status code ' + status) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) + } + + init = webidl.converters.ResponseInit(init) + + // TODO + this[kRealm] = { settingsObject: {} } + + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers() + this[kHeaders][kGuard] = 'response' + this[kHeaders][kHeadersList] = this[kState].headersList + this[kHeaders][kRealm] = this[kRealm] + + // 3. Let bodyWithType be null. + let bodyWithType = null + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) + + // The type getter steps are to return this’s response’s type. + return this[kState].type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) + + const urlList = this[kState].urlList + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) + + // The status getter steps are to return this’s response’s status. + return this[kState].status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) + + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + get body () { + webidl.brandCheck(this, Response) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || (this.body && this.body.locked)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + const clonedResponseObject = new Response() + clonedResponseObject[kState] = clonedResponse + clonedResponseObject[kRealm] = this[kRealm] + clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList + clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + return clonedResponseObject + } +} + +mixinBody(Response) + +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } +}) + +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) + +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body) + } + + // 4. Return newResponse. + return newResponse +} + +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList(), + urlList: init.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) +} + +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} + +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) +} + +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kHeaders], init.headers) + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: 'Invalid response status code ' + response.status + }) + } + + // 2. Set response's body to body's body. + response[kState].body = body.body + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('Content-Type')) { + response[kState].headersList.append('content-type', body.type) + } + } +} + +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) + +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) + +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) + +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + types.isAnyArrayBuffer(V) || + types.isTypedArray(V) || + types.isDataView(V) + ) { + return webidl.converters.BufferSource(V) + } + + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) + } + + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) + } + + return webidl.converters.DOMString(V) +} + +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V) +} + +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) + +module.exports = { + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse +} diff --git a/node_modules/undici/lib/fetch/symbols.js b/node_modules/undici/lib/fetch/symbols.js new file mode 100644 index 0000000..0b947d5 --- /dev/null +++ b/node_modules/undici/lib/fetch/symbols.js @@ -0,0 +1,10 @@ +'use strict' + +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') +} diff --git a/node_modules/undici/lib/fetch/util.js b/node_modules/undici/lib/fetch/util.js new file mode 100644 index 0000000..033fa20 --- /dev/null +++ b/node_modules/undici/lib/fetch/util.js @@ -0,0 +1,1046 @@ +'use strict' + +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require('./constants') +const { getGlobalOrigin } = require('./global') +const { performance } = require('perf_hooks') +const { isBlobLike, toUSVString, ReadableStreamFrom } = require('../core/util') +const assert = require('assert') +const { isUint8Array } = require('util/types') + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto + +try { + crypto = require('crypto') +} catch { + +} + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location') + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + location = new URL(location, responseURL(response)) + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } + + // 5. Return location. + return location +} + +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} + +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' +} + +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} + +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true +} + +function isTokenChar (c) { + return !( + c >= 0x7f || + c <= 0x20 || + c === '(' || + c === ')' || + c === '<' || + c === '>' || + c === '@' || + c === ',' || + c === ';' || + c === ':' || + c === '\\' || + c === '"' || + c === '/' || + c === '[' || + c === ']' || + c === '?' || + c === '=' || + c === '{' || + c === '}' + ) +} + +// See RFC 7230, Section 3.2.6. +// https://github.com/chromium/chromium/blob/d7da0240cae77824d1eda25745c4022757499131/third_party/blink/renderer/platform/network/http_parsers.cc#L321 +function isValidHTTPToken (characters) { + if (!characters || typeof characters !== 'string') { + return false + } + for (let i = 0; i < characters.length; ++i) { + const c = characters.charCodeAt(i) + if (c > 0x7f || !isTokenChar(c)) { + return false + } + } + return true +} + +// https://fetch.spec.whatwg.org/#header-name +// https://github.com/chromium/chromium/blob/b3d37e6f94f87d59e44662d6078f6a12de845d17/net/http/http_util.cc#L342 +function isValidHeaderName (potentialValue) { + if (potentialValue.length === 0) { + return false + } + + return isValidHTTPToken(potentialValue) +} + +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + if ( + potentialValue.startsWith('\t') || + potentialValue.startsWith(' ') || + potentialValue.endsWith('\t') || + potentialValue.endsWith(' ') + ) { + return false + } + + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false + } + + return true +} + +// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = '' + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.has(token)) { + policy = token + break + } + } + } + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} + +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} + +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} + +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} + +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header) + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} + +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. + let serializedOrigin = request.origin + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + if (serializedOrigin) { + request.headersList.append('origin', serializedOrigin) + } + + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } + + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin) + } + } +} + +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} + +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} + +// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer +function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) + + // 2. Let environment be request’s client. + + let referrerSource = null + + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin() + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin + } +} + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ +function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL) + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = '' + + // 4. Set url’s password to the empty string. + url.password = '' + + // 5. Set url’s fragment to null. + url.hash = '' + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' + + // 2. Set url’s query to null. + url.search = '' + } + + // 7. Return url. + return url +} + +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } + + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // If scheme is data, return true + if (url.protocol === 'data:') return true + + // If file, return true + if (url.protocol === 'file:') return true + + return isOriginPotentiallyTrustworthy(url.origin) + + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false + + const originAsURL = new URL(origin) + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true + } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false + } +} + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ +function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } + + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) + + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } + + // 3. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 4. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const list = parsedMetadata.sort((c, d) => d.algo.localeCompare(c.algo)) + // get the strongest algorithm + const strongest = list[0].algo + // get all entries that use the strongest algorithm; ignore weaker + const metadata = list.filter((item) => item.algo === strongest) + + // 5. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo + + // 2. Let expectedValue be the val component of item. + let expectedValue = item.hash + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + if (expectedValue.endsWith('==')) { + expectedValue = expectedValue.slice(0, -2) + } + + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + + if (actualValue.endsWith('==')) { + actualValue = actualValue.slice(0, -2) + } + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (actualValue === expectedValue) { + return true + } + + let actualBase64URL = crypto.createHash(algorithm).update(bytes).digest('base64url') + + if (actualBase64URL.endsWith('==')) { + actualBase64URL = actualBase64URL.slice(0, -2) + } + + if (actualBase64URL === expectedValue) { + return true + } + } + + // 6. Return false. + return false +} + +// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options +// https://www.w3.org/TR/CSP2/#source-list-syntax +// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 +const parseHashWithOptions = /((?sha256|sha384|sha512)-(?[A-z0-9+/]{1}.*={0,2}))( +[\x21-\x7e]?)?/i + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = [] + + // 2. Let empty be equal to true. + let empty = true + + const supportedHashes = crypto.getHashes() + + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) + + // 3. If token does not parse, continue to the next token. + if (parsedToken === null || parsedToken.groups === undefined) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } + + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm.toLowerCase())) { + result.push(parsedToken.groups) + } + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true + } + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false +} + +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) + + return { promise, resolve: res, reject: rej } +} + +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} + +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +// https://fetch.spec.whatwg.org/#concept-method-normalize +function normalizeMethod (method) { + return /^(DELETE|GET|HEAD|OPTIONS|POST|PUT)$/i.test(method) + ? method.toUpperCase() + : method +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result +} + +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {() => unknown[]} iterator + * @param {string} name name of the instance + * @param {'key'|'value'|'key+value'} kind + */ +function makeIterator (iterator, name, kind) { + const object = { + index: 0, + kind, + target: iterator + } + + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + + // 2. Let thisValue be the this value. + + // 3. Let object be ? ToObject(thisValue). + + // 4. If object is a platform object, then perform a security + // check, passing: + + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const { index, kind, target } = object + const values = target() + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { value: undefined, done: true } + } + + // 11. Let pair be the entry in values at index index. + const pair = values[index] + + // 12. Set object’s index to index + 1. + object.index = index + 1 + + // 13. Return the iterator result for pair and kind. + return iteratorResult(pair, kind) + }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". + [Symbol.toStringTag]: `${name} Iterator` + } + + // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. + Object.setPrototypeOf(i, esIteratorPrototype) + // esIteratorPrototype needs to be the prototype of i + // which is the prototype of an empty object. Yes, it's confusing. + return Object.setPrototypeOf({}, i) +} + +// https://webidl.spec.whatwg.org/#iterator-result +function iteratorResult (pair, kind) { + let result + + // 1. Let result be a value determined by the value of kind: + switch (kind) { + case 'key': { + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = pair[0] + break + } + case 'value': { + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = pair[1] + break + } + case 'key+value': { + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = pair + break + } + } + + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } +} + +/** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +async function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError + + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader + + try { + reader = body.stream.getReader() + } catch (e) { + errorSteps(e) + return + } + + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + const result = await readAllBytes(reader) + successSteps(result) + } catch (e) { + errorSteps(e) + } +} + +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream + +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} + +const MAXIMUM_ARGUMENT_LENGTH = 65535 + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {number[]|Uint8Array} input + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + + if (input.length < MAXIMUM_ARGUMENT_LENGTH) { + return String.fromCharCode(...input) + } + + return input.reduce((previous, current) => previous + String.fromCharCode(current), '') +} + +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed')) { + throw err + } + } +} + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + for (let i = 0; i < input.length; i++) { + assert(input.charCodeAt(i) <= 0xFF) + } + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} + +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + */ +async function readAllBytes (reader) { + const bytes = [] + let byteLength = 0 + + while (true) { + const { done, value: chunk } = await reader.read() + + if (done) { + // 1. Call successSteps with bytes. + return Buffer.concat(bytes, byteLength) + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + throw new TypeError('Received non-Uint8Array chunk') + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } +} + +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} + +/** + * @param {string|URL} url + */ +function urlHasHttpsScheme (url) { + if (typeof url === 'string') { + return url.startsWith('https:') + } + + return url.protocol === 'https:' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'http:' || protocol === 'https:' +} + +/** + * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. + */ +const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) + +module.exports = { + isAborted, + isCancelled, + createDeferredPromise, + ReadableStreamFrom, + toUSVString, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + makeIterator, + isValidHeaderName, + isValidHeaderValue, + hasOwn, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + isomorphicDecode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes +} diff --git a/node_modules/undici/lib/fetch/webidl.js b/node_modules/undici/lib/fetch/webidl.js new file mode 100644 index 0000000..38a05e6 --- /dev/null +++ b/node_modules/undici/lib/fetch/webidl.js @@ -0,0 +1,648 @@ +'use strict' + +const { types } = require('util') +const { hasOwn, toUSVString } = require('./util') + +/** @type {import('../../types/webidl').Webidl} */ +const webidl = {} +webidl.converters = {} +webidl.util = {} +webidl.errors = {} + +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} + +webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of' + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.` + + return webidl.errors.exception({ + header: context.prefix, + message + }) +} + +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I, opts = undefined) { + if (opts?.strict !== false && !(V instanceof I)) { + throw new TypeError('Illegal invocation') + } else { + return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] + } +} + +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + ...ctx + }) + } +} + +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) +} + +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } + + return 'Object' + } + } +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { + let upperBound + let lowerBound + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0 + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V) + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${V} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r +} + +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: 'Sequence', + message: `Value of type ${webidl.util.Type(V)} is not an Object.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = V?.[Symbol.iterator]?.() + const seq = [] + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: 'Sequence', + message: 'Object is not an iterator.' + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value)) + } + + return seq + } +} + +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: 'Record', + message: `Value of type ${webidl.util.Type(O)} is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {} + + if (!types.isProxy(O)) { + // Object.keys only returns enumerable properties + const keys = Object.keys(O) + + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + } + + // 5. Return result. + return result + } +} + +webidl.interfaceConverter = function (i) { + return (V, opts = {}) => { + if (opts.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: i.name, + message: `Expected ${V} to be an instance of ${i.name}.` + }) + } + + return V + } +} + +webidl.dictionaryConverter = function (converters) { + return (dictionary) => { + const type = webidl.util.Type(dictionary) + const dict = {} + + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options + + if (required === true) { + if (!hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key] + const hasDefault = hasOwn(options, 'defaultValue') + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value = value ?? defaultValue + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value) + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value + } + } + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V + } + + return converter(V) + } +} + +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, opts = {}) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts.legacyNullToEmptyString) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw new TypeError('Could not convert argument of type symbol to string.') + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) +} + +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + const charCode = x.charCodeAt(index) + + if (charCode > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${charCode} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x +} + +// https://webidl.spec.whatwg.org/#es-USVString +webidl.converters.USVString = toUSVString + +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V) + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} + +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V +} + +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed') + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned') + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned') + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix: `${V}`, + argument: `${V}`, + types: ['ArrayBuffer'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + // Note: resizable ArrayBuffers are currently a proposal. + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +webidl.converters.TypedArray = function (V, T, opts = {}) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix: `${T.name}`, + argument: `${V}`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable array buffers are currently a proposal + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V +} + +webidl.converters.DataView = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: 'DataView', + message: 'Object is not a DataView.' + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable ArrayBuffers are currently a proposal + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, opts = {}) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, opts) + } + + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor) + } + + if (types.isDataView(V)) { + return webidl.converters.DataView(V, opts) + } + + throw new TypeError(`Could not convert ${V} to a BufferSource.`) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) + +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) + +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) + +module.exports = { + webidl +} diff --git a/node_modules/undici/lib/fileapi/encoding.js b/node_modules/undici/lib/fileapi/encoding.js new file mode 100644 index 0000000..1d1d2b6 --- /dev/null +++ b/node_modules/undici/lib/fileapi/encoding.js @@ -0,0 +1,290 @@ +'use strict' + +/** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ +function getEncoding (label) { + if (!label) { + return 'failure' + } + + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' + } +} + +module.exports = { + getEncoding +} diff --git a/node_modules/undici/lib/fileapi/filereader.js b/node_modules/undici/lib/fileapi/filereader.js new file mode 100644 index 0000000..cd36a22 --- /dev/null +++ b/node_modules/undici/lib/fileapi/filereader.js @@ -0,0 +1,344 @@ +'use strict' + +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = require('./util') +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = require('./symbols') +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../core/util') + +class FileReader extends EventTarget { + constructor () { + super() + + this[kState] = 'empty' + this[kResult] = null + this[kError] = null + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding) + } + + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding) + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL') + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null + return + } + + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done' + this[kResult] = null + } + + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true + + // 4. Terminate the algorithm for the read method being processed. + // TODO + + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) + + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader) + + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader) + + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader) + + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] + } + + get onloadend () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadend + } + + set onloadend (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend) + } + + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null + } + } + + get onerror () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].error + } + + set onerror (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error) + } + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null + } + } + + get onloadstart () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadstart + } + + set onloadstart (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart) + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null + } + } + + get onprogress () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].progress + } + + set onprogress (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) + } + + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null + } + } + + get onload () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].load + } + + set onload (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) + } + + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null + } + } + + get onabort () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].abort + } + + set onabort (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort) + } + + if (typeof fn === 'function') { + this[kEvents].abort = fn + this.addEventListener('abort', fn) + } else { + this[kEvents].abort = null + } + } +} + +// https://w3c.github.io/FileAPI/#dom-filereader-empty +FileReader.EMPTY = FileReader.prototype.EMPTY = 0 +// https://w3c.github.io/FileAPI/#dom-filereader-loading +FileReader.LOADING = FileReader.prototype.LOADING = 1 +// https://w3c.github.io/FileAPI/#dom-filereader-done +FileReader.DONE = FileReader.prototype.DONE = 2 + +Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) + +module.exports = { + FileReader +} diff --git a/node_modules/undici/lib/fileapi/progressevent.js b/node_modules/undici/lib/fileapi/progressevent.js new file mode 100644 index 0000000..778cf22 --- /dev/null +++ b/node_modules/undici/lib/fileapi/progressevent.js @@ -0,0 +1,78 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') + +const kState = Symbol('ProgressEvent state') + +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) + + super(type, eventInitDict) + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + } + } + + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].lengthComputable + } + + get loaded () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].loaded + } + + get total () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].total + } +} + +webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +]) + +module.exports = { + ProgressEvent +} diff --git a/node_modules/undici/lib/fileapi/symbols.js b/node_modules/undici/lib/fileapi/symbols.js new file mode 100644 index 0000000..dd11746 --- /dev/null +++ b/node_modules/undici/lib/fileapi/symbols.js @@ -0,0 +1,10 @@ +'use strict' + +module.exports = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') +} diff --git a/node_modules/undici/lib/fileapi/util.js b/node_modules/undici/lib/fileapi/util.js new file mode 100644 index 0000000..1d10899 --- /dev/null +++ b/node_modules/undici/lib/fileapi/util.js @@ -0,0 +1,392 @@ +'use strict' + +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = require('./symbols') +const { ProgressEvent } = require('./progressevent') +const { getEncoding } = require('./encoding') +const { DOMException } = require('../fetch/constants') +const { serializeAMimeType, parseMIMEType } = require('../fetch/dataURL') +const { types } = require('util') +const { StringDecoder } = require('string_decoder') +const { btoa } = require('buffer') + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +/** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ +function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading' + + // 3. Set fr’s result to null. + fr[kResult] = null + + // 4. Set fr’s error to null. + fr[kError] = null + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream() + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader() + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = [] + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr) + }) + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value) + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now() + queueMicrotask(() => { + fireAProgressEvent('progress', fr) + }) + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read() + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName) + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr) + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Set fr’s error to error. + fr[kError] = error + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } + })() +} + +/** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ +function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }) + + reader.dispatchEvent(event) +} + +/** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ +function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: + + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:' + + const parsed = parseMIMEType(mimeType || 'application/octet-stream') + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed) + } + + dataURL += ';base64,' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)) + } + + dataURL += btoa(decoder.end()) + + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure' + + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName) + } + + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType) + + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')) + } + } + + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8' + } + + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) + } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes) + + return sequence.buffer + } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = '' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + binaryString += decoder.write(chunk) + } + + binaryString += decoder.end() + + return binaryString + } + } +} + +/** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ +function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue) + + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes) + + let slice = 0 + + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding + + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2 + } + + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". + + // 4. Return output. + + const sliced = bytes.slice(slice) + return new TextDecoder(encoding).decode(sliced) +} + +/** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ +function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue + + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } + + return null +} + +/** + * @param {Uint8Array[]} sequences + */ +function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0) + + let offset = 0 + + return sequences.reduce((a, b) => { + a.set(b, offset) + offset += b.byteLength + return a + }, new Uint8Array(size)) +} + +module.exports = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} diff --git a/node_modules/undici/lib/global.js b/node_modules/undici/lib/global.js new file mode 100644 index 0000000..18bfd73 --- /dev/null +++ b/node_modules/undici/lib/global.js @@ -0,0 +1,32 @@ +'use strict' + +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = require('./core/errors') +const Agent = require('./agent') + +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) +} + +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) +} + +function getGlobalDispatcher () { + return globalThis[globalDispatcher] +} + +module.exports = { + setGlobalDispatcher, + getGlobalDispatcher +} diff --git a/node_modules/undici/lib/handler/DecoratorHandler.js b/node_modules/undici/lib/handler/DecoratorHandler.js new file mode 100644 index 0000000..9d70a76 --- /dev/null +++ b/node_modules/undici/lib/handler/DecoratorHandler.js @@ -0,0 +1,35 @@ +'use strict' + +module.exports = class DecoratorHandler { + constructor (handler) { + this.handler = handler + } + + onConnect (...args) { + return this.handler.onConnect(...args) + } + + onError (...args) { + return this.handler.onError(...args) + } + + onUpgrade (...args) { + return this.handler.onUpgrade(...args) + } + + onHeaders (...args) { + return this.handler.onHeaders(...args) + } + + onData (...args) { + return this.handler.onData(...args) + } + + onComplete (...args) { + return this.handler.onComplete(...args) + } + + onBodySent (...args) { + return this.handler.onBodySent(...args) + } +} diff --git a/node_modules/undici/lib/handler/RedirectHandler.js b/node_modules/undici/lib/handler/RedirectHandler.js new file mode 100644 index 0000000..baca27e --- /dev/null +++ b/node_modules/undici/lib/handler/RedirectHandler.js @@ -0,0 +1,216 @@ +'use strict' + +const util = require('../core/util') +const { kBodyUsed } = require('../core/symbols') +const assert = require('assert') +const { InvalidArgumentError } = require('../core/errors') +const EE = require('events') + +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] + +const kBody = Symbol('body') + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + util.validateHandler(handler, opts.method, opts.upgrade) + + this.dispatch = dispatch + this.location = null + this.abort = null + this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] + + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) + } + } + + onConnect (abort) { + this.abort = abort + this.handler.onConnect(abort, { history: this.history }) + } + + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket) + } + + onError (error) { + this.handler.onError(error) + } + + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers) + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) + } + + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) + } + + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.maxRedirections = 0 + this.opts.query = null + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + this.opts.body = null + } + } + + onData (chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response bodies. + + Redirection is used to serve the requested resource from another URL, so it is assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. + + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. + + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitily chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + return this.handler.onData(chunk) + } + } + + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed informations. + */ + + this.location = null + this.abort = null + + this.dispatch(this.opts, this) + } else { + this.handler.onComplete(trailers) + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk) + } + } +} + +function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } + + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toString().toLowerCase() === 'location') { + return headers[i + 1] + } + } +} + +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + return ( + (header.length === 4 && header.toString().toLowerCase() === 'host') || + (removeContent && header.toString().toLowerCase().indexOf('content-') === 0) || + (unknownOrigin && header.length === 13 && header.toString().toLowerCase() === 'authorization') || + (unknownOrigin && header.length === 6 && header.toString().toLowerCase() === 'cookie') + ) +} + +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret +} + +module.exports = RedirectHandler diff --git a/node_modules/undici/lib/interceptor/redirectInterceptor.js b/node_modules/undici/lib/interceptor/redirectInterceptor.js new file mode 100644 index 0000000..7cc035e --- /dev/null +++ b/node_modules/undici/lib/interceptor/redirectInterceptor.js @@ -0,0 +1,21 @@ +'use strict' + +const RedirectHandler = require('../handler/RedirectHandler') + +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } +} + +module.exports = createRedirectInterceptor diff --git a/node_modules/undici/lib/llhttp/constants.d.ts b/node_modules/undici/lib/llhttp/constants.d.ts new file mode 100644 index 0000000..b75ab1b --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.d.ts @@ -0,0 +1,199 @@ +import { IEnumMap } from './utils'; +export declare type HTTPMode = 'loose' | 'strict'; +export declare enum ERROR { + OK = 0, + INTERNAL = 1, + STRICT = 2, + LF_EXPECTED = 3, + UNEXPECTED_CONTENT_LENGTH = 4, + CLOSED_CONNECTION = 5, + INVALID_METHOD = 6, + INVALID_URL = 7, + INVALID_CONSTANT = 8, + INVALID_VERSION = 9, + INVALID_HEADER_TOKEN = 10, + INVALID_CONTENT_LENGTH = 11, + INVALID_CHUNK_SIZE = 12, + INVALID_STATUS = 13, + INVALID_EOF_STATE = 14, + INVALID_TRANSFER_ENCODING = 15, + CB_MESSAGE_BEGIN = 16, + CB_HEADERS_COMPLETE = 17, + CB_MESSAGE_COMPLETE = 18, + CB_CHUNK_HEADER = 19, + CB_CHUNK_COMPLETE = 20, + PAUSED = 21, + PAUSED_UPGRADE = 22, + PAUSED_H2_UPGRADE = 23, + USER = 24 +} +export declare enum TYPE { + BOTH = 0, + REQUEST = 1, + RESPONSE = 2 +} +export declare enum FLAGS { + CONNECTION_KEEP_ALIVE = 1, + CONNECTION_CLOSE = 2, + CONNECTION_UPGRADE = 4, + CHUNKED = 8, + UPGRADE = 16, + CONTENT_LENGTH = 32, + SKIPBODY = 64, + TRAILING = 128, + TRANSFER_ENCODING = 512 +} +export declare enum LENIENT_FLAGS { + HEADERS = 1, + CHUNKED_LENGTH = 2, + KEEP_ALIVE = 4 +} +export declare enum METHODS { + DELETE = 0, + GET = 1, + HEAD = 2, + POST = 3, + PUT = 4, + CONNECT = 5, + OPTIONS = 6, + TRACE = 7, + COPY = 8, + LOCK = 9, + MKCOL = 10, + MOVE = 11, + PROPFIND = 12, + PROPPATCH = 13, + SEARCH = 14, + UNLOCK = 15, + BIND = 16, + REBIND = 17, + UNBIND = 18, + ACL = 19, + REPORT = 20, + MKACTIVITY = 21, + CHECKOUT = 22, + MERGE = 23, + 'M-SEARCH' = 24, + NOTIFY = 25, + SUBSCRIBE = 26, + UNSUBSCRIBE = 27, + PATCH = 28, + PURGE = 29, + MKCALENDAR = 30, + LINK = 31, + UNLINK = 32, + SOURCE = 33, + PRI = 34, + DESCRIBE = 35, + ANNOUNCE = 36, + SETUP = 37, + PLAY = 38, + PAUSE = 39, + TEARDOWN = 40, + GET_PARAMETER = 41, + SET_PARAMETER = 42, + REDIRECT = 43, + RECORD = 44, + FLUSH = 45 +} +export declare const METHODS_HTTP: METHODS[]; +export declare const METHODS_ICE: METHODS[]; +export declare const METHODS_RTSP: METHODS[]; +export declare const METHOD_MAP: IEnumMap; +export declare const H_METHOD_MAP: IEnumMap; +export declare enum FINISH { + SAFE = 0, + SAFE_WITH_CB = 1, + UNSAFE = 2 +} +export declare type CharList = Array; +export declare const ALPHA: CharList; +export declare const NUM_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const HEX_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; +}; +export declare const NUM: CharList; +export declare const ALPHANUM: CharList; +export declare const MARK: CharList; +export declare const USERINFO_CHARS: CharList; +export declare const STRICT_URL_CHAR: CharList; +export declare const URL_CHAR: CharList; +export declare const HEX: CharList; +export declare const STRICT_TOKEN: CharList; +export declare const TOKEN: CharList; +export declare const HEADER_CHARS: CharList; +export declare const CONNECTION_TOKEN_CHARS: CharList; +export declare const MAJOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const MINOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare enum HEADER_STATE { + GENERAL = 0, + CONNECTION = 1, + CONTENT_LENGTH = 2, + TRANSFER_ENCODING = 3, + UPGRADE = 4, + CONNECTION_KEEP_ALIVE = 5, + CONNECTION_CLOSE = 6, + CONNECTION_UPGRADE = 7, + TRANSFER_ENCODING_CHUNKED = 8 +} +export declare const SPECIAL_HEADERS: { + connection: HEADER_STATE; + 'content-length': HEADER_STATE; + 'proxy-connection': HEADER_STATE; + 'transfer-encoding': HEADER_STATE; + upgrade: HEADER_STATE; +}; diff --git a/node_modules/undici/lib/llhttp/constants.js b/node_modules/undici/lib/llhttp/constants.js new file mode 100644 index 0000000..fb0b5a2 --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.js @@ -0,0 +1,278 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = require("./utils"); +// C headers +var ERROR; +(function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; +})(ERROR = exports.ERROR || (exports.ERROR = {})); +var TYPE; +(function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; +})(TYPE = exports.TYPE || (exports.TYPE = {})); +var FLAGS; +(function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; +})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); +var LENIENT_FLAGS; +(function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; +})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); +var METHODS; +(function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; +})(METHODS = exports.METHODS || (exports.METHODS = {})); +exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, +]; +exports.METHODS_ICE = [ + METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, +]; +exports.METHOD_MAP = utils_1.enumToMap(METHODS); +exports.H_METHOD_MAP = {}; +Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } +}); +var FINISH; +(function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; +})(FINISH = exports.FINISH || (exports.FINISH = {})); +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); +// All characters with 0x80 bit set to 1 +for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); +} +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +var HEADER_STATE; +(function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; +})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); +exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, +}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/constants.js.map b/node_modules/undici/lib/llhttp/constants.js.map new file mode 100644 index 0000000..6ac54bc --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/llhttp/constants.ts"],"names":[],"mappings":";;;AAAA,mCAA8C;AAI9C,YAAY;AAEZ,IAAY,KA6BX;AA7BD,WAAY,KAAK;IACf,6BAAM,CAAA;IACN,y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E,CAAC,CAAC;AAE3C,QAAA,KAAK,GAAG,eAAO,CAAC;AAChB,QAAA,KAAK,GAAG,aAAK,CAAC;AAE3B,IAAY,YAWX;AAXD,WAAY,YAAY;IACtB,qDAAW,CAAA;IACX,2DAAU,CAAA;IACV,mEAAc,CAAA;IACd,yEAAiB,CAAA;IACjB,qDAAO,CAAA;IAEP,iFAAqB,CAAA;IACrB,uEAAgB,CAAA;IAChB,2EAAkB,CAAA;IAClB,yFAAyB,CAAA;AAC3B,CAAC,EAXW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAWvB;AAEY,QAAA,eAAe,GAAG;IAC7B,YAAY,EAAE,YAAY,CAAC,UAAU;IACrC,gBAAgB,EAAE,YAAY,CAAC,cAAc;IAC7C,kBAAkB,EAAE,YAAY,CAAC,UAAU;IAC3C,mBAAmB,EAAE,YAAY,CAAC,iBAAiB;IACnD,SAAS,EAAE,YAAY,CAAC,OAAO;CAChC,CAAC"} \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/llhttp-wasm.js b/node_modules/undici/lib/llhttp/llhttp-wasm.js new file mode 100644 index 0000000..ad4682c --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp-wasm.js @@ -0,0 +1 @@ +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBA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MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh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BHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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kACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAdUB1gHXAdgB2QHaAdsB3AHdAd4B4AHhAeIB4wHkAeUB5gHnAegB6QHqAesB7AHtAe4B7wHwAfEB8gHzAZkCpAKwAv4C/gILIAEiBCACRw3zAUHdAS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ACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAE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AAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=' diff --git a/node_modules/undici/lib/llhttp/llhttp.wasm b/node_modules/undici/lib/llhttp/llhttp.wasm new file mode 100644 index 0000000..fe63282 Binary files /dev/null and b/node_modules/undici/lib/llhttp/llhttp.wasm differ diff --git a/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js b/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js new file mode 100644 index 0000000..017e247 --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js @@ -0,0 +1 @@ +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHB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g0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB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wEhEAwdC0GoASEQDBwLQakBIRAMGwtBqgEhEAwaC0GrASEQDBkLQawBIRAMGAtBrQEhEAwXC0GuASEQDBYLQQEhEAwVC0GvASEQDBQLQbABIRAMEwtBsQEhEAwSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQ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QDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB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ACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxN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UJFSFRUUC9BRFRQLw==' diff --git a/node_modules/undici/lib/llhttp/llhttp_simd.wasm b/node_modules/undici/lib/llhttp/llhttp_simd.wasm new file mode 100644 index 0000000..7aa0b55 Binary files /dev/null and b/node_modules/undici/lib/llhttp/llhttp_simd.wasm differ diff --git a/node_modules/undici/lib/llhttp/utils.d.ts b/node_modules/undici/lib/llhttp/utils.d.ts new file mode 100644 index 0000000..15497f3 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.d.ts @@ -0,0 +1,4 @@ +export interface IEnumMap { + [key: string]: number; +} +export declare function enumToMap(obj: any): IEnumMap; diff --git a/node_modules/undici/lib/llhttp/utils.js b/node_modules/undici/lib/llhttp/utils.js new file mode 100644 index 0000000..8a32e56 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enumToMap = void 0; +function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; +} +exports.enumToMap = enumToMap; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/utils.js.map b/node_modules/undici/lib/llhttp/utils.js.map new file mode 100644 index 0000000..2d7c356 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/llhttp/utils.ts"],"names":[],"mappings":";;;AAIA,SAAgB,SAAS,CAAC,GAAQ;IAChC,MAAM,GAAG,GAAa,EAAE,CAAC;IAEzB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;SAClB;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC;AACb,CAAC;AAXD,8BAWC"} \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/wasm_build_env.txt b/node_modules/undici/lib/llhttp/wasm_build_env.txt new file mode 100644 index 0000000..5f478b5 --- /dev/null +++ b/node_modules/undici/lib/llhttp/wasm_build_env.txt @@ -0,0 +1,32 @@ +alpine-baselayout-data-3.4.0-r0 +musl-1.2.3-r4 +busybox-1.35.0-r29 +busybox-binsh-1.35.0-r29 +alpine-baselayout-3.4.0-r0 +alpine-keys-2.4-r1 +ca-certificates-bundle-20220614-r4 +libcrypto3-3.0.8-r3 +libssl3-3.0.8-r3 +ssl_client-1.35.0-r29 +zlib-1.2.13-r0 +apk-tools-2.12.10-r1 +scanelf-1.3.5-r1 +musl-utils-1.2.3-r4 +libc-utils-0.7.2-r3 +libgcc-12.2.1_git20220924-r4 +libstdc++-12.2.1_git20220924-r4 +libffi-3.4.4-r0 +xz-libs-5.2.9-r0 +libxml2-2.10.4-r0 +zstd-libs-1.5.5-r0 +llvm15-libs-15.0.7-r0 +clang15-libs-15.0.7-r0 +libstdc++-dev-12.2.1_git20220924-r4 +clang15-15.0.7-r0 +lld-libs-15.0.7-r0 +lld-15.0.7-r0 +wasi-libc-0.20220525-r1 +wasi-libcxx-15.0.7-r0 +wasi-libcxxabi-15.0.7-r0 +wasi-compiler-rt-15.0.7-r0 +wasi-sdk-16-r0 diff --git a/node_modules/undici/lib/mock/mock-agent.js b/node_modules/undici/lib/mock/mock-agent.js new file mode 100644 index 0000000..828e8af --- /dev/null +++ b/node_modules/undici/lib/mock/mock-agent.js @@ -0,0 +1,171 @@ +'use strict' + +const { kClients } = require('../core/symbols') +const Agent = require('../agent') +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = require('./mock-symbols') +const MockClient = require('./mock-client') +const MockPool = require('./mock-pool') +const { matchValue, buildMockOptions } = require('./mock-utils') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const Dispatcher = require('../dispatcher') +const Pluralizer = require('./pluralizer') +const PendingInterceptorsFormatter = require('./pending-interceptors-formatter') + +class FakeWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value + } +} + +class MockAgent extends Dispatcher { + constructor (opts) { + super(opts) + + this[kNetConnect] = true + this[kIsMockActive] = true + + // Instantiate Agent and encapsulate + if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts && opts.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent + + this[kClients] = agent[kClients] + this[kOptions] = buildMockOptions(opts) + } + + get (origin) { + let dispatcher = this[kMockAgentGet](origin) + + if (!dispatcher) { + dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + } + return dispatcher + } + + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + return this[kAgent].dispatch(opts, handler) + } + + async close () { + await this[kAgent].close() + this[kClients].clear() + } + + deactivate () { + this[kIsMockActive] = false + } + + activate () { + this[kIsMockActive] = true + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, new FakeWeakRef(dispatcher)) + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const ref = this[kClients].get(origin) + if (ref) { + return ref.deref() + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { + const nonExplicitDispatcher = nonExplicitRef.deref() + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients] + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() + + if (pending.length === 0) { + return + } + + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) + + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + +${pendingInterceptorsFormatter.format(pending)} +`.trim()) + } +} + +module.exports = MockAgent diff --git a/node_modules/undici/lib/mock/mock-client.js b/node_modules/undici/lib/mock/mock-client.js new file mode 100644 index 0000000..5f31215 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-client.js @@ -0,0 +1,59 @@ +'use strict' + +const { promisify } = require('util') +const Client = require('../client') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockClient diff --git a/node_modules/undici/lib/mock/mock-errors.js b/node_modules/undici/lib/mock/mock-errors.js new file mode 100644 index 0000000..5442c0e --- /dev/null +++ b/node_modules/undici/lib/mock/mock-errors.js @@ -0,0 +1,17 @@ +'use strict' + +const { UndiciError } = require('../core/errors') + +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, MockNotMatchedError) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} + +module.exports = { + MockNotMatchedError +} diff --git a/node_modules/undici/lib/mock/mock-interceptor.js b/node_modules/undici/lib/mock/mock-interceptor.js new file mode 100644 index 0000000..781e477 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-interceptor.js @@ -0,0 +1,206 @@ +'use strict' + +const { getResponseData, buildKey, addMockDispatch } = require('./mock-utils') +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = require('./mock-symbols') +const { InvalidArgumentError } = require('../core/errors') +const { buildURL } = require('../core/util') + +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch + } + + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + + this[kMockDispatch].delay = waitInMs + return this + } + + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } + + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes + return this + } +} + +/** + * Defines an interceptor for a Mock + */ +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } + + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false + } + + createMockScopeDispatchData (statusCode, data, responseOptions = {}) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } + + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (statusCode, data, responseOptions) { + if (typeof statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof data === 'undefined') { + throw new InvalidArgumentError('data must be defined') + } + if (typeof responseOptions !== 'object') { + throw new InvalidArgumentError('responseOptions must be an object') + } + } + + /** + * Mock an undici request with a defined reply. + */ + reply (replyData) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyData === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyData(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object') { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const { statusCode, data = '', responseOptions = {} } = resolvedData + this.validateReplyParameters(statusCode, data, responseOptions) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(statusCode, data, responseOptions) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const [statusCode, data = '', responseOptions = {}] = [...arguments] + this.validateReplyParameters(statusCode, data, responseOptions) + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) + return new MockScope(newMockDispatch) + } + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers + return this + } + + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } + + this[kDefaultTrailers] = trailers + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this + } +} + +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope diff --git a/node_modules/undici/lib/mock/mock-pool.js b/node_modules/undici/lib/mock/mock-pool.js new file mode 100644 index 0000000..0a3a7cd --- /dev/null +++ b/node_modules/undici/lib/mock/mock-pool.js @@ -0,0 +1,59 @@ +'use strict' + +const { promisify } = require('util') +const Pool = require('../pool') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockPool diff --git a/node_modules/undici/lib/mock/mock-symbols.js b/node_modules/undici/lib/mock/mock-symbols.js new file mode 100644 index 0000000..8c4cbb6 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-symbols.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') +} diff --git a/node_modules/undici/lib/mock/mock-utils.js b/node_modules/undici/lib/mock/mock-utils.js new file mode 100644 index 0000000..42ea185 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-utils.js @@ -0,0 +1,351 @@ +'use strict' + +const { MockNotMatchedError } = require('./mock-errors') +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = require('./mock-symbols') +const { buildURL, nop } = require('../core/util') +const { STATUS_CODES } = require('http') +const { + types: { + isPromise + } +} = require('util') + +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} + +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} + +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } +} + +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) +} + +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true +} + +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + + const pathSegments = path.split('?') + + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} + +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} + +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } +} + +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath + + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) + } + + return matchedMockDispatches[0] +} + +function addMockDispatch (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch +} + +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) + } +} + +function buildKey (opts) { + const { path, method, body, headers, query } = opts + return { + path, + method, + body, + headers, + query + } +} + +function generateKeyValues (data) { + return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ + ...keyValuePairs, + Buffer.from(`${key}`), + Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) + ], []) +} + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' +} + +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') +} + +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) + + mockDispatch.timesInvoked++ + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)) + return + } + + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.abort = nop + handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData(Buffer.from(responseData)) + handler.onComplete(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true +} + +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } +} + +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} + +function buildMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts + return mockOptions + } +} + +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildMockOptions, + getHeaderByName +} diff --git a/node_modules/undici/lib/mock/pending-interceptors-formatter.js b/node_modules/undici/lib/mock/pending-interceptors-formatter.js new file mode 100644 index 0000000..1bc7539 --- /dev/null +++ b/node_modules/undici/lib/mock/pending-interceptors-formatter.js @@ -0,0 +1,40 @@ +'use strict' + +const { Transform } = require('stream') +const { Console } = require('console') + +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) + } + }) + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? '✅' : '❌', + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) + + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() + } +} diff --git a/node_modules/undici/lib/mock/pluralizer.js b/node_modules/undici/lib/mock/pluralizer.js new file mode 100644 index 0000000..47f150b --- /dev/null +++ b/node_modules/undici/lib/mock/pluralizer.js @@ -0,0 +1,29 @@ +'use strict' + +const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' +} + +const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' +} + +module.exports = class Pluralizer { + constructor (singular, plural) { + this.singular = singular + this.plural = plural + } + + pluralize (count) { + const one = count === 1 + const keys = one ? singulars : plurals + const noun = one ? this.singular : this.plural + return { ...keys, count, noun } + } +} diff --git a/node_modules/undici/lib/node/fixed-queue.js b/node_modules/undici/lib/node/fixed-queue.js new file mode 100644 index 0000000..3572681 --- /dev/null +++ b/node_modules/undici/lib/node/fixed-queue.js @@ -0,0 +1,117 @@ +/* eslint-disable */ + +'use strict' + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048; +const kMask = kSize - 1; + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | [empty] | <-- top | item | | item | +// | [empty] | | item | | item | +// | [empty] | | [empty] | <-- top top --> | [empty] | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | [empty] | | item | +// | [empty] | | item | +// | item | <-- bottom top --> | [empty] | +// | item | | [empty] | +// | [empty] | <-- top bottom --> | item | +// | [empty] | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; + } + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } +} + +module.exports = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } +}; diff --git a/node_modules/undici/lib/pool-base.js b/node_modules/undici/lib/pool-base.js new file mode 100644 index 0000000..2a909ee --- /dev/null +++ b/node_modules/undici/lib/pool-base.js @@ -0,0 +1,194 @@ +'use strict' + +const DispatcherBase = require('./dispatcher-base') +const FixedQueue = require('./node/fixed-queue') +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('./core/symbols') +const PoolStats = require('./pool-stats') + +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') +const kStats = Symbol('stats') + +class PoolBase extends DispatcherBase { + constructor () { + super() + + this[kQueue] = new FixedQueue() + this[kClients] = [] + this[kQueued] = 0 + + const pool = this + + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue] + + let needDrain = false + + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + pool[kQueued]-- + needDrain = !this.dispatch(item.opts, item.handler) + } + + this[kNeedDrain] = needDrain + + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false + pool.emit('drain', origin, [pool, ...targets]) + } + + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]) + } + } + + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err) + } + + this[kStats] = new PoolStats(this) + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } + + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } + + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending + } + return ret + } + + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret + } + + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret + } + + get stats () { + return this[kStats] + } + + async [kClose] () { + if (this[kQueue].isEmpty()) { + return Promise.all(this[kClients].map(c => c.close())) + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve + }) + } + } + + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) + } + + return Promise.all(this[kClients].map(c => c.destroy(err))) + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + process.nextTick(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]) + } + }) + } + + return this + } + + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + } +} + +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} diff --git a/node_modules/undici/lib/pool-stats.js b/node_modules/undici/lib/pool-stats.js new file mode 100644 index 0000000..b4af8ae --- /dev/null +++ b/node_modules/undici/lib/pool-stats.js @@ -0,0 +1,34 @@ +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require('./core/symbols') +const kPool = Symbol('pool') + +class PoolStats { + constructor (pool) { + this[kPool] = pool + } + + get connected () { + return this[kPool][kConnected] + } + + get free () { + return this[kPool][kFree] + } + + get pending () { + return this[kPool][kPending] + } + + get queued () { + return this[kPool][kQueued] + } + + get running () { + return this[kPool][kRunning] + } + + get size () { + return this[kPool][kSize] + } +} + +module.exports = PoolStats diff --git a/node_modules/undici/lib/pool.js b/node_modules/undici/lib/pool.js new file mode 100644 index 0000000..e3cd339 --- /dev/null +++ b/node_modules/undici/lib/pool.js @@ -0,0 +1,94 @@ +'use strict' + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher +} = require('./pool-base') +const Client = require('./client') +const { + InvalidArgumentError +} = require('./core/errors') +const util = require('./core/util') +const { kUrl, kInterceptors } = require('./core/symbols') +const buildConnector = require('./core/connect') + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + ...options + } = {}) { + super() + + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : [] + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2 } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory + } + + [kGetDispatcher] () { + let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + + if (dispatcher) { + return dispatcher + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + } + + return dispatcher + } +} + +module.exports = Pool diff --git a/node_modules/undici/lib/proxy-agent.js b/node_modules/undici/lib/proxy-agent.js new file mode 100644 index 0000000..c710948 --- /dev/null +++ b/node_modules/undici/lib/proxy-agent.js @@ -0,0 +1,187 @@ +'use strict' + +const { kProxy, kClose, kDestroy, kInterceptors } = require('./core/symbols') +const { URL } = require('url') +const Agent = require('./agent') +const Pool = require('./pool') +const DispatcherBase = require('./dispatcher-base') +const { InvalidArgumentError, RequestAbortedError } = require('./core/errors') +const buildConnector = require('./core/connect') + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 +} + +function buildProxyOptions (opts) { + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + return { + uri: opts.uri, + protocol: opts.protocol || 'https' + } +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class ProxyAgent extends DispatcherBase { + constructor (opts) { + super(opts) + this[kProxy] = buildProxyOptions(opts) + this[kAgent] = new Agent(opts) + this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : [] + + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } + + const resolvedUrl = new URL(opts.uri) + const { origin, port, host } = resolvedUrl + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + this[kClient] = clientFactory(resolvedUrl, { connect }) + this[kAgent] = new Agent({ + ...opts, + connect: async (opts, callback) => { + let requestedHost = opts.host + if (!opts.port) { + requestedHost += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedHost, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host + } + }) + if (statusCode !== 200) { + socket.on('error', () => {}).destroy() + callback(new RequestAbortedError('Proxy response !== 200 when HTTP Tunneling')) + } + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + callback(err) + } + } + }) + } + + dispatch (opts, handler) { + const { host } = new URL(opts.origin) + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + return this[kAgent].dispatch( + { + ...opts, + headers: { + ...headers, + host + } + }, + handler + ) + } + + async [kClose] () { + await this[kAgent].close() + await this[kClient].close() + } + + async [kDestroy] () { + await this[kAgent].destroy() + await this[kClient].destroy() + } +} + +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] + } + + return headersPair + } + + return headers +} + +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } +} + +module.exports = ProxyAgent diff --git a/node_modules/undici/lib/timers.js b/node_modules/undici/lib/timers.js new file mode 100644 index 0000000..5782217 --- /dev/null +++ b/node_modules/undici/lib/timers.js @@ -0,0 +1,97 @@ +'use strict' + +let fastNow = Date.now() +let fastNowTimeout + +const fastTimers = [] + +function onTimeout () { + fastNow = Date.now() + + let len = fastTimers.length + let idx = 0 + while (idx < len) { + const timer = fastTimers[idx] + + if (timer.state === 0) { + timer.state = fastNow + timer.delay + } else if (timer.state > 0 && fastNow >= timer.state) { + timer.state = -1 + timer.callback(timer.opaque) + } + + if (timer.state === -1) { + timer.state = -2 + if (idx !== len - 1) { + fastTimers[idx] = fastTimers.pop() + } else { + fastTimers.pop() + } + len -= 1 + } else { + idx += 1 + } + } + + if (fastTimers.length > 0) { + refreshTimeout() + } +} + +function refreshTimeout () { + if (fastNowTimeout && fastNowTimeout.refresh) { + fastNowTimeout.refresh() + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTimeout, 1e3) + if (fastNowTimeout.unref) { + fastNowTimeout.unref() + } + } +} + +class Timeout { + constructor (callback, delay, opaque) { + this.callback = callback + this.delay = delay + this.opaque = opaque + + // -2 not in timer list + // -1 in timer list but inactive + // 0 in timer list waiting for time + // > 0 in timer list waiting for time to expire + this.state = -2 + + this.refresh() + } + + refresh () { + if (this.state === -2) { + fastTimers.push(this) + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + } + + this.state = 0 + } + + clear () { + this.state = -1 + } +} + +module.exports = { + setTimeout (callback, delay, opaque) { + return delay < 1e3 + ? setTimeout(callback, delay, opaque) + : new Timeout(callback, delay, opaque) + }, + clearTimeout (timeout) { + if (timeout instanceof Timeout) { + timeout.clear() + } else { + clearTimeout(timeout) + } + } +} diff --git a/node_modules/undici/lib/websocket/connection.js b/node_modules/undici/lib/websocket/connection.js new file mode 100644 index 0000000..e0fa697 --- /dev/null +++ b/node_modules/undici/lib/websocket/connection.js @@ -0,0 +1,291 @@ +'use strict' + +const diagnosticsChannel = require('diagnostics_channel') +const { uid, states } = require('./constants') +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose +} = require('./symbols') +const { fireEvent, failWebsocketConnection } = require('./util') +const { CloseEvent } = require('./events') +const { makeRequest } = require('../fetch/request') +const { fetching } = require('../fetch/index') +const { Headers } = require('../fetch/headers') +const { getGlobalDispatcher } = require('../global') +const { kHeadersList } = require('../core/symbols') + +const channels = {} +channels.open = diagnosticsChannel.channel('undici:websocket:open') +channels.close = diagnosticsChannel.channel('undici:websocket:close') +channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = require('crypto') +} catch { + +} + +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any) => void} onEstablish + * @param {Partial} options + */ +function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }) + + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = new Headers(options.headers)[kHeadersList] + + request.headersList = headersList + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13') + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + // TODO: enable once permessage-deflate is supported + const permessageDeflate = '' // 'permessage-deflate; 15' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + // request.headersList.append('sec-websocket-extensions', permessageDeflate) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher ?? getGlobalDispatcher(), + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.') + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.') + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') + + if (secExtension !== null && secExtension !== permessageDeflate) { + failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') + return + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') + + if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') + return + } + + response.socket.on('data', onSocketData) + response.socket.on('close', onSocketClose) + response.socket.on('error', onSocketError) + + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }) + } + + onEstablish(response) + } + }) + + return controller +} + +/** + * @param {Buffer} chunk + */ +function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause() + } +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ +function onSocketClose () { + const { ws } = this + + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] && ws[kReceivedClose] + + let code = 1005 + let reason = '' + + const result = ws[kByteParser].closingInfo + + if (result) { + code = result.code ?? 1005 + reason = result.reason + } else if (!ws[kSentClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + } + + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + fireEvent('close', ws, CloseEvent, { + wasClean, code, reason + }) + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }) + } +} + +function onSocketError (error) { + const { ws } = this + + ws[kReadyState] = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error) + } + + this.destroy() +} + +module.exports = { + establishWebSocketConnection +} diff --git a/node_modules/undici/lib/websocket/constants.js b/node_modules/undici/lib/websocket/constants.js new file mode 100644 index 0000000..406b8e3 --- /dev/null +++ b/node_modules/undici/lib/websocket/constants.js @@ -0,0 +1,51 @@ +'use strict' + +// This is a Globally Unique Identifier unique used +// to validate that the endpoint accepts websocket +// connections. +// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 +} + +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA +} + +const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 + +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 +} + +const emptyBuffer = Buffer.allocUnsafe(0) + +module.exports = { + uid, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer +} diff --git a/node_modules/undici/lib/websocket/events.js b/node_modules/undici/lib/websocket/events.js new file mode 100644 index 0000000..621a226 --- /dev/null +++ b/node_modules/undici/lib/websocket/events.js @@ -0,0 +1,303 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../core/util') +const { MessagePort } = require('worker_threads') + +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.MessageEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get data () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent) + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } +} + +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason + } +} + +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) + + super(type, eventInitDict) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict + } + + get message () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.error + } +} + +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) + +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) + +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) + +webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +] + +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + get defaultValue () { + return [] + } + } +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'error', + converter: webidl.converters.any + } +]) + +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent +} diff --git a/node_modules/undici/lib/websocket/frame.js b/node_modules/undici/lib/websocket/frame.js new file mode 100644 index 0000000..d867ad1 --- /dev/null +++ b/node_modules/undici/lib/websocket/frame.js @@ -0,0 +1,73 @@ +'use strict' + +const { maxUnsigned16Bit } = require('./constants') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = require('crypto') +} catch { + +} + +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + this.maskKey = crypto.randomBytes(4) + } + + createFrame (opcode) { + const bodyLength = this.frameData?.byteLength ?? 0 + + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset) + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = this.maskKey[0] + buffer[offset - 3] = this.maskKey[1] + buffer[offset - 2] = this.maskKey[2] + buffer[offset - 1] = this.maskKey[3] + + buffer[1] = payloadLength + + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } + + buffer[1] |= 0x80 // MASK + + // mask body + for (let i = 0; i < bodyLength; i++) { + buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] + } + + return buffer + } +} + +module.exports = { + WebsocketFrameSend +} diff --git a/node_modules/undici/lib/websocket/receiver.js b/node_modules/undici/lib/websocket/receiver.js new file mode 100644 index 0000000..bdd2031 --- /dev/null +++ b/node_modules/undici/lib/websocket/receiver.js @@ -0,0 +1,344 @@ +'use strict' + +const { Writable } = require('stream') +const diagnosticsChannel = require('diagnostics_channel') +const { parserStates, opcodes, states, emptyBuffer } = require('./constants') +const { kReadyState, kSentClose, kResponse, kReceivedClose } = require('./symbols') +const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = require('./util') +const { WebsocketFrameSend } = require('./frame') + +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors + +const channels = {} +channels.ping = diagnosticsChannel.channel('undici:websocket:ping') +channels.pong = diagnosticsChannel.channel('undici:websocket:pong') + +class ByteParser extends Writable { + #buffers = [] + #byteOffset = 0 + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + constructor (ws) { + super() + + this.ws = ws + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length + + this.run(callback) + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (true) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.fin = (buffer[0] & 0x80) !== 0 + this.#info.opcode = buffer[0] & 0x0F + + // If we receive a fragmented message, we use the type of the first + // frame to parse the full message as binary/text, when it's terminated + this.#info.originalOpcode ??= this.#info.opcode + + this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION + + if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') + return + } + + const payloadLength = buffer[1] & 0x7F + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } + + if (this.#info.fragmented && payloadLength > 125) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') + return + } else if ( + (this.#info.opcode === opcodes.PING || + this.#info.opcode === opcodes.PONG || + this.#info.opcode === opcodes.CLOSE) && + payloadLength > 125 + ) { + // Control frames can have a payload length of 125 bytes MAX + failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') + return + } else if (this.#info.opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') + return + } + + const body = this.consume(payloadLength) + + this.#info.closeInfo = this.parseCloseBody(false, body) + + if (!this.ws[kSentClose]) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + const body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + const closeFrame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true + } + } + ) + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING + this.ws[kReceivedClose] = true + + this.end() + + return + } else if (this.#info.opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + const body = this.consume(payloadLength) + + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) + + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }) + } + } + + this.#state = parserStates.INFO + + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } else if (this.#info.opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + + const body = this.consume(payloadLength) + + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }) + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) + + // 2^31 is the maxinimum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') + return + } + + const lower = buffer.readUInt32BE(4) + + this.#info.payloadLength = (upper << 8) + lower + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + // If there is still more data in this chunk that needs to be read + return callback() + } else if (this.#byteOffset >= this.#info.payloadLength) { + // If the server sent multiple frames in a single chunk + + const body = this.consume(this.#info.payloadLength) + + this.#fragments.push(body) + + // If the frame is unfragmented, or a fragmented frame was terminated, + // a message was received + if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { + const fullMessage = Buffer.concat(this.#fragments) + + websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) + + this.#info = {} + this.#fragments.length = 0 + } + + this.#state = parserStates.INFO + } + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + break + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer|null} + */ + consume (n) { + if (n > this.#byteOffset) { + return null + } else if (n === 0) { + return emptyBuffer + } + + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length + return this.#buffers.shift() + } + + const buffer = Buffer.allocUnsafe(n) + let offset = 0 + + while (offset !== n) { + const next = this.#buffers[0] + const { length } = next + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += next.length + } + } + + this.#byteOffset -= n + + return buffer + } + + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } + + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } + + return { code } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } + + if (code !== undefined && !isValidStatusCode(code)) { + return null + } + + try { + // TODO: optimize this + reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) + } catch { + return null + } + + return { code, reason } + } + + get closingInfo () { + return this.#info.closeInfo + } +} + +module.exports = { + ByteParser +} diff --git a/node_modules/undici/lib/websocket/symbols.js b/node_modules/undici/lib/websocket/symbols.js new file mode 100644 index 0000000..11d03e3 --- /dev/null +++ b/node_modules/undici/lib/websocket/symbols.js @@ -0,0 +1,12 @@ +'use strict' + +module.exports = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') +} diff --git a/node_modules/undici/lib/websocket/util.js b/node_modules/undici/lib/websocket/util.js new file mode 100644 index 0000000..6c59b2c --- /dev/null +++ b/node_modules/undici/lib/websocket/util.js @@ -0,0 +1,200 @@ +'use strict' + +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols') +const { states, opcodes } = require('./constants') +const { MessageEvent, ErrorEvent } = require('./events') + +/* globals Blob */ + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN +} + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING +} + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosed (ws) { + return ws[kReadyState] === states.CLOSED +} + +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {EventInit | undefined} eventInitDict + */ +function fireEvent (e, target, eventConstructor = Event, eventInitDict) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ +function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = new Uint8Array(data).buffer + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, MessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }) +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (const char of protocol) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || + code > 0x7E || + char === '(' || + char === ')' || + char === '<' || + char === '>' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' || + code === 32 || // SP + code === 9 // HT + ) { + return false + } + } + + return true +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 +} + +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws + + controller.abort() + + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() + } + + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }) + } +} + +module.exports = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived +} diff --git a/node_modules/undici/lib/websocket/websocket.js b/node_modules/undici/lib/websocket/websocket.js new file mode 100644 index 0000000..e4aa58f --- /dev/null +++ b/node_modules/undici/lib/websocket/websocket.js @@ -0,0 +1,641 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') +const { DOMException } = require('../fetch/constants') +const { URLSerializer } = require('../fetch/dataURL') +const { getGlobalOrigin } = require('../fetch/global') +const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = require('./constants') +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = require('./symbols') +const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = require('./util') +const { establishWebSocketConnection } = require('./connection') +const { WebsocketFrameSend } = require('./frame') +const { ByteParser } = require('./receiver') +const { kEnumerableProperty, isBlobLike } = require('../core/util') +const { getGlobalDispatcher } = require('../global') +const { types } = require('util') + +let experimentalWarned = false + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('WebSockets are experimental, expect them to change at any time.', { + code: 'UNDICI-WS' + }) + } + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) + + url = webidl.converters.USVString(url) + protocols = options.protocols + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = getGlobalOrigin() + + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". + urlRecord.protocol = 'wss:' + } + + // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 9. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href) + + // 11. Let client be this's relevant settings object. + + // 12. Run this step in parallel: + + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob' + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, { clamp: true }) + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason) + } + + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + let reasonByteLength = 0 + + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason) + + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } + + // 3. Run the first matching steps from the following list: + if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { + // If this's ready state is CLOSING (2) or CLOSED (3) + // Do nothing. + } else if (!isEstablished(this)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(this, 'Connection was closed before it was established.') + this[kReadyState] = WebSocket.CLOSING + } else if (!isClosing(this)) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + socket.write(frame.createFrame(opcodes.CLOSE), (err) => { + if (!err) { + this[kSentClose] = true + } + }) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this[kReadyState] = states.CLOSING + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + this[kReadyState] = WebSocket.CLOSING + } + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) + + data = webidl.converters.WebSocketSendData(data) + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (this[kReadyState] === WebSocket.CONNECTING) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this) || isClosing(this)) { + return + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.TEXT) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + const ab = Buffer.from(data, data.byteOffset, data.byteLength) + + const frame = new WebsocketFrameSend(ab) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += ab.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= ab.byteLength + }) + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + const frame = new WebsocketFrameSend() + + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab) + frame.frameData = value + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + }) + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket) + + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket) + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } + + get extensions () { + webidl.brandCheck(this, WebSocket) + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket) + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket) + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket) + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket) + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } + + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket) + + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket) + + return this[kBinaryType] + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket) + + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob' + } else { + this[kBinaryType] = type + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response + + const parser = new ByteParser(this) + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume() + }) + + response.socket.ws = this + this[kByteParser] = parser + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + } +} + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) + +webidl.converters['DOMString or sequence'] = function (V) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } + + return webidl.converters.DOMString(V) +} + +// This implements the propsal made in https://github.com/whatwg/websockets/issues/42 +webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + get defaultValue () { + return [] + } + }, + { + key: 'dispatcher', + converter: (V) => V, + get defaultValue () { + return getGlobalDispatcher() + } + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } +]) + +webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } + + return { protocols: webidl.converters['DOMString or sequence'](V) } +} + +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { + return webidl.converters.BufferSource(V) + } + } + + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket +} diff --git a/node_modules/undici/package.json b/node_modules/undici/package.json new file mode 100644 index 0000000..ea1228f --- /dev/null +++ b/node_modules/undici/package.json @@ -0,0 +1,166 @@ +{ + "name": "undici", + "version": "5.27.2", + "description": "An HTTP/1.1 client, written from scratch for Node.js", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ], + "keywords": [ + "fetch", + "http", + "https", + "promise", + "request", + "curl", + "wget", + "xhr", + "whatwg" + ], + "main": "index.js", + "types": "index.d.ts", + "files": [ + "*.d.ts", + "index.js", + "index-fetch.js", + "lib", + "types", + "docs" + ], + "scripts": { + "build:node": "npx esbuild@0.19.4 index-fetch.js --bundle --platform=node --outfile=undici-fetch.js --define:esbuildDetection=1 --keep-names", + "prebuild:wasm": "node build/wasm.js --prebuild", + "build:wasm": "node build/wasm.js --docker", + "lint": "standard | snazzy", + "lint:fix": "standard --fix | snazzy", + "test": "node scripts/generate-pem && npm run test:tap && npm run test:node-fetch && npm run test:fetch && npm run test:cookies && npm run test:wpt && npm run test:websocket && npm run test:jest && npm run test:typescript", + "test:cookies": "node scripts/verifyVersion 16 || tap test/cookie/*.js", + "test:node-fetch": "node scripts/verifyVersion.js 16 || mocha --exit test/node-fetch", + "test:fetch": "node scripts/verifyVersion.js 16 || (npm run build:node && tap --expose-gc test/fetch/*.js && tap test/webidl/*.js)", + "test:jest": "node scripts/verifyVersion.js 14 || jest", + "test:tap": "tap test/*.js test/diagnostics-channel/*.js", + "test:tdd": "tap test/*.js test/diagnostics-channel/*.js -w", + "test:typescript": "node scripts/verifyVersion.js 14 || tsd && tsc --skipLibCheck test/imports/undici-import.ts", + "test:websocket": "node scripts/verifyVersion.js 18 || tap test/websocket/*.js", + "test:wpt": "node scripts/verifyVersion 18 || (node test/wpt/start-fetch.mjs && node test/wpt/start-FileAPI.mjs && node test/wpt/start-mimesniff.mjs && node test/wpt/start-xhr.mjs && node test/wpt/start-websockets.mjs)", + "coverage": "nyc --reporter=text --reporter=html npm run test", + "coverage:ci": "nyc --reporter=lcov npm run test", + "bench": "PORT=3042 concurrently -k -s first npm:bench:server npm:bench:run", + "bench:server": "node benchmarks/server.js", + "prebench:run": "node benchmarks/wait.js", + "bench:run": "CONNECTIONS=1 node benchmarks/benchmark.js; CONNECTIONS=50 node benchmarks/benchmark.js", + "serve:website": "docsify serve .", + "prepare": "husky install", + "fuzz": "jsfuzz test/fuzzing/fuzz.js corpus" + }, + "devDependencies": { + "@sinonjs/fake-timers": "^11.1.0", + "@types/node": "^18.0.3", + "abort-controller": "^3.0.0", + "atomic-sleep": "^1.0.0", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^3.0.2", + "chai-string": "^1.5.0", + "concurrently": "^8.0.1", + "cronometro": "^1.0.5", + "delay": "^5.0.0", + "dns-packet": "^5.4.0", + "docsify-cli": "^4.4.3", + "form-data": "^4.0.0", + "formdata-node": "^4.3.1", + "https-pem": "^3.0.0", + "husky": "^8.0.1", + "import-fresh": "^3.3.0", + "jest": "^29.0.2", + "jsdom": "^22.1.0", + "jsfuzz": "^1.0.15", + "mocha": "^10.0.0", + "p-timeout": "^3.2.0", + "pre-commit": "^1.2.2", + "proxy": "^1.0.2", + "proxyquire": "^2.1.3", + "semver": "^7.5.4", + "sinon": "^16.1.0", + "snazzy": "^9.0.0", + "standard": "^17.0.0", + "table": "^6.8.0", + "tap": "^16.1.0", + "tsd": "^0.29.0", + "typescript": "^5.0.2", + "wait-on": "^7.0.1", + "ws": "^8.11.0" + }, + "engines": { + "node": ">=14.0" + }, + "standard": { + "env": [ + "mocha" + ], + "ignore": [ + "lib/llhttp/constants.js", + "lib/llhttp/utils.js", + "test/wpt/tests" + ] + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "esModuleInterop": true, + "lib": [ + "esnext" + ] + } + }, + "jest": { + "testMatch": [ + "/test/jest/**" + ] + }, + "dependencies": { + "@fastify/busboy": "^2.0.0" + } +} diff --git a/node_modules/undici/types/README.md b/node_modules/undici/types/README.md new file mode 100644 index 0000000..20a721c --- /dev/null +++ b/node_modules/undici/types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/node_modules/undici/types/agent.d.ts b/node_modules/undici/types/agent.d.ts new file mode 100644 index 0000000..58081ce --- /dev/null +++ b/node_modules/undici/types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from "./dispatcher"; + +export default Agent + +declare class Agent extends Dispatcher{ + constructor(opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean; + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean; + /** Dispatches a request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + /** Integer. Default: `0` */ + maxRedirections?: number; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + /** Integer. */ + maxRedirections?: number; + } +} diff --git a/node_modules/undici/types/api.d.ts b/node_modules/undici/types/api.d.ts new file mode 100644 index 0000000..400341d --- /dev/null +++ b/node_modules/undici/types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +export { + request, + stream, + pipeline, + connect, + upgrade, +} + +/** Performs an HTTP request. */ +declare function request( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit & Partial>, +): Promise; + +/** A faster version of `request`. */ +declare function stream( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + factory: Dispatcher.StreamFactory +): Promise; + +/** For easy use with `stream.pipeline`. */ +declare function pipeline( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + handler: Dispatcher.PipelineHandler +): Duplex; + +/** Starts two-way communications with the requested resource. */ +declare function connect( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; + +/** Upgrade to a different protocol. */ +declare function upgrade( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; diff --git a/node_modules/undici/types/balanced-pool.d.ts b/node_modules/undici/types/balanced-pool.d.ts new file mode 100644 index 0000000..d1e9375 --- /dev/null +++ b/node_modules/undici/types/balanced-pool.d.ts @@ -0,0 +1,18 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +declare class BalancedPool extends Dispatcher { + constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + + addUpstream(upstream: string | URL): BalancedPool; + removeUpstream(upstream: string | URL): BalancedPool; + upstreams: Array; + + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; +} diff --git a/node_modules/undici/types/cache.d.ts b/node_modules/undici/types/cache.d.ts new file mode 100644 index 0000000..4c33335 --- /dev/null +++ b/node_modules/undici/types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/node_modules/undici/types/client.d.ts b/node_modules/undici/types/client.d.ts new file mode 100644 index 0000000..74948b1 --- /dev/null +++ b/node_modules/undici/types/client.d.ts @@ -0,0 +1,97 @@ +import { URL } from 'url' +import { TlsOptions } from 'tls' +import Dispatcher from './dispatcher' +import buildConnector from "./connector"; + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor(url: string | URL, options?: Client.Options); + /** Property to get and set the pipelining factor. */ + pipelining: number; + /** `true` after `client.close()` has been called. */ + closed: boolean; + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean; +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + maxRedirections?: number; + /** TODO */ + connect?: buildConnector.BuildOptions | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overriden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client; diff --git a/node_modules/undici/types/connector.d.ts b/node_modules/undici/types/connector.d.ts new file mode 100644 index 0000000..bd92433 --- /dev/null +++ b/node_modules/undici/types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/node_modules/undici/types/content-type.d.ts b/node_modules/undici/types/content-type.d.ts new file mode 100644 index 0000000..f2a87f1 --- /dev/null +++ b/node_modules/undici/types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/node_modules/undici/types/cookies.d.ts b/node_modules/undici/types/cookies.d.ts new file mode 100644 index 0000000..aa38cae --- /dev/null +++ b/node_modules/undici/types/cookies.d.ts @@ -0,0 +1,28 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void diff --git a/node_modules/undici/types/diagnostics-channel.d.ts b/node_modules/undici/types/diagnostics-channel.d.ts new file mode 100644 index 0000000..85d4482 --- /dev/null +++ b/node_modules/undici/types/diagnostics-channel.d.ts @@ -0,0 +1,67 @@ +import { Socket } from "net"; +import { URL } from "url"; +import Connector from "./connector"; +import Dispatcher from "./dispatcher"; + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: string; + addHeader(key: string, value: string): Request; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + type Error = unknown; + interface ConnectParams { + host: URL["host"]; + hostname: URL["hostname"]; + protocol: URL["protocol"]; + port: URL["port"]; + servername: string | null; + } + type Connector = Connector.connector; + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/node_modules/undici/types/dispatcher.d.ts b/node_modules/undici/types/dispatcher.d.ts new file mode 100644 index 0000000..816db19 --- /dev/null +++ b/node_modules/undici/types/dispatcher.d.ts @@ -0,0 +1,241 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' + +type AbortSignal = unknown; + +export default Dispatcher + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise; + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise; + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + /** Upgrade to a different protocol. */ + upgrade(options: Dispatcher.UpgradeOptions): Promise; + upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close(): Promise; + close(callback: () => void): void; + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + + on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'drain', callback: (origin: URL) => void): this; + + + once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'drain', callback: (origin: URL) => void): this; + + + off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'drain', callback: (origin: URL) => void): this; + + + addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'drain', callback: (origin: URL) => void): this; + + removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; + + listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'drain'): ((origin: URL) => void)[]; + + rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; + + emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; + emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'drain', origin: URL): boolean; +} + +declare namespace Dispatcher { + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/ + expectContinue?: boolean; + } + export interface ConnectOptions { + path: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: unknown; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: unknown; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeader?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: unknown; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: unknown; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable; + export interface DispatchHandlers { + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + onConnect?(abort: () => void): void; + /** Invoked when an error has occurred. */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + onHeaders?(statusCode: number, headers: Buffer[] | string[] | null, resume: () => void): boolean; + /** Invoked when response payload data is received. */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable; + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; // throws on node v16.6.0 + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch'] + } +} diff --git a/node_modules/undici/types/errors.d.ts b/node_modules/undici/types/errors.d.ts new file mode 100644 index 0000000..7923ddd --- /dev/null +++ b/node_modules/undici/types/errors.d.ts @@ -0,0 +1,128 @@ +import { IncomingHttpHeaders } from "./header"; +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string; + code: string; + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError'; + code: 'UND_ERR_CONNECT_TIMEOUT'; + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError'; + code: 'UND_ERR_HEADERS_TIMEOUT'; + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError'; + code: 'UND_ERR_BODY_TIMEOUT'; + } + + export class ResponseStatusCodeError extends UndiciError { + constructor ( + message?: string, + statusCode?: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'ResponseStatusCodeError'; + code: 'UND_ERR_RESPONSE_STATUS_CODE'; + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null; + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError'; + code: 'UND_ERR_INVALID_ARG'; + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError'; + code: 'UND_ERR_INVALID_RETURN_VALUE'; + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError'; + code: 'UND_ERR_ABORTED'; + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError'; + code: 'UND_ERR_INFO'; + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError'; + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError'; + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError'; + code: 'UND_ERR_DESTROYED'; + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError'; + code: 'UND_ERR_CLOSED'; + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError'; + code: 'UND_ERR_SOCKET'; + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError'; + code: 'UND_ERR_NOT_SUPPORTED'; + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError'; + code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError'; + code: string; + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError'; + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } +} diff --git a/node_modules/undici/types/fetch.d.ts b/node_modules/undici/types/fetch.d.ts new file mode 100644 index 0000000..fa4619c --- /dev/null +++ b/node_modules/undici/types/fetch.d.ts @@ -0,0 +1,209 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' + +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export interface BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = string[][] | Record> | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + method?: string + keepalive?: boolean + headers?: HeadersInit + body?: BodyInit + redirect?: RequestRedirect + integrity?: string + signal?: AbortSignal + credentials?: RequestCredentials + mode?: RequestMode + referrer?: string + referrerPolicy?: ReferrerPolicy + window?: null + dispatcher?: Dispatcher + duplex?: RequestDuplex +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url'; + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request implements BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrerPolicy: string + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response implements BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Response + + static error (): Response + static json(data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/node_modules/undici/types/file.d.ts b/node_modules/undici/types/file.d.ts new file mode 100644 index 0000000..c695b7a --- /dev/null +++ b/node_modules/undici/types/file.d.ts @@ -0,0 +1,39 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT) +/// + +import { Blob } from 'buffer' + +export interface BlobPropertyBag { + type?: string + endings?: 'native' | 'transparent' +} + +export interface FilePropertyBag extends BlobPropertyBag { + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + lastModified?: number +} + +export declare class File extends Blob { + /** + * Creates a new File instance. + * + * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + * @param fileName The name of the file. + * @param options An options object containing optional attributes for the file. + */ + constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag) + + /** + * Name of the file referenced by the File object. + */ + readonly name: string + + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + readonly lastModified: number + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici/types/filereader.d.ts b/node_modules/undici/types/filereader.d.ts new file mode 100644 index 0000000..f05d231 --- /dev/null +++ b/node_modules/undici/types/filereader.d.ts @@ -0,0 +1,54 @@ +/// + +import { Blob } from 'buffer' +import { DOMException, Event, EventInit, EventTarget } from './patch' + +export declare class FileReader { + __proto__: EventTarget & FileReader + + constructor () + + readAsArrayBuffer (blob: Blob): void + readAsBinaryString (blob: Blob): void + readAsText (blob: Blob, encoding?: string): void + readAsDataURL (blob: Blob): void + + abort (): void + + static readonly EMPTY = 0 + static readonly LOADING = 1 + static readonly DONE = 2 + + readonly EMPTY = 0 + readonly LOADING = 1 + readonly DONE = 2 + + readonly readyState: number + + readonly result: string | ArrayBuffer | null + + readonly error: DOMException | null + + onloadstart: null | ((this: FileReader, event: ProgressEvent) => void) + onprogress: null | ((this: FileReader, event: ProgressEvent) => void) + onload: null | ((this: FileReader, event: ProgressEvent) => void) + onabort: null | ((this: FileReader, event: ProgressEvent) => void) + onerror: null | ((this: FileReader, event: ProgressEvent) => void) + onloadend: null | ((this: FileReader, event: ProgressEvent) => void) +} + +export interface ProgressEventInit extends EventInit { + lengthComputable?: boolean + loaded?: number + total?: number +} + +export declare class ProgressEvent { + __proto__: Event & ProgressEvent + + constructor (type: string, eventInitDict?: ProgressEventInit) + + readonly lengthComputable: boolean + readonly loaded: number + readonly total: number +} diff --git a/node_modules/undici/types/formdata.d.ts b/node_modules/undici/types/formdata.d.ts new file mode 100644 index 0000000..df29a57 --- /dev/null +++ b/node_modules/undici/types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from './file' +import { SpecIterator, SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append(name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set(name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get(name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll(name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has(name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete(name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici/types/global-dispatcher.d.ts b/node_modules/undici/types/global-dispatcher.d.ts new file mode 100644 index 0000000..728f95c --- /dev/null +++ b/node_modules/undici/types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export { + getGlobalDispatcher, + setGlobalDispatcher +} + +declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; +declare function getGlobalDispatcher(): Dispatcher; diff --git a/node_modules/undici/types/global-origin.d.ts b/node_modules/undici/types/global-origin.d.ts new file mode 100644 index 0000000..322542d --- /dev/null +++ b/node_modules/undici/types/global-origin.d.ts @@ -0,0 +1,7 @@ +export { + setGlobalOrigin, + getGlobalOrigin +} + +declare function setGlobalOrigin(origin: string | URL | undefined): void; +declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/node_modules/undici/types/handlers.d.ts b/node_modules/undici/types/handlers.d.ts new file mode 100644 index 0000000..eb4f5a9 --- /dev/null +++ b/node_modules/undici/types/handlers.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export declare class RedirectHandler implements Dispatcher.DispatchHandlers{ + constructor (dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandlers{ + constructor (handler: Dispatcher.DispatchHandlers) +} diff --git a/node_modules/undici/types/header.d.ts b/node_modules/undici/types/header.d.ts new file mode 100644 index 0000000..bfdb329 --- /dev/null +++ b/node_modules/undici/types/header.d.ts @@ -0,0 +1,4 @@ +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record; diff --git a/node_modules/undici/types/index.d.ts b/node_modules/undici/types/index.d.ts new file mode 100644 index 0000000..4589845 --- /dev/null +++ b/node_modules/undici/types/index.d.ts @@ -0,0 +1,63 @@ +import Dispatcher from'./dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from'./pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from'./client' +import buildConnector from'./connector' +import errors from'./errors' +import Agent from'./agent' +import MockClient from'./mock-client' +import MockPool from'./mock-pool' +import MockAgent from'./mock-agent' +import mockErrors from'./mock-errors' +import ProxyAgent from'./proxy-agent' +import { request, pipeline, stream, connect, upgrade } from './api' + +export * from './cookies' +export * from './fetch' +export * from './file' +export * from './filereader' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, RedirectHandler, DecoratorHandler } +export default Undici + +declare namespace Undici { + var Dispatcher: typeof import('./dispatcher').default + var Pool: typeof import('./pool').default; + var RedirectHandler: typeof import ('./handlers').RedirectHandler + var DecoratorHandler: typeof import ('./handlers').DecoratorHandler + var createRedirectInterceptor: typeof import ('./interceptors').createRedirectInterceptor + var BalancedPool: typeof import('./balanced-pool').default; + var Client: typeof import('./client').default; + var buildConnector: typeof import('./connector').default; + var errors: typeof import('./errors').default; + var Agent: typeof import('./agent').default; + var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher; + var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher; + var request: typeof import('./api').request; + var stream: typeof import('./api').stream; + var pipeline: typeof import('./api').pipeline; + var connect: typeof import('./api').connect; + var upgrade: typeof import('./api').upgrade; + var MockClient: typeof import('./mock-client').default; + var MockPool: typeof import('./mock-pool').default; + var MockAgent: typeof import('./mock-agent').default; + var mockErrors: typeof import('./mock-errors').default; + var fetch: typeof import('./fetch').fetch; + var Headers: typeof import('./fetch').Headers; + var Response: typeof import('./fetch').Response; + var Request: typeof import('./fetch').Request; + var FormData: typeof import('./formdata').FormData; + var File: typeof import('./file').File; + var FileReader: typeof import('./filereader').FileReader; + var caches: typeof import('./cache').caches; +} diff --git a/node_modules/undici/types/interceptors.d.ts b/node_modules/undici/types/interceptors.d.ts new file mode 100644 index 0000000..047ac17 --- /dev/null +++ b/node_modules/undici/types/interceptors.d.ts @@ -0,0 +1,5 @@ +import Dispatcher from "./dispatcher"; + +type RedirectInterceptorOpts = { maxRedirections?: number } + +export declare function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatchInterceptor diff --git a/node_modules/undici/types/mock-agent.d.ts b/node_modules/undici/types/mock-agent.d.ts new file mode 100644 index 0000000..98cd645 --- /dev/null +++ b/node_modules/undici/types/mock-agent.d.ts @@ -0,0 +1,50 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch; + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor(options?: MockAgent.Options) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable; + get(origin: RegExp): TInterceptable; + get(origin: ((origin: string) => boolean)): TInterceptable; + /** Dispatches a mocked request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close(): Promise; + /** Disables mocking in MockAgent. */ + deactivate(): void; + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate(): void; + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect(): void; + enableNetConnect(host: string): void; + enableNetConnect(host: RegExp): void; + enableNetConnect(host: ((host: string) => boolean)): void; + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect(): void; + pendingInterceptors(): PendingInterceptor[]; + assertNoPendingInterceptors(options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void; +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Agent; + } +} diff --git a/node_modules/undici/types/mock-client.d.ts b/node_modules/undici/types/mock-client.d.ts new file mode 100644 index 0000000..51d008c --- /dev/null +++ b/node_modules/undici/types/mock-client.d.ts @@ -0,0 +1,25 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor(origin: string, options: MockClient.Options); + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici/types/mock-errors.d.ts b/node_modules/undici/types/mock-errors.d.ts new file mode 100644 index 0000000..3d9e727 --- /dev/null +++ b/node_modules/undici/types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor(message?: string); + name: 'MockNotMatchedError'; + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } +} diff --git a/node_modules/undici/types/mock-interceptor.d.ts b/node_modules/undici/types/mock-interceptor.d.ts new file mode 100644 index 0000000..6b3961c --- /dev/null +++ b/node_modules/undici/types/mock-interceptor.d.ts @@ -0,0 +1,93 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher'; +import { BodyInit, Headers } from './fetch' + +export { + Interceptable, + MockInterceptor, + MockScope +} + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor(mockDispatch: MockInterceptor.MockDispatch); + /** Delay a reply by a set amount of time in ms. */ + delay(waitInMs: number): MockScope; + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist(): MockScope; + /** Define a reply for a set amount of matching requests. */ + times(repeatTimes: number): MockScope; +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope; + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope; + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers(trailers: Record): MockInterceptor; + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength(): MockInterceptor; +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + origin: string; + method: string; + body?: BodyInit | Dispatcher.DispatchOptions['body']; + headers: Headers | Record; + maxRedirections: number; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string; + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; +} diff --git a/node_modules/undici/types/mock-pool.d.ts b/node_modules/undici/types/mock-pool.d.ts new file mode 100644 index 0000000..39e709a --- /dev/null +++ b/node_modules/undici/types/mock-pool.d.ts @@ -0,0 +1,25 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor(origin: string, options: MockPool.Options); + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici/types/patch.d.ts b/node_modules/undici/types/patch.d.ts new file mode 100644 index 0000000..3871acf --- /dev/null +++ b/node_modules/undici/types/patch.d.ts @@ -0,0 +1,71 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export type DOMException = typeof globalThis extends { DOMException: infer T } + ? T + : any + +export type EventTarget = typeof globalThis extends { EventTarget: infer T } + ? T + : { + addEventListener( + type: string, + listener: any, + options?: any, + ): void + dispatchEvent(event: Event): boolean + removeEventListener( + type: string, + listener: any, + options?: any | boolean, + ): void + } + +export type Event = typeof globalThis extends { Event: infer T } + ? T + : { + readonly bubbles: boolean + cancelBubble: () => void + readonly cancelable: boolean + readonly composed: boolean + composedPath(): [EventTarget?] + readonly currentTarget: EventTarget | null + readonly defaultPrevented: boolean + readonly eventPhase: 0 | 2 + readonly isTrusted: boolean + preventDefault(): void + returnValue: boolean + readonly srcElement: EventTarget | null + stopImmediatePropagation(): void + stopPropagation(): void + readonly target: EventTarget | null + readonly timeStamp: number + readonly type: string + } + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/node_modules/undici/types/pool-stats.d.ts b/node_modules/undici/types/pool-stats.d.ts new file mode 100644 index 0000000..8b6d2bf --- /dev/null +++ b/node_modules/undici/types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from "./pool" + +export default PoolStats + +declare class PoolStats { + constructor(pool: Pool); + /** Number of open socket connections in this pool. */ + connected: number; + /** Number of open socket connections in this pool that do not have an active request. */ + free: number; + /** Number of pending requests across all clients in this pool. */ + pending: number; + /** Number of queued requests across all clients in this pool. */ + queued: number; + /** Number of currently active requests across all clients in this pool. */ + running: number; + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number; +} diff --git a/node_modules/undici/types/pool.d.ts b/node_modules/undici/types/pool.d.ts new file mode 100644 index 0000000..7747d48 --- /dev/null +++ b/node_modules/undici/types/pool.d.ts @@ -0,0 +1,28 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from "./dispatcher"; + +export default Pool + +declare class Pool extends Dispatcher { + constructor(url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats; +} + +declare namespace Pool { + export type PoolStats = TPoolStats; + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + } +} diff --git a/node_modules/undici/types/proxy-agent.d.ts b/node_modules/undici/types/proxy-agent.d.ts new file mode 100644 index 0000000..96b2638 --- /dev/null +++ b/node_modules/undici/types/proxy-agent.d.ts @@ -0,0 +1,30 @@ +import Agent from './agent' +import buildConnector from './connector'; +import Client from './client' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' +import Pool from './pool' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor(options: ProxyAgent.Options | string) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + } +} diff --git a/node_modules/undici/types/readable.d.ts b/node_modules/undici/types/readable.d.ts new file mode 100644 index 0000000..4549a8c --- /dev/null +++ b/node_modules/undici/types/readable.d.ts @@ -0,0 +1,61 @@ +import { Readable } from "stream"; +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor( + resume?: (this: Readable, size: number) => void | null, + abort?: () => void | null, + contentType?: string + ) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text(): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json(): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob(): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer(): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData(): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** Throws on node 16.6.0 + * + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 262144 + */ + dump(opts?: { limit: number }): Promise +} diff --git a/node_modules/undici/types/webidl.d.ts b/node_modules/undici/types/webidl.d.ts new file mode 100644 index 0000000..40cfe06 --- /dev/null +++ b/node_modules/undici/types/webidl.d.ts @@ -0,0 +1,220 @@ +// These types are not exported, and are only used internally + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + exception (opts: { header: string, message: string }): TypeError + /** + * @description Throw an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + IntegerPart (N: number): number +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + [Key: string]: (...args: any[]) => unknown +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (cls: Interface): ( + V: unknown, + opts?: { strict: boolean } + ) => asserts V is typeof cls + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: { + header: string + message?: string + }): void +} diff --git a/node_modules/undici/types/websocket.d.ts b/node_modules/undici/types/websocket.d.ts new file mode 100644 index 0000000..15a357d --- /dev/null +++ b/node_modules/undici/types/websocket.d.ts @@ -0,0 +1,131 @@ +/// + +import type { Blob } from 'buffer' +import type { MessagePort } from 'worker_threads' +import { + EventTarget, + Event, + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: Event + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} diff --git a/node_modules/web-streams-polyfill/LICENSE b/node_modules/web-streams-polyfill/LICENSE new file mode 100644 index 0000000..9fe85ac --- /dev/null +++ b/node_modules/web-streams-polyfill/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2024 Mattias Buelens +Copyright (c) 2016 Diwank Singh Tomer + +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/web-streams-polyfill/README.md b/node_modules/web-streams-polyfill/README.md new file mode 100644 index 0000000..8aa88cf --- /dev/null +++ b/node_modules/web-streams-polyfill/README.md @@ -0,0 +1,111 @@ +# web-streams-polyfill + +Web Streams, based on the WHATWG spec reference implementation. + +[![build status](https://api.travis-ci.com/MattiasBuelens/web-streams-polyfill.svg?branch=master)](https://travis-ci.com/MattiasBuelens/web-streams-polyfill) +[![npm version](https://img.shields.io/npm/v/web-streams-polyfill.svg)](https://www.npmjs.com/package/web-streams-polyfill) +[![license](https://img.shields.io/npm/l/web-streams-polyfill.svg)](https://github.com/MattiasBuelens/web-streams-polyfill/blob/master/LICENSE) +[![Join the chat at https://gitter.im/web-streams-polyfill/Lobby](https://badges.gitter.im/web-streams-polyfill/Lobby.svg)](https://gitter.im/web-streams-polyfill/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +## Links + + - [Official spec][spec] + - [Reference implementation][ref-impl] + +## Usage + +This library comes in multiple variants: +* `web-streams-polyfill`: a polyfill that replaces the native stream implementations. + Recommended for use in web apps supporting older browsers through a ` + + + +``` +Usage as a Node module: +```js +var streams = require("web-streams-polyfill/ponyfill"); +var readable = new streams.ReadableStream(); +``` +Usage as a ES2015 module: +```js +import { ReadableStream } from "web-streams-polyfill/ponyfill"; +const readable = new ReadableStream(); +``` + +## Compatibility + +The `polyfill` and `ponyfill` variants work in any ES5-compatible environment that has a global `Promise`. +If you need to support older browsers or Node versions that do not have a native `Promise` implementation +(check the [support table][promise-support]), you must first include a `Promise` polyfill +(e.g. [promise-polyfill][promise-polyfill]). + +The `polyfill/es6` and `ponyfill/es6` variants work in any ES2015-compatible environment. + +The `polyfill/es2018` and `ponyfill/es2018` variants work in any ES2018-compatible environment. + +[Async iterable support for `ReadableStream`][rs-asynciterator] is available in all variants, but requires an ES2018-compatible environment or a polyfill for `Symbol.asyncIterator`. + +[`WritableStreamDefaultController.signal`][ws-controller-signal] is available in all variants, but requires a global `AbortController` constructor. If necessary, consider using a polyfill such as [abortcontroller-polyfill]. + +[Reading with a BYOB reader][mdn-byob-read] is available in all variants, but requires `ArrayBuffer.prototype.transfer()` or `structuredClone()` to exist in order to correctly transfer the given view's buffer. If not available, then the buffer won't be transferred during the read. + +## Compliance + +The polyfill implements [version `4dc123a` (13 Nov 2023)][spec-snapshot] of the streams specification. + +The polyfill is tested against the same [web platform tests][wpt] that are used by browsers to test their native implementations. +The polyfill aims to pass all tests, although it allows some exceptions for practical reasons: +* The `es2018` variant passes all of the tests. +* The `es6` variant passes the same tests as the `es2018` variant, except for the [test for the prototype of `ReadableStream`'s async iterator][wpt-async-iterator-prototype]. + Retrieving the correct `%AsyncIteratorPrototype%` requires using an async generator (`async function* () {}`), which is invalid syntax before ES2018. + Instead, the polyfill [creates its own version][stub-async-iterator-prototype] which is functionally equivalent to the real prototype. +* The `es5` variant passes the same tests as the `es6` variant, except for various tests about specific characteristics of the constructors, properties and methods. + These test failures do not affect the run-time behavior of the polyfill. + For example: + * The `name` property of down-leveled constructors is incorrect. + * The `length` property of down-leveled constructors and methods with optional arguments is incorrect. + * Not all properties and methods are correctly marked as non-enumerable. + * Down-leveled class methods are not correctly marked as non-constructable. + +The type definitions are compatible with the built-in stream types of TypeScript 3.3. + +## Contributors + +Thanks to these people for their work on [the original polyfill][creatorrr-polyfill]: + + - Diwank Singh Tomer ([creatorrr](https://github.com/creatorrr)) + - Anders Riutta ([ariutta](https://github.com/ariutta)) + +[spec]: https://streams.spec.whatwg.org +[ref-impl]: https://github.com/whatwg/streams +[ponyfill]: https://github.com/sindresorhus/ponyfill +[promise-support]: https://kangax.github.io/compat-table/es6/#test-Promise +[promise-polyfill]: https://www.npmjs.com/package/promise-polyfill +[rs-asynciterator]: https://streams.spec.whatwg.org/#rs-asynciterator +[ws-controller-signal]: https://streams.spec.whatwg.org/#ws-default-controller-signal +[abortcontroller-polyfill]: https://www.npmjs.com/package/abortcontroller-polyfill +[mdn-byob-read]: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamBYOBReader/read +[spec-snapshot]: https://streams.spec.whatwg.org/commit-snapshots/4dc123a6e7f7ba89a8c6a7975b021156f39cab52/ +[wpt]: https://github.com/web-platform-tests/wpt/tree/2a298b616b7c865917d7198a287310881cbfdd8d/streams +[wpt-async-iterator-prototype]: https://github.com/web-platform-tests/wpt/blob/2a298b616b7c865917d7198a287310881cbfdd8d/streams/readable-streams/async-iterator.any.js#L24 +[stub-async-iterator-prototype]: https://github.com/MattiasBuelens/web-streams-polyfill/blob/v2.0.0/src/target/es5/stub/async-iterator-prototype.ts +[creatorrr-polyfill]: https://github.com/creatorrr/web-streams-polyfill diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.js b/node_modules/web-streams-polyfill/dist/polyfill.es2018.js new file mode 100644 index 0000000..6395183 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.js @@ -0,0 +1,4767 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + const exports$1 = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (const prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.es2018.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map b/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map new file mode 100644 index 0000000..e5b6b25 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException","exports"],"mappings":";;;;;;;;;;;;;IAAA;IAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,IAAA,MAAM;IACN,IAAA,WAAW,IAAI,CAAU,OAAA,EAAA,WAAW,GAAoB;;aCL5C,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KA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ClC,IAAA,KAAK,MAAM,IAAI,IAAIA,SAAO,EAAE;IAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;IACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;IACnC,gBAAA,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;IAC9C,gBAAA,QAAQ,EAAE,IAAI;IACd,gBAAA,YAAY,EAAE,IAAI;IACnB,aAAA,CAAC,CAAC;aACJ;SACF;IACH;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js b/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js new file mode 100644 index 0000000..80158eb --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}function o(e){return"object"==typeof e&&null!==e||"function"==typeof e}const n=r;function a(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const i=Promise,l=Promise.prototype.then,s=Promise.reject.bind(i);function u(e){return new i(e)}function c(e){return u((t=>t(e)))}function d(e){return s(e)}function f(e,t,r){return l.call(e,t,r)}function b(e,t,r){f(f(e,t,r),void 0,n)}function h(e,t){b(e,t)}function m(e,t){b(e,void 0,t)}function _(e,t,r){return f(e,t,r)}function p(e){f(e,void 0,n)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=c(void 0);y=t=>f(e,t)}return y(e)};function S(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function g(e,t,r){try{return c(S(e,t,r))}catch(e){return d(e)}}class v{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const w=t("[[AbortSteps]]"),R=t("[[ErrorSteps]]"),T=t("[[CancelSteps]]"),C=t("[[PullSteps]]"),P=t("[[ReleaseSteps]]");function q(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?O(e):"closed"===t._state?function(e){O(e),A(e)}(e):j(e,t._storedError)}function E(e,t){return Cr(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?k(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){j(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[P](),t._reader=void 0,e._ownerReadableStream=void 0}function B(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function O(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function j(e,t){O(e),k(e,t)}function k(e,t){void 0!==e._closedPromise_reject&&(p(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function A(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const D=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},z=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function L(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function F(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function I(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Y(e){return Number(e)}function Q(e){return 0===e?0:e}function x(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=Q(o),!D(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return Q(z(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return D(o)&&0!==o?o:0}function N(e,t){if(!Rr(e))throw new TypeError(`${t} is not a ReadableStream.`)}function H(e){return new ReadableStreamDefaultReader(e)}function V(e,t){e._reader._readRequests.push(t)}function U(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function G(e){return e._reader._readRequests.length}function X(e){const t=e._reader;return void 0!==t&&!!J(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),N(e,"First parameter"),Tr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");q(this,e),this._readRequests=new v}get closed(){return J(this)?this._closedPromise:d(ee("closed"))}cancel(e=void 0){return J(this)?void 0===this._ownerReadableStream?d(B("cancel")):E(this,e):d(ee("cancel"))}read(){if(!J(this))return d(ee("read"));if(void 0===this._ownerReadableStream)return d(B("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return K(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!J(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function J(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function K(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[C](t)}function Z(e,t){const r=e._readRequests;e._readRequests=new v,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(ReadableStreamDefaultReader.prototype.cancel,"cancel"),a(ReadableStreamDefaultReader.prototype.read,"read"),a(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0});const te=Object.getPrototypeOf(Object.getPrototypeOf((async function*(){})).prototype);class re{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?_(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?_(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;let t,r;const o=u(((e,o)=>{t=e,r=o}));return K(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,y((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,W(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,W(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(!this._preventCancel){const r=E(t,e);return W(t),_(r,(()=>({value:e,done:!0})))}return W(t),c({value:e,done:!0})}}const oe={next(){return ne(this)?this._asyncIteratorImpl.next():d(ae("next"))},return(e){return ne(this)?this._asyncIteratorImpl.return(e):d(ae("return"))}};function ne(e){if(!o(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof re}catch(e){return!1}}function ae(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==te&&Object.setPrototypeOf(oe,te);const ie=Number.isNaN||function(e){return e!=e};function le(e){return e.slice()}function se(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}let ue=e=>(ue="function"==typeof e.transfer?e=>e.transfer():"function"==typeof structuredClone?e=>structuredClone(e,{transfer:[e]}):e=>e,ue(e)),ce=e=>(ce="boolean"==typeof e.detached?e=>e.detached:e=>0===e.byteLength,ce(e));function de(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return se(n,0,e,t,o),n}function fe(e,t){const r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(`${String(t)} is not a function`);return r}}function be(e,r="sync",n){if(void 0===n)if("async"===r){if(void 0===(n=fe(e,t.asyncIterator))){return function(e){const r={[t.iterator]:()=>e.iterator},o=async function*(){return yield*r}();return{iterator:o,nextMethod:o.next,done:!1}}(be(e,"sync",fe(e,t.iterator)))}}else n=fe(e,t.iterator);if(void 0===n)throw new TypeError("The object is not iterable");const a=S(n,e,[]);if(!o(a))throw new TypeError("The iterator method must return an object");return{iterator:a,nextMethod:a.next,done:!1}}function he(e){const t=de(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function me(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function _e(e,t,r){if("number"!=typeof(o=r)||ie(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function pe(e){e._queue=new v,e._queueTotalSize=0}function ye(e){return e===DataView}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!ge(this))throw He("view");return this._view}respond(e){if(!ge(this))throw He("respond");if($(e,1,"respond"),e=x(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(ce(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Qe(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!ge(this))throw He("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(ce(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");xe(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),a(ReadableStreamBYOBRequest.prototype.respond,"respond"),a(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Se(this))throw Ve("byobRequest");return Me(this)}get desiredSize(){if(!Se(this))throw Ve("desiredSize");return Ye(this)}close(){if(!Se(this))throw Ve("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Le(this)}enqueue(e){if(!Se(this))throw Ve("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);Fe(this,e)}error(e=void 0){if(!Se(this))throw Ve("error");Ie(this,e)}[T](e){we(this),pe(this);const t=this._cancelAlgorithm(e);return ze(this),t}[C](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void $e(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}V(t,e),ve(this)}[P](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new v,this._pendingPullIntos.push(e)}}}function Se(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function ge(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function ve(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(X(t)&&G(t)>0)return!0;if(Ke(t)&&Je(t)>0)return!0;const r=Ye(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,ve(e)),null)),(t=>(Ie(e,t),null)))}function we(e){Oe(e),e._pendingPullIntos=new v}function Re(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=Te(t);"default"===t.readerType?U(e,o,r):function(e,t,r){const o=e._reader,n=o._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,o,r)}function Te(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Ce(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function Pe(e,t,r,o){let n;try{n=de(t,r,r+o)}catch(t){throw Ie(e,t),t}Ce(e,n,0,o)}function qe(e,t){t.bytesFilled>0&&Pe(e,t.buffer,t.byteOffset,t.bytesFilled),De(e)}function Ee(e,t){const r=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),o=t.bytesFilled+r;let n=r,a=!1;const i=o-o%t.elementSize;i>=t.minimumFill&&(n=i-t.bytesFilled,a=!0);const l=e._queue;for(;n>0;){const r=l.peek(),o=Math.min(n,r.byteLength),a=t.byteOffset+t.bytesFilled;se(t.buffer,a,r.buffer,r.byteOffset,o),r.byteLength===o?l.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,We(e,o,t),n-=o}return a}function We(e,t,r){r.bytesFilled+=t}function Be(e){0===e._queueTotalSize&&e._closeRequested?(ze(e),Pr(e._controlledReadableByteStream)):ve(e)}function Oe(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function je(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();Ee(e,t)&&(De(e),Re(e._controlledReadableByteStream,t))}}function ke(e,t,r,o){const n=e._controlledReadableByteStream,a=t.constructor,i=function(e){return ye(e)?1:e.BYTES_PER_ELEMENT}(a),{byteOffset:l,byteLength:s}=t,u=r*i;let c;try{c=ue(t.buffer)}catch(e){return void o._errorSteps(e)}const d={buffer:c,bufferByteLength:c.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:u,elementSize:i,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(d),void Xe(n,o);if("closed"!==n._state){if(e._queueTotalSize>0){if(Ee(e,d)){const t=Te(d);return Be(e),void o._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Ie(e,t),void o._errorSteps(t)}}e._pendingPullIntos.push(d),Xe(n,o),ve(e)}else{const e=new a(d.buffer,d.byteOffset,0);o._closeSteps(e)}}function Ae(e,t){const r=e._pendingPullIntos.peek();Oe(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&De(e);const r=e._controlledReadableByteStream;if(Ke(r))for(;Je(r)>0;)Re(r,De(e))}(e,r):function(e,t,r){if(We(0,t,r),"none"===r.readerType)return qe(e,r),void je(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;Pe(e,r.buffer,t-o,o)}r.bytesFilled-=o,Re(e._controlledReadableByteStream,r),je(e)}(e,t,r),ve(e)}function De(e){return e._pendingPullIntos.shift()}function ze(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Le(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Ie(e,t),t}}ze(e),Pr(t)}}function Fe(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const{buffer:o,byteOffset:n,byteLength:a}=t;if(ce(o))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");const i=ue(o);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(ce(t.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");Oe(e),t.buffer=ue(t.buffer),"none"===t.readerType&&qe(e,t)}if(X(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;$e(e,t._readRequests.shift())}}(e),0===G(r))Ce(e,i,n,a);else{e._pendingPullIntos.length>0&&De(e);U(r,new Uint8Array(i,n,a),!1)}else Ke(r)?(Ce(e,i,n,a),je(e)):Ce(e,i,n,a);ve(e)}function Ie(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(we(e),pe(e),ze(e),qr(r,t))}function $e(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,Be(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function Me(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function Ye(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Qe(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=ue(r.buffer),Ae(e,t)}function xe(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=ue(t.buffer),Ae(e,o)}function Ne(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,pe(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new v,e._readableStreamController=t;b(c(r()),(()=>(t._started=!0,ve(t),null)),(e=>(Ie(t,e),null)))}function He(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ve(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Ue(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function Ge(e){return new ReadableStreamBYOBReader(e)}function Xe(e,t){e._reader._readIntoRequests.push(t)}function Je(e){return e._reader._readIntoRequests.length}function Ke(e){const t=e._reader;return void 0!==t&&!!Ze(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),a(ReadableByteStreamController.prototype.close,"close"),a(ReadableByteStreamController.prototype.enqueue,"enqueue"),a(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),N(e,"First parameter"),Tr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Se(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");q(this,e),this._readIntoRequests=new v}get closed(){return Ze(this)?this._closedPromise:d(rt("closed"))}cancel(e=void 0){return Ze(this)?void 0===this._ownerReadableStream?d(B("cancel")):E(this,e):d(rt("cancel"))}read(e,t={}){if(!Ze(this))return d(rt("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(ce(e.buffer))return d(new TypeError("view's buffer has been detached"));let r;try{r=function(e,t){var r;return L(e,t),{min:x(null!==(r=null==e?void 0:e.min)&&void 0!==r?r:1,`${t} has member 'min' that`)}}(t,"options")}catch(e){return d(e)}const o=r.min;if(0===o)return d(new TypeError("options.min must be greater than 0"));if(function(e){return ye(e.constructor)}(e)){if(o>e.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(o>e.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return d(B("read from"));let n,a;const i=u(((e,t)=>{n=e,a=t}));return et(this,e,o,{_chunkSteps:e=>n({value:e,done:!1}),_closeSteps:e=>n({value:e,done:!0}),_errorSteps:e=>a(e)}),i}releaseLock(){if(!Ze(this))throw rt("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");tt(e,t)}(this)}}function Ze(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function et(e,t,r,o){const n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?o._errorSteps(n._storedError):ke(n._readableStreamController,t,r,o)}function tt(e,t){const r=e._readIntoRequests;e._readIntoRequests=new v,r.forEach((e=>{e._errorSteps(t)}))}function rt(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function ot(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ie(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function nt(e){const{size:t}=e;return t||(()=>1)}function at(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Y(r),size:void 0===o?void 0:it(o,`${t} has member 'size' that`)}}function it(e,t){return F(e,t),t=>Y(e(t))}function lt(e,t,r){return F(e,r),r=>g(e,t,[r])}function st(e,t,r){return F(e,r),()=>g(e,t,[])}function ut(e,t,r){return F(e,r),r=>S(e,t,[r])}function ct(e,t,r){return F(e,r),(r,o)=>g(e,t,[r,o])}function dt(e,t){if(!mt(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(ReadableStreamBYOBReader.prototype.cancel,"cancel"),a(ReadableStreamBYOBReader.prototype.read,"read"),a(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const ft="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:I(e,"First parameter");const r=at(t,"Second parameter"),o=function(e,t){L(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:lt(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:st(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:ut(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:ct(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");ht(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=nt(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>c(void 0);l=void 0!==t.close?()=>t.close():()=>c(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>c(void 0);kt(e,n,a,i,l,s,r,o)}(this,o,ot(r,1),n)}get locked(){if(!mt(this))throw $t("locked");return _t(this)}abort(e=void 0){return mt(this)?_t(this)?d(new TypeError("Cannot abort a stream that already has a writer")):pt(this,e):d($t("abort"))}close(){return mt(this)?_t(this)?d(new TypeError("Cannot close a stream that already has a writer")):wt(this)?d(new TypeError("Cannot close an already-closing stream")):yt(this):d($t("close"))}getWriter(){if(!mt(this))throw $t("getWriter");return bt(this)}}function bt(e){return new WritableStreamDefaultWriter(e)}function ht(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new v,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function mt(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function _t(e){return void 0!==e._writer}function pt(e,t){var r;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=u(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||gt(e,t),a}function yt(e){const t=e._state;if("closed"===t||"errored"===t)return d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&Kt(o),_e(n=e._writableStreamController,Ot,0),zt(n),r}function St(e,t){"writable"!==e._state?vt(e):gt(e,t)}function gt(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&Et(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&vt(e)}function vt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new v,void 0===e._pendingAbortRequest)return void Rt(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Rt(e);b(e._writableStreamController[w](r._reason),(()=>(r._resolve(),Rt(e),null)),(t=>(r._reject(t),Rt(e),null)))}function wt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Rt(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&Ht(t,e._storedError)}function Tt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Ut(e)}(r):Kt(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),a(WritableStream.prototype.abort,"abort"),a(WritableStream.prototype.close,"close"),a(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStream.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),dt(e,"First parameter"),_t(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!wt(e)&&e._backpressure?Ut(this):Xt(this),xt(this);else if("erroring"===t)Gt(this,e._storedError),xt(this);else if("closed"===t)Xt(this),xt(r=this),Vt(r);else{const t=e._storedError;Gt(this,t),Nt(this,t)}var r}get closed(){return Ct(this)?this._closedPromise:d(Yt("closed"))}get desiredSize(){if(!Ct(this))throw Yt("desiredSize");if(void 0===this._ownerWritableStream)throw Qt("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return Dt(t._writableStreamController)}(this)}get ready(){return Ct(this)?this._readyPromise:d(Yt("ready"))}abort(e=void 0){return Ct(this)?void 0===this._ownerWritableStream?d(Qt("abort")):function(e,t){return pt(e._ownerWritableStream,t)}(this,e):d(Yt("abort"))}close(){if(!Ct(this))return d(Yt("close"));const e=this._ownerWritableStream;return void 0===e?d(Qt("close")):wt(e)?d(new TypeError("Cannot close an already-closing stream")):Pt(this)}releaseLock(){if(!Ct(this))throw Yt("releaseLock");void 0!==this._ownerWritableStream&&Wt(this)}write(e=void 0){return Ct(this)?void 0===this._ownerWritableStream?d(Qt("write to")):Bt(this,e):d(Yt("write"))}}function Ct(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function Pt(e){return yt(e._ownerWritableStream)}function qt(e,t){"pending"===e._closedPromiseState?Ht(e,t):function(e,t){Nt(e,t)}(e,t)}function Et(e,t){"pending"===e._readyPromiseState?Jt(e,t):function(e,t){Gt(e,t)}(e,t)}function Wt(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");Et(e,r),qt(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function Bt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Lt(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(Qt("write to"));const a=r._state;if("errored"===a)return d(r._storedError);if(wt(r)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(r._storedError);const i=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{_e(e,t,r)}catch(t){return void Lt(e,t)}const o=e._controlledWritableStream;if(!wt(o)&&"writable"===o._state){Tt(o,Ft(e))}zt(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),a(WritableStreamDefaultWriter.prototype.abort,"abort"),a(WritableStreamDefaultWriter.prototype.close,"close"),a(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),a(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const Ot={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!jt(this))throw Mt("abortReason");return this._abortReason}get signal(){if(!jt(this))throw Mt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!jt(this))throw Mt("error");"writable"===this._controlledWritableStream._state&&It(this,e)}[w](e){const t=this._abortAlgorithm(e);return At(this),t}[R](){pe(this)}}function jt(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function kt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,pe(t),t._abortReason=void 0,t._abortController=function(){if(ft)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=Ft(t);Tt(e,s);b(c(r()),(()=>(t._started=!0,zt(t),null)),(r=>(t._started=!0,St(e,r),null)))}function At(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Dt(e){return e._strategyHWM-e._queueTotalSize}function zt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void vt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===Ot?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),me(e);const r=e._closeAlgorithm();At(e),b(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Vt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),St(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const o=e._writeAlgorithm(t);b(o,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(me(e),!wt(r)&&"writable"===t){const t=Ft(e);Tt(r,t)}return zt(e),null}),(t=>("writable"===r._state&&At(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,St(e,t)}(r,t),null)))}(e,r)}function Lt(e,t){"writable"===e._controlledWritableStream._state&&It(e,t)}function Ft(e){return Dt(e)<=0}function It(e,t){const r=e._controlledWritableStream;At(e),gt(r,t)}function $t(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Mt(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Yt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Qt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function xt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function Nt(e,t){xt(e),Ht(e,t)}function Ht(e,t){void 0!==e._closedPromise_reject&&(p(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Vt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Ut(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function Gt(e,t){Ut(e),Jt(e,t)}function Xt(e){Ut(e),Kt(e)}function Jt(e,t){void 0!==e._readyPromise_reject&&(p(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function Kt(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const Zt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;const er=function(){const e=null==Zt?void 0:Zt.DOMException;return function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(e)?e:void 0}()||function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return a(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function tr(e,t,o,n,a,i){const l=H(e),s=bt(t);e._disturbed=!0;let _=!1,y=c(void 0);return u(((S,g)=>{let v;if(void 0!==i){if(v=()=>{const r=void 0!==i.reason?i.reason:new er("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===t._state?pt(t,r):c(void 0))),a||o.push((()=>"readable"===e._state?Cr(e,r):c(void 0))),q((()=>Promise.all(o.map((e=>e())))),!0,r)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(P(e,l._closedPromise,(e=>(n?E(!0,e):q((()=>pt(t,e)),!0,e),null))),P(t,s._closedPromise,(t=>(a?E(!0,t):q((()=>Cr(e,t)),!0,t),null))),w=e,R=l._closedPromise,T=()=>(o?E():q((()=>function(e){const t=e._ownerWritableStream,r=t._state;return wt(t)||"closed"===r?c(void 0):"errored"===r?d(t._storedError):Pt(e)}(s))),null),"closed"===w._state?T():h(R,T),wt(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?E(!0,t):q((()=>Cr(e,t)),!0,t)}function C(){const e=y;return f(y,(()=>e!==y?C():void 0))}function P(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function q(e,r,o){function n(){return b(e(),(()=>B(r,o)),(e=>B(!0,e))),null}_||(_=!0,"writable"!==t._state||wt(t)?n():h(C(),n))}function E(e,r){_||(_=!0,"writable"!==t._state||wt(t)?B(e,r):h(C(),(()=>B(e,r))))}function B(e,t){return Wt(s),W(l),void 0!==i&&i.removeEventListener("abort",v),e?g(t):S(void 0),null}p(u(((e,t)=>{!function o(n){n?e():f(_?c(!0):f(s._readyPromise,(()=>u(((e,t)=>{K(l,{_chunkSteps:t=>{y=f(Bt(s,t),void 0,r),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),o,t)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!rr(this))throw fr("desiredSize");return ur(this)}close(){if(!rr(this))throw fr("close");if(!cr(this))throw new TypeError("The stream is not in a state that permits close");ir(this)}enqueue(e=void 0){if(!rr(this))throw fr("enqueue");if(!cr(this))throw new TypeError("The stream is not in a state that permits enqueue");return lr(this,e)}error(e=void 0){if(!rr(this))throw fr("error");sr(this,e)}[T](e){pe(this);const t=this._cancelAlgorithm(e);return ar(this),t}[C](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=me(this);this._closeRequested&&0===this._queue.length?(ar(this),Pr(t)):or(this),e._chunkSteps(r)}else V(t,e),or(this)}[P](){}}function rr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function or(e){if(!nr(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,or(e)),null)),(t=>(sr(e,t),null)))}function nr(e){const t=e._controlledReadableStream;if(!cr(e))return!1;if(!e._started)return!1;if(Tr(t)&&G(t)>0)return!0;return ur(e)>0}function ar(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function ir(e){if(!cr(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(ar(e),Pr(t))}function lr(e,t){if(!cr(e))return;const r=e._controlledReadableStream;if(Tr(r)&&G(r)>0)U(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw sr(e,t),t}try{_e(e,t,r)}catch(t){throw sr(e,t),t}}or(e)}function sr(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(pe(e),ar(e),qr(r,t))}function ur(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function cr(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function dr(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,pe(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;b(c(r()),(()=>(t._started=!0,or(t),null)),(e=>(sr(t,e),null)))}function fr(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function br(e,t){return Se(e._readableStreamController)?function(e){let t,r,o,n,a,i=H(e),l=!1,s=!1,d=!1,f=!1,b=!1;const h=u((e=>{a=e}));function _(e){m(e._closedPromise,(t=>(e!==i||(Ie(o._readableStreamController,t),Ie(n._readableStreamController,t),f&&b||a(void 0)),null)))}function p(){Ze(i)&&(W(i),i=H(e),_(i));K(i,{_chunkSteps:t=>{y((()=>{s=!1,d=!1;const r=t;let i=t;if(!f&&!b)try{i=he(t)}catch(t){return Ie(o._readableStreamController,t),Ie(n._readableStreamController,t),void a(Cr(e,t))}f||Fe(o._readableStreamController,r),b||Fe(n._readableStreamController,i),l=!1,s?g():d&&v()}))},_closeSteps:()=>{l=!1,f||Le(o._readableStreamController),b||Le(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&Qe(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&Qe(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function S(t,r){J(i)&&(W(i),i=Ge(e),_(i));const u=r?n:o,c=r?o:n;et(i,t,1,{_chunkSteps:t=>{y((()=>{s=!1,d=!1;const o=r?b:f;if(r?f:b)o||xe(u._readableStreamController,t);else{let r;try{r=he(t)}catch(t){return Ie(u._readableStreamController,t),Ie(c._readableStreamController,t),void a(Cr(e,t))}o||xe(u._readableStreamController,t),Fe(c._readableStreamController,r)}l=!1,s?g():d&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||Le(u._readableStreamController),o||Le(c._readableStreamController),void 0!==e&&(t||xe(u._readableStreamController,e),!o&&c._readableStreamController._pendingPullIntos.length>0&&Qe(c._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function g(){if(l)return s=!0,c(void 0);l=!0;const e=Me(o._readableStreamController);return null===e?p():S(e._view,!1),c(void 0)}function v(){if(l)return d=!0,c(void 0);l=!0;const e=Me(n._readableStreamController);return null===e?p():S(e._view,!0),c(void 0)}function w(o){if(f=!0,t=o,b){const o=le([t,r]),n=Cr(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=le([t,r]),n=Cr(e,o);a(n)}return h}function T(){}return o=vr(T,g,w),n=vr(T,v,R),_(i),[o,n]}(e):function(e,t){const r=H(e);let o,n,a,i,l,s=!1,d=!1,f=!1,b=!1;const h=u((e=>{l=e}));function _(){if(s)return d=!0,c(void 0);s=!0;return K(r,{_chunkSteps:e=>{y((()=>{d=!1;const t=e,r=e;f||lr(a._readableStreamController,t),b||lr(i._readableStreamController,r),s=!1,d&&_()}))},_closeSteps:()=>{s=!1,f||ir(a._readableStreamController),b||ir(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{s=!1}}),c(void 0)}function p(t){if(f=!0,o=t,b){const t=le([o,n]),r=Cr(e,t);l(r)}return h}function S(t){if(b=!0,n=t,f){const t=le([o,n]),r=Cr(e,t);l(r)}return h}function g(){}return a=gr(g,_,p),i=gr(g,_,S),m(r._closedPromise,(e=>(sr(a._readableStreamController,e),sr(i._readableStreamController,e),f&&b||l(void 0),null))),[a,i]}(e)}function hr(e){return o(t=e)&&void 0!==t.getReader?function(e){let t;function n(){let r;try{r=e.read()}catch(e){return d(e)}return _(r,(e=>{if(!o(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)ir(t._readableStreamController);else{const r=e.value;lr(t._readableStreamController,r)}}))}function a(t){try{return c(e.cancel(t))}catch(e){return d(e)}}return t=gr(r,n,a,0),t}(e.getReader()):function(e){let t;const n=be(e,"async");function a(){let e;try{e=function(e){const t=S(e.nextMethod,e.iterator,[]);if(!o(t))throw new TypeError("The iterator.next() method must return an object");return t}(n)}catch(e){return d(e)}return _(c(e),(e=>{if(!o(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");const r=function(e){return Boolean(e.done)}(e);if(r)ir(t._readableStreamController);else{const r=function(e){return e.value}(e);lr(t._readableStreamController,r)}}))}function i(e){const t=n.iterator;let r,a;try{r=fe(t,"return")}catch(e){return d(e)}if(void 0===r)return c(void 0);try{a=S(r,t,[e])}catch(e){return d(e)}return _(c(a),(e=>{if(!o(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return t=gr(r,a,i,0),t}(e);var t}function mr(e,t,r){return F(e,r),r=>g(e,t,[r])}function _r(e,t,r){return F(e,r),r=>g(e,t,[r])}function pr(e,t,r){return F(e,r),r=>S(e,t,[r])}function yr(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Sr(e,t){L(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),a(ReadableStreamDefaultController.prototype.close,"close"),a(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),a(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:I(e,"First parameter");const r=at(t,"Second parameter"),o=function(e,t){L(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:x(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:mr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:_r(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:pr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:yr(l,`${t} has member 'type' that`)}}(e,"First parameter");if(wr(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>c(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");Ne(e,o,n,a,i,r,l)}(this,o,ot(r,0))}else{const e=nt(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>c(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0),dr(e,n,a,i,l,r,o)}(this,o,ot(r,1),e)}}get locked(){if(!Rr(this))throw Er("locked");return Tr(this)}cancel(e=void 0){return Rr(this)?Tr(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Cr(this,e):d(Er("cancel"))}getReader(e=void 0){if(!Rr(this))throw Er("getReader");return void 0===function(e,t){L(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Ue(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?H(this):Ge(this)}pipeThrough(e,t={}){if(!Rr(this))throw Er("pipeThrough");$(e,1,"pipeThrough");const r=function(e,t){L(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),N(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),dt(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=Sr(t,"Second parameter");if(Tr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(_t(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return p(tr(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!Rr(this))return d(Er("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!mt(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Sr(t,"Second parameter")}catch(e){return d(e)}return Tr(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):_t(e)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):tr(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Rr(this))throw Er("tee");return le(br(this))}values(e=void 0){if(!Rr(this))throw Er("values");return function(e,t){const r=H(e),o=new re(r,t),n=Object.create(oe);return n._asyncIteratorImpl=o,n}(this,function(e,t){L(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}static from(e){return hr(e)}}function gr(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);wr(a);return dr(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function vr(e,t,r){const o=Object.create(ReadableStream.prototype);wr(o);return Ne(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function wr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Rr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Tr(e){return void 0!==e._reader}function Cr(e,t){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);Pr(e);const o=e._reader;if(void 0!==o&&Ze(o)){const e=o._readIntoRequests;o._readIntoRequests=new v,e.forEach((e=>{e._closeSteps(void 0)}))}return _(e._readableStreamController[T](t),r)}function Pr(e){e._state="closed";const t=e._reader;if(void 0!==t&&(A(t),J(t))){const e=t._readRequests;t._readRequests=new v,e.forEach((e=>{e._closeSteps()}))}}function qr(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(k(r,t),J(r)?Z(r,t):tt(r,t))}function Er(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Wr(e,t){L(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(r)}}Object.defineProperties(ReadableStream,{from:{enumerable:!0}}),Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),a(ReadableStream.from,"from"),a(ReadableStream.prototype.cancel,"cancel"),a(ReadableStream.prototype.getReader,"getReader"),a(ReadableStream.prototype.pipeThrough,"pipeThrough"),a(ReadableStream.prototype.pipeTo,"pipeTo"),a(ReadableStream.prototype.tee,"tee"),a(ReadableStream.prototype.values,"values"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStream.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(ReadableStream.prototype,t.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const Br=e=>e.byteLength;a(Br,"size");class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=Wr(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!jr(this))throw Or("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!jr(this))throw Or("size");return Br}}function Or(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function jr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const kr=()=>1;a(kr,"size");class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=Wr(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Dr(this))throw Ar("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!Dr(this))throw Ar("size");return kr}}function Ar(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function Dr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function zr(e,t,r){return F(e,r),r=>g(e,t,[r])}function Lr(e,t,r){return F(e,r),r=>S(e,t,[r])}function Fr(e,t,r){return F(e,r),(r,o)=>g(e,t,[r,o])}function Ir(e,t,r){return F(e,r),r=>g(e,t,[r])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=at(t,"Second parameter"),n=at(r,"Third parameter"),a=function(e,t){L(e,t);const r=null==e?void 0:e.cancel,o=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,l=null==e?void 0:e.writableType;return{cancel:void 0===r?void 0:Ir(r,e,`${t} has member 'cancel' that`),flush:void 0===o?void 0:zr(o,e,`${t} has member 'flush' that`),readableType:n,start:void 0===a?void 0:Lr(a,e,`${t} has member 'start' that`),transform:void 0===i?void 0:Fr(i,e,`${t} has member 'transform' that`),writableType:l}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=ot(n,0),l=nt(n),s=ot(o,1),f=nt(o);let h;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return _(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return Ur(r,t)}))}return Ur(r,t)}(e,t)}function s(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._readable;r._finishPromise=u(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return Hr(r),b(n,(()=>("errored"===o._state?Jr(r,o._storedError):(sr(o._readableStreamController,t),Xr(r)),null)),(e=>(sr(o._readableStreamController,e),Jr(r,e),null))),r._finishPromise}(e,t)}function c(){return function(e){const t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;const r=e._readable;t._finishPromise=u(((e,r)=>{t._finishPromise_resolve=e,t._finishPromise_reject=r}));const o=t._flushAlgorithm();return Hr(t),b(o,(()=>("errored"===r._state?Jr(t,r._storedError):(ir(r._readableStreamController),Xr(t)),null)),(e=>(sr(r._readableStreamController,e),Jr(t,e),null))),t._finishPromise}(e)}function d(){return function(e){return xr(e,!1),e._backpressureChangePromise}(e)}function f(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._writable;r._finishPromise=u(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return Hr(r),b(n,(()=>("errored"===o._state?Jr(r,o._storedError):(Lt(o._writableStreamController,t),Qr(e),Xr(r)),null)),(t=>(Lt(o._writableStreamController,t),Qr(e),Jr(r,t),null))),r._finishPromise}(e,t)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return ht(i),kt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,c,s,r,o),e._readable=gr(i,d,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,xr(e,!0),e._transformStreamController=void 0}(this,u((e=>{h=e})),s,f,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n,a;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return Vr(r,e),c(void 0)}catch(e){return d(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>c(void 0);a=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);!function(e,t,r,o,n){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o,t._cancelAlgorithm=n,t._finishPromise=void 0,t._finishPromise_resolve=void 0,t._finishPromise_reject=void 0}(e,r,o,n,a)}(this,a),void 0!==a.start?h(a.start(this._transformStreamController)):h(void 0)}get readable(){if(!$r(this))throw Kr("readable");return this._readable}get writable(){if(!$r(this))throw Kr("writable");return this._writable}}function $r(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function Mr(e,t){sr(e._readable._readableStreamController,t),Yr(e,t)}function Yr(e,t){Hr(e._transformStreamController),Lt(e._writable._writableStreamController,t),Qr(e)}function Qr(e){e._backpressure&&xr(e,!1)}function xr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStream.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Nr(this))throw Gr("desiredSize");return ur(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!Nr(this))throw Gr("enqueue");Vr(this,e)}error(e=void 0){if(!Nr(this))throw Gr("error");var t;t=e,Mr(this._controlledTransformStream,t)}terminate(){if(!Nr(this))throw Gr("terminate");!function(e){const t=e._controlledTransformStream;ir(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Yr(t,r)}(this)}}function Nr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function Hr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function Vr(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!cr(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{lr(o,t)}catch(e){throw Yr(r,e),r._readable._storedError}const n=function(e){return!nr(e)}(o);n!==r._backpressure&&xr(r,!0)}function Ur(e,t){return _(e._transformAlgorithm(t),void 0,(t=>{throw Mr(e._controlledTransformStream,t),t}))}function Gr(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function Xr(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function Jr(e,t){void 0!==e._finishPromise_reject&&(p(e._finishPromise),e._finishPromise_reject(t),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function Kr(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),a(TransformStreamDefaultController.prototype.enqueue,"enqueue"),a(TransformStreamDefaultController.prototype.error,"error"),a(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const Zr={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==Zt)for(const e in Zr)Object.prototype.hasOwnProperty.call(Zr,e)&&Object.defineProperty(Zt,e,{value:Zr[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter})); +//# sourceMappingURL=polyfill.es2018.min.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map b/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map new file mode 100644 index 0000000..e066402 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.min.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["SymbolPolyfill","Symbol","iterator","description","noop","typeIsObject","x","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","value","configurable","_a","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseReject","reject","bind","newPromise","executor","promiseResolvedWith","resolve","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise","cb","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","constructor","this","_cursor","_size","_front","_elements","_next","_back","length","push","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","shift","oldFront","newFront","oldCursor","newCursor","elements","forEach","i","node","peek","front","cursor","AbortSteps","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","defineProperties","enumerable","toStringTag","AsyncIteratorPrototype","getPrototypeOf","async","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","next","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","n","Uint8Array","set","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","GetIterator","hint","method","asyncIterator","syncIteratorRecord","syncIterable","nextMethod","CreateAsyncFromSyncIterator","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","r","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","abortReason","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","getFromGlobal","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","flushAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"mappings":";;;;;;;0PAEA,MAAMA,EACc,mBAAXC,QAAoD,iBAApBA,OAAOC,SAC5CD,OACAE,GAAe,UAAUA,cCLbC,IAEhB,CCCM,SAAUC,EAAaC,GAC3B,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,CACzD,CAEO,MAAMC,EAUPH,EAEU,SAAAI,EAAgBC,EAAcC,GA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,KAE7B9J,EAAgBqqB,iCAAiC1pB,UAAUqP,QAAS,WACpEhQ,EAAgBqqB,iCAAiC1pB,UAAUuP,MAAO,SAClElQ,EAAgBqqB,iCAAiC1pB,UAAUuqB,UAAW,aACpC,iBAAvBzrB,EAAOsK,aAChB5J,OAAOC,eAAeiqB,iCAAiC1pB,UAAWlB,EAAOsK,YAAa,CACpF1J,MAAO,mCACPC,cAAc,IClVlB,MAAMgrB,GAAU,CACd/F,8BACAtE,gEACA7R,0DACAZ,oDACAvG,wDACAuN,kDAEA2B,8BACAW,gEACAc,wDAEAoO,oDACAK,0CAEAQ,gCACAwC,mEAIF,QAAuB,IAAZ9L,GACT,IAAK,MAAMzR,KAAQwe,GACbnrB,OAAOQ,UAAU+I,eAAehI,KAAK4pB,GAASxe,IAChD3M,OAAOC,eAAeme,GAASzR,EAAM,CACnCzM,MAAOirB,GAAQxe,GACfmS,UAAU,EACV3e,cAAc"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs b/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs new file mode 100644 index 0000000..ad90a61 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs @@ -0,0 +1,4747 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +const PullSteps = SymbolPolyfill('[[PullSteps]]'); +const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +/* eslint-disable @typescript-eslint/no-empty-function */ +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +const exports = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (const prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.es2018.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map b/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map new file mode 100644 index 0000000..cfd3203 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es2018.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es2018.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","default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3B,yBAAyB;IACzB,oBAAoB;IAEpB,eAAe;IACf,gCAAgC;CACjC,CAAC;AAEF;AACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;AAClC,IAAA,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;AAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;AACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;AACnC,gBAAA,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;AAC9C,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,YAAY,EAAE,IAAI;AACnB,aAAA,CAAC,CAAC;SACJ;KACF;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.js b/node_modules/web-streams-polyfill/dist/polyfill.es6.js new file mode 100644 index 0000000..9a32b0d --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.js @@ -0,0 +1,4844 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + let AsyncIteratorPrototype; + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolPolyfill.asyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); + } + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + 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; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + const exports$1 = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (const prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.es6.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map b/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map new file mode 100644 index 0000000..62cd27c --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException","exports"],"mappings":";;;;;;;;;;;;;IAAA;IAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,IAAA,MAAM;IACN,IAAA,WAAW,IAAI,CAAU,OAAA,EAAA,WAAW,GAAoB;;aCL5C,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;IAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;IACxD,IAAA,IAAI;IACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;IAChC,YAAA,KAAK,EAAE,IAAI;IACX,YAAA,YAAY,EAAE,IAAI;IACnB,SAAA,CAAC,CAAC;SACJ;IAAC,IAAA,OAAA,EAAA,EAAM;;;SAGP;IACH;;IC1BA,MAAM,eAAe,GAAG,OAAO,CAAC;IAChC,MAAM,mBAAmB,GAAG,OAAO,CAAC,SAAS,CAAC,IAAI,CAAC;IACnD,M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;QAC/B,4BAA4B;QAC5B,yBAAyB;QACzB,2BAA2B;QAC3B,wBAAwB;QAExB,cAAc;QACd,+BAA+B;QAC/B,2BAA2B;QAE3B,yBAAyB;QACzB,oBAAoB;QAEpB,eAAe;QACf,gCAAgC;KACjC,CAAC;IAEF;IACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;IAClC,IAAA,KAAK,MAAM,IAAI,IAAIA,SAAO,EAAE;IAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;IACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;IACnC,gBAAA,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;IAC9C,gBAAA,QAAQ,EAAE,IAAI;IACd,gBAAA,YAAY,EAAE,IAAI;IACnB,aAAA,CAAC,CAAC;aACJ;SACF;IACH;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[15]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js b/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js new file mode 100644 index 0000000..df6fa3a --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";const t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:e=>`Symbol(${e})`;function r(){}function o(e){return"object"==typeof e&&null!==e||"function"==typeof e}const n=r;function a(e,t){try{Object.defineProperty(e,"name",{value:t,configurable:!0})}catch(e){}}const i=Promise,l=Promise.prototype.then,s=Promise.reject.bind(i);function u(e){return new i(e)}function c(e){return u((t=>t(e)))}function d(e){return s(e)}function f(e,t,r){return l.call(e,t,r)}function b(e,t,r){f(f(e,t,r),void 0,n)}function h(e,t){b(e,t)}function m(e,t){b(e,void 0,t)}function _(e,t,r){return f(e,t,r)}function p(e){f(e,void 0,n)}let y=e=>{if("function"==typeof queueMicrotask)y=queueMicrotask;else{const e=c(void 0);y=t=>f(e,t)}return y(e)};function S(e,t,r){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,t,r)}function g(e,t,r){try{return c(S(e,t,r))}catch(e){return d(e)}}class v{constructor(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}get length(){return this._size}push(e){const t=this._back;let r=t;16383===t._elements.length&&(r={_elements:[],_next:void 0}),t._elements.push(e),r!==t&&(this._back=r,t._next=r),++this._size}shift(){const e=this._front;let t=e;const r=this._cursor;let o=r+1;const n=e._elements,a=n[r];return 16384===o&&(t=e._next,o=0),--this._size,this._cursor=o,e!==t&&(this._front=t),n[r]=void 0,a}forEach(e){let t=this._cursor,r=this._front,o=r._elements;for(;!(t===o.length&&void 0===r._next||t===o.length&&(r=r._next,o=r._elements,t=0,0===o.length));)e(o[t]),++t}peek(){const e=this._front,t=this._cursor;return e._elements[t]}}const w=t("[[AbortSteps]]"),R=t("[[ErrorSteps]]"),T=t("[[CancelSteps]]"),C=t("[[PullSteps]]"),P=t("[[ReleaseSteps]]");function q(e,t){e._ownerReadableStream=t,t._reader=e,"readable"===t._state?O(e):"closed"===t._state?function(e){O(e),A(e)}(e):j(e,t._storedError)}function E(e,t){return Br(e._ownerReadableStream,t)}function W(e){const t=e._ownerReadableStream;"readable"===t._state?k(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,t){j(e,t)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),t._readableStreamController[P](),t._reader=void 0,e._ownerReadableStream=void 0}function B(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function O(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r}))}function j(e,t){O(e),k(e,t)}function k(e,t){void 0!==e._closedPromise_reject&&(p(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function A(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}const D=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},z=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function I(e,t){if(void 0!==e&&("object"!=typeof(r=e)&&"function"!=typeof r))throw new TypeError(`${t} is not an object.`);var r}function L(e,t){if("function"!=typeof e)throw new TypeError(`${t} is not a function.`)}function F(e,t){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError(`${t} is not an object.`)}function $(e,t,r){if(void 0===e)throw new TypeError(`Parameter ${t} is required in '${r}'.`)}function M(e,t,r){if(void 0===e)throw new TypeError(`${t} is required in '${r}'.`)}function Y(e){return Number(e)}function x(e){return 0===e?0:e}function Q(e,t){const r=Number.MAX_SAFE_INTEGER;let o=Number(e);if(o=x(o),!D(o))throw new TypeError(`${t} is not a finite number`);if(o=function(e){return x(z(e))}(o),o<0||o>r)throw new TypeError(`${t} is outside the accepted range of 0 to ${r}, inclusive`);return D(o)&&0!==o?o:0}function N(e,t){if(!Er(e))throw new TypeError(`${t} is not a ReadableStream.`)}function H(e){return new ReadableStreamDefaultReader(e)}function V(e,t){e._reader._readRequests.push(t)}function U(e,t,r){const o=e._reader._readRequests.shift();r?o._closeSteps():o._chunkSteps(t)}function G(e){return e._reader._readRequests.length}function X(e){const t=e._reader;return void 0!==t&&!!J(t)}class ReadableStreamDefaultReader{constructor(e){if($(e,1,"ReadableStreamDefaultReader"),N(e,"First parameter"),Wr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");q(this,e),this._readRequests=new v}get closed(){return J(this)?this._closedPromise:d(ee("closed"))}cancel(e=void 0){return J(this)?void 0===this._ownerReadableStream?d(B("cancel")):E(this,e):d(ee("cancel"))}read(){if(!J(this))return d(ee("read"));if(void 0===this._ownerReadableStream)return d(B("read from"));let e,t;const r=u(((r,o)=>{e=r,t=o}));return K(this,{_chunkSteps:t=>e({value:t,done:!1}),_closeSteps:()=>e({value:void 0,done:!0}),_errorSteps:e=>t(e)}),r}releaseLock(){if(!J(this))throw ee("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");Z(e,t)}(this)}}function J(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ReadableStreamDefaultReader)}function K(e,t){const r=e._ownerReadableStream;r._disturbed=!0,"closed"===r._state?t._closeSteps():"errored"===r._state?t._errorSteps(r._storedError):r._readableStreamController[C](t)}function Z(e,t){const r=e._readRequests;e._readRequests=new v,r.forEach((e=>{e._errorSteps(t)}))}function ee(e){return new TypeError(`ReadableStreamDefaultReader.prototype.${e} can only be used on a ReadableStreamDefaultReader`)}let te;Object.defineProperties(ReadableStreamDefaultReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(ReadableStreamDefaultReader.prototype.cancel,"cancel"),a(ReadableStreamDefaultReader.prototype.read,"read"),a(ReadableStreamDefaultReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultReader.prototype,t.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof t.asyncIterator&&(te={[t.asyncIterator](){return this}},Object.defineProperty(te,t.asyncIterator,{enumerable:!1}));class re{constructor(e,t){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=t}next(){const e=()=>this._nextSteps();return this._ongoingPromise=this._ongoingPromise?_(this._ongoingPromise,e,e):e(),this._ongoingPromise}return(e){const t=()=>this._returnSteps(e);return this._ongoingPromise?_(this._ongoingPromise,t,t):t()}_nextSteps(){if(this._isFinished)return Promise.resolve({value:void 0,done:!0});const e=this._reader;let t,r;const o=u(((e,o)=>{t=e,r=o}));return K(e,{_chunkSteps:e=>{this._ongoingPromise=void 0,y((()=>t({value:e,done:!1})))},_closeSteps:()=>{this._ongoingPromise=void 0,this._isFinished=!0,W(e),t({value:void 0,done:!0})},_errorSteps:t=>{this._ongoingPromise=void 0,this._isFinished=!0,W(e),r(t)}}),o}_returnSteps(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;const t=this._reader;if(!this._preventCancel){const r=E(t,e);return W(t),_(r,(()=>({value:e,done:!0})))}return W(t),c({value:e,done:!0})}}const oe={next(){return ne(this)?this._asyncIteratorImpl.next():d(ae("next"))},return(e){return ne(this)?this._asyncIteratorImpl.return(e):d(ae("return"))}};function ne(e){if(!o(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof re}catch(e){return!1}}function ae(e){return new TypeError(`ReadableStreamAsyncIterator.${e} can only be used on a ReadableSteamAsyncIterator`)}void 0!==te&&Object.setPrototypeOf(oe,te);const ie=Number.isNaN||function(e){return e!=e};function le(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],o=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&o>=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function se(e){return this instanceof se?(this.v=e,this):new se(e)}function ue(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var o,n=r.apply(e,t||[]),a=[];return o={},i("next"),i("throw"),i("return"),o[Symbol.asyncIterator]=function(){return this},o;function i(e){n[e]&&(o[e]=function(t){return new Promise((function(r,o){a.push([e,t,r,o])>1||l(e,t)}))})}function l(e,t){try{(r=n[e](t)).value instanceof se?Promise.resolve(r.value.v).then(s,u):c(a[0][2],r)}catch(e){c(a[0][3],e)}var r}function s(e){l("next",e)}function u(e){l("throw",e)}function c(e,t){e(t),a.shift(),a.length&&l(a[0][0],a[0][1])}}function ce(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=le(e),t={},o("next"),o("throw"),o("return"),t[Symbol.asyncIterator]=function(){return this},t);function o(r){t[r]=e[r]&&function(t){return new Promise((function(o,n){(function(e,t,r,o){Promise.resolve(o).then((function(t){e({value:t,done:r})}),t)})(o,n,(t=e[r](t)).done,t.value)}))}}}function de(e){return e.slice()}function fe(e,t,r,o,n){new Uint8Array(e).set(new Uint8Array(r,o,n),t)}"function"==typeof SuppressedError&&SuppressedError;let be=e=>(be="function"==typeof e.transfer?e=>e.transfer():"function"==typeof structuredClone?e=>structuredClone(e,{transfer:[e]}):e=>e,be(e)),he=e=>(he="boolean"==typeof e.detached?e=>e.detached:e=>0===e.byteLength,he(e));function me(e,t,r){if(e.slice)return e.slice(t,r);const o=r-t,n=new ArrayBuffer(o);return fe(n,0,e,t,o),n}function _e(e,t){const r=e[t];if(null!=r){if("function"!=typeof r)throw new TypeError(`${String(t)} is not a function`);return r}}function pe(e){const r={[t.iterator]:()=>e.iterator},o=function(){return ue(this,arguments,(function*(){return yield se(yield se(yield*function(e){var t,r;return t={},o("next"),o("throw",(function(e){throw e})),o("return"),t[Symbol.iterator]=function(){return this},t;function o(o,n){t[o]=e[o]?function(t){return(r=!r)?{value:se(e[o](t)),done:!1}:n?n(t):t}:n}}(ce(r))))}))}();return{iterator:o,nextMethod:o.next,done:!1}}function ye(e,r="sync",n){if(void 0===n)if("async"===r){if(void 0===(n=_e(e,t.asyncIterator))){return pe(ye(e,"sync",_e(e,t.iterator)))}}else n=_e(e,t.iterator);if(void 0===n)throw new TypeError("The object is not iterable");const a=S(n,e,[]);if(!o(a))throw new TypeError("The iterator method must return an object");return{iterator:a,nextMethod:a.next,done:!1}}function Se(e){const t=me(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(t)}function ge(e){const t=e._queue.shift();return e._queueTotalSize-=t.size,e._queueTotalSize<0&&(e._queueTotalSize=0),t.value}function ve(e,t,r){if("number"!=typeof(o=r)||ie(o)||o<0||r===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var o;e._queue.push({value:t,size:r}),e._queueTotalSize+=r}function we(e){e._queue=new v,e._queueTotalSize=0}function Re(e){return e===DataView}class ReadableStreamBYOBRequest{constructor(){throw new TypeError("Illegal constructor")}get view(){if(!Ce(this))throw Je("view");return this._view}respond(e){if(!Ce(this))throw Je("respond");if($(e,1,"respond"),e=Q(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(he(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");Ue(this._associatedReadableByteStreamController,e)}respondWithNewView(e){if(!Ce(this))throw Je("respondWithNewView");if($(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(he(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");Ge(this._associatedReadableByteStreamController,e)}}Object.defineProperties(ReadableStreamBYOBRequest.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),a(ReadableStreamBYOBRequest.prototype.respond,"respond"),a(ReadableStreamBYOBRequest.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBRequest.prototype,t.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});class ReadableByteStreamController{constructor(){throw new TypeError("Illegal constructor")}get byobRequest(){if(!Te(this))throw Ke("byobRequest");return He(this)}get desiredSize(){if(!Te(this))throw Ke("desiredSize");return Ve(this)}close(){if(!Te(this))throw Ke("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");const e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError(`The stream (in ${e} state) is not in the readable state and cannot be closed`);Ye(this)}enqueue(e){if(!Te(this))throw Ke("enqueue");if($(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");const t=this._controlledReadableByteStream._state;if("readable"!==t)throw new TypeError(`The stream (in ${t} state) is not in the readable state and cannot be enqueued to`);xe(this,e)}error(e=void 0){if(!Te(this))throw Ke("error");Qe(this,e)}[T](e){qe(this),we(this);const t=this._cancelAlgorithm(e);return Me(this),t}[C](e){const t=this._controlledReadableByteStream;if(this._queueTotalSize>0)return void Ne(this,e);const r=this._autoAllocateChunkSize;if(void 0!==r){let t;try{t=new ArrayBuffer(r)}catch(t){return void e._errorSteps(t)}const o={buffer:t,bufferByteLength:r,byteOffset:0,byteLength:r,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}V(t,e),Pe(this)}[P](){if(this._pendingPullIntos.length>0){const e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new v,this._pendingPullIntos.push(e)}}}function Te(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof ReadableByteStreamController)}function Ce(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof ReadableStreamBYOBRequest)}function Pe(e){const t=function(e){const t=e._controlledReadableByteStream;if("readable"!==t._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(X(t)&&G(t)>0)return!0;if(ot(t)&&rt(t)>0)return!0;const r=Ve(e);if(r>0)return!0;return!1}(e);if(!t)return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,Pe(e)),null)),(t=>(Qe(e,t),null)))}function qe(e){ze(e),e._pendingPullIntos=new v}function Ee(e,t){let r=!1;"closed"===e._state&&(r=!0);const o=We(t);"default"===t.readerType?U(e,o,r):function(e,t,r){const o=e._reader,n=o._readIntoRequests.shift();r?n._closeSteps(t):n._chunkSteps(t)}(e,o,r)}function We(e){const t=e.bytesFilled,r=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,t/r)}function Be(e,t,r,o){e._queue.push({buffer:t,byteOffset:r,byteLength:o}),e._queueTotalSize+=o}function Oe(e,t,r,o){let n;try{n=me(t,r,r+o)}catch(t){throw Qe(e,t),t}Be(e,n,0,o)}function je(e,t){t.bytesFilled>0&&Oe(e,t.buffer,t.byteOffset,t.bytesFilled),$e(e)}function ke(e,t){const r=Math.min(e._queueTotalSize,t.byteLength-t.bytesFilled),o=t.bytesFilled+r;let n=r,a=!1;const i=o-o%t.elementSize;i>=t.minimumFill&&(n=i-t.bytesFilled,a=!0);const l=e._queue;for(;n>0;){const r=l.peek(),o=Math.min(n,r.byteLength),a=t.byteOffset+t.bytesFilled;fe(t.buffer,a,r.buffer,r.byteOffset,o),r.byteLength===o?l.shift():(r.byteOffset+=o,r.byteLength-=o),e._queueTotalSize-=o,Ae(e,o,t),n-=o}return a}function Ae(e,t,r){r.bytesFilled+=t}function De(e){0===e._queueTotalSize&&e._closeRequested?(Me(e),Or(e._controlledReadableByteStream)):Pe(e)}function ze(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Ie(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;const t=e._pendingPullIntos.peek();ke(e,t)&&($e(e),Ee(e._controlledReadableByteStream,t))}}function Le(e,t,r,o){const n=e._controlledReadableByteStream,a=t.constructor,i=function(e){return Re(e)?1:e.BYTES_PER_ELEMENT}(a),{byteOffset:l,byteLength:s}=t,u=r*i;let c;try{c=be(t.buffer)}catch(e){return void o._errorSteps(e)}const d={buffer:c,bufferByteLength:c.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:u,elementSize:i,viewConstructor:a,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(d),void tt(n,o);if("closed"!==n._state){if(e._queueTotalSize>0){if(ke(e,d)){const t=We(d);return De(e),void o._chunkSteps(t)}if(e._closeRequested){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");return Qe(e,t),void o._errorSteps(t)}}e._pendingPullIntos.push(d),tt(n,o),Pe(e)}else{const e=new a(d.buffer,d.byteOffset,0);o._closeSteps(e)}}function Fe(e,t){const r=e._pendingPullIntos.peek();ze(e);"closed"===e._controlledReadableByteStream._state?function(e,t){"none"===t.readerType&&$e(e);const r=e._controlledReadableByteStream;if(ot(r))for(;rt(r)>0;)Ee(r,$e(e))}(e,r):function(e,t,r){if(Ae(0,t,r),"none"===r.readerType)return je(e,r),void Ie(e);if(r.bytesFilled0){const t=r.byteOffset+r.bytesFilled;Oe(e,r.buffer,t-o,o)}r.bytesFilled-=o,Ee(e._controlledReadableByteStream,r),Ie(e)}(e,t,r),Pe(e)}function $e(e){return e._pendingPullIntos.shift()}function Me(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ye(e){const t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){const t=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Qe(e,t),t}}Me(e),Or(t)}}function xe(e,t){const r=e._controlledReadableByteStream;if(e._closeRequested||"readable"!==r._state)return;const{buffer:o,byteOffset:n,byteLength:a}=t;if(he(o))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");const i=be(o);if(e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek();if(he(t.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");ze(e),t.buffer=be(t.buffer),"none"===t.readerType&&je(e,t)}if(X(r))if(function(e){const t=e._controlledReadableByteStream._reader;for(;t._readRequests.length>0;){if(0===e._queueTotalSize)return;Ne(e,t._readRequests.shift())}}(e),0===G(r))Be(e,i,n,a);else{e._pendingPullIntos.length>0&&$e(e);U(r,new Uint8Array(i,n,a),!1)}else ot(r)?(Be(e,i,n,a),Ie(e)):Be(e,i,n,a);Pe(e)}function Qe(e,t){const r=e._controlledReadableByteStream;"readable"===r._state&&(qe(e),we(e),Me(e),jr(r,t))}function Ne(e,t){const r=e._queue.shift();e._queueTotalSize-=r.byteLength,De(e);const o=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);t._chunkSteps(o)}function He(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){const t=e._pendingPullIntos.peek(),r=new Uint8Array(t.buffer,t.byteOffset+t.bytesFilled,t.byteLength-t.bytesFilled),o=Object.create(ReadableStreamBYOBRequest.prototype);!function(e,t,r){e._associatedReadableByteStreamController=t,e._view=r}(o,e,r),e._byobRequest=o}return e._byobRequest}function Ve(e){const t=e._controlledReadableByteStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function Ue(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===t)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(r.bytesFilled+t>r.byteLength)throw new RangeError("bytesWritten out of range")}r.buffer=be(r.buffer),Fe(e,t)}function Ge(e,t){const r=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==t.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===t.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(r.byteOffset+r.bytesFilled!==t.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(r.bufferByteLength!==t.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(r.bytesFilled+t.byteLength>r.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");const o=t.byteLength;r.buffer=be(t.buffer),Fe(e,o)}function Xe(e,t,r,o,n,a,i){t._controlledReadableByteStream=e,t._pullAgain=!1,t._pulling=!1,t._byobRequest=null,t._queue=t._queueTotalSize=void 0,we(t),t._closeRequested=!1,t._started=!1,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,t._autoAllocateChunkSize=i,t._pendingPullIntos=new v,e._readableStreamController=t;b(c(r()),(()=>(t._started=!0,Pe(t),null)),(e=>(Qe(t,e),null)))}function Je(e){return new TypeError(`ReadableStreamBYOBRequest.prototype.${e} can only be used on a ReadableStreamBYOBRequest`)}function Ke(e){return new TypeError(`ReadableByteStreamController.prototype.${e} can only be used on a ReadableByteStreamController`)}function Ze(e,t){if("byob"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamReaderMode`);return e}function et(e){return new ReadableStreamBYOBReader(e)}function tt(e,t){e._reader._readIntoRequests.push(t)}function rt(e){return e._reader._readIntoRequests.length}function ot(e){const t=e._reader;return void 0!==t&&!!nt(t)}Object.defineProperties(ReadableByteStreamController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),a(ReadableByteStreamController.prototype.close,"close"),a(ReadableByteStreamController.prototype.enqueue,"enqueue"),a(ReadableByteStreamController.prototype.error,"error"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableByteStreamController.prototype,t.toStringTag,{value:"ReadableByteStreamController",configurable:!0});class ReadableStreamBYOBReader{constructor(e){if($(e,1,"ReadableStreamBYOBReader"),N(e,"First parameter"),Wr(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Te(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");q(this,e),this._readIntoRequests=new v}get closed(){return nt(this)?this._closedPromise:d(lt("closed"))}cancel(e=void 0){return nt(this)?void 0===this._ownerReadableStream?d(B("cancel")):E(this,e):d(lt("cancel"))}read(e,t={}){if(!nt(this))return d(lt("read"));if(!ArrayBuffer.isView(e))return d(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return d(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return d(new TypeError("view's buffer must have non-zero byteLength"));if(he(e.buffer))return d(new TypeError("view's buffer has been detached"));let r;try{r=function(e,t){var r;return I(e,t),{min:Q(null!==(r=null==e?void 0:e.min)&&void 0!==r?r:1,`${t} has member 'min' that`)}}(t,"options")}catch(e){return d(e)}const o=r.min;if(0===o)return d(new TypeError("options.min must be greater than 0"));if(function(e){return Re(e.constructor)}(e)){if(o>e.byteLength)return d(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(o>e.length)return d(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return d(B("read from"));let n,a;const i=u(((e,t)=>{n=e,a=t}));return at(this,e,o,{_chunkSteps:e=>n({value:e,done:!1}),_closeSteps:e=>n({value:e,done:!0}),_errorSteps:e=>a(e)}),i}releaseLock(){if(!nt(this))throw lt("releaseLock");void 0!==this._ownerReadableStream&&function(e){W(e);const t=new TypeError("Reader was released");it(e,t)}(this)}}function nt(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof ReadableStreamBYOBReader)}function at(e,t,r,o){const n=e._ownerReadableStream;n._disturbed=!0,"errored"===n._state?o._errorSteps(n._storedError):Le(n._readableStreamController,t,r,o)}function it(e,t){const r=e._readIntoRequests;e._readIntoRequests=new v,r.forEach((e=>{e._errorSteps(t)}))}function lt(e){return new TypeError(`ReadableStreamBYOBReader.prototype.${e} can only be used on a ReadableStreamBYOBReader`)}function st(e,t){const{highWaterMark:r}=e;if(void 0===r)return t;if(ie(r)||r<0)throw new RangeError("Invalid highWaterMark");return r}function ut(e){const{size:t}=e;return t||(()=>1)}function ct(e,t){I(e,t);const r=null==e?void 0:e.highWaterMark,o=null==e?void 0:e.size;return{highWaterMark:void 0===r?void 0:Y(r),size:void 0===o?void 0:dt(o,`${t} has member 'size' that`)}}function dt(e,t){return L(e,t),t=>Y(e(t))}function ft(e,t,r){return L(e,r),r=>g(e,t,[r])}function bt(e,t,r){return L(e,r),()=>g(e,t,[])}function ht(e,t,r){return L(e,r),r=>S(e,t,[r])}function mt(e,t,r){return L(e,r),(r,o)=>g(e,t,[r,o])}function _t(e,t){if(!gt(e))throw new TypeError(`${t} is not a WritableStream.`)}Object.defineProperties(ReadableStreamBYOBReader.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),a(ReadableStreamBYOBReader.prototype.cancel,"cancel"),a(ReadableStreamBYOBReader.prototype.read,"read"),a(ReadableStreamBYOBReader.prototype.releaseLock,"releaseLock"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamBYOBReader.prototype,t.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});const pt="function"==typeof AbortController;class WritableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=ct(t,"Second parameter"),o=function(e,t){I(e,t);const r=null==e?void 0:e.abort,o=null==e?void 0:e.close,n=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===r?void 0:ft(r,e,`${t} has member 'abort' that`),close:void 0===o?void 0:bt(o,e,`${t} has member 'close' that`),start:void 0===n?void 0:ht(n,e,`${t} has member 'start' that`),write:void 0===i?void 0:mt(i,e,`${t} has member 'write' that`),type:a}}(e,"First parameter");St(this);if(void 0!==o.type)throw new RangeError("Invalid type is specified");const n=ut(r);!function(e,t,r,o){const n=Object.create(WritableStreamDefaultController.prototype);let a,i,l,s;a=void 0!==t.start?()=>t.start(n):()=>{};i=void 0!==t.write?e=>t.write(e,n):()=>c(void 0);l=void 0!==t.close?()=>t.close():()=>c(void 0);s=void 0!==t.abort?e=>t.abort(e):()=>c(void 0);Lt(e,n,a,i,l,s,r,o)}(this,o,st(r,1),n)}get locked(){if(!gt(this))throw Nt("locked");return vt(this)}abort(e=void 0){return gt(this)?vt(this)?d(new TypeError("Cannot abort a stream that already has a writer")):wt(this,e):d(Nt("abort"))}close(){return gt(this)?vt(this)?d(new TypeError("Cannot close a stream that already has a writer")):qt(this)?d(new TypeError("Cannot close an already-closing stream")):Rt(this):d(Nt("close"))}getWriter(){if(!gt(this))throw Nt("getWriter");return yt(this)}}function yt(e){return new WritableStreamDefaultWriter(e)}function St(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new v,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function gt(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof WritableStream)}function vt(e){return void 0!==e._writer}function wt(e,t){var r;if("closed"===e._state||"errored"===e._state)return c(void 0);e._writableStreamController._abortReason=t,null===(r=e._writableStreamController._abortController)||void 0===r||r.abort(t);const o=e._state;if("closed"===o||"errored"===o)return c(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;let n=!1;"erroring"===o&&(n=!0,t=void 0);const a=u(((r,o)=>{e._pendingAbortRequest={_promise:void 0,_resolve:r,_reject:o,_reason:t,_wasAlreadyErroring:n}}));return e._pendingAbortRequest._promise=a,n||Ct(e,t),a}function Rt(e){const t=e._state;if("closed"===t||"errored"===t)return d(new TypeError(`The stream (in ${t} state) is not in the writable state and cannot be closed`));const r=u(((t,r)=>{const o={_resolve:t,_reject:r};e._closeRequest=o})),o=e._writer;var n;return void 0!==o&&e._backpressure&&"writable"===t&&or(o),ve(n=e._writableStreamController,zt,0),Mt(n),r}function Tt(e,t){"writable"!==e._state?Pt(e):Ct(e,t)}function Ct(e,t){const r=e._writableStreamController;e._state="erroring",e._storedError=t;const o=e._writer;void 0!==o&&kt(o,t),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&r._started&&Pt(e)}function Pt(e){e._state="errored",e._writableStreamController[R]();const t=e._storedError;if(e._writeRequests.forEach((e=>{e._reject(t)})),e._writeRequests=new v,void 0===e._pendingAbortRequest)return void Et(e);const r=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,r._wasAlreadyErroring)return r._reject(t),void Et(e);b(e._writableStreamController[w](r._reason),(()=>(r._resolve(),Et(e),null)),(t=>(r._reject(t),Et(e),null)))}function qt(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function Et(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);const t=e._writer;void 0!==t&&Jt(t,e._storedError)}function Wt(e,t){const r=e._writer;void 0!==r&&t!==e._backpressure&&(t?function(e){Zt(e)}(r):or(r)),e._backpressure=t}Object.defineProperties(WritableStream.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),a(WritableStream.prototype.abort,"abort"),a(WritableStream.prototype.close,"close"),a(WritableStream.prototype.getWriter,"getWriter"),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStream.prototype,t.toStringTag,{value:"WritableStream",configurable:!0});class WritableStreamDefaultWriter{constructor(e){if($(e,1,"WritableStreamDefaultWriter"),_t(e,"First parameter"),vt(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;const t=e._state;if("writable"===t)!qt(e)&&e._backpressure?Zt(this):tr(this),Gt(this);else if("erroring"===t)er(this,e._storedError),Gt(this);else if("closed"===t)tr(this),Gt(r=this),Kt(r);else{const t=e._storedError;er(this,t),Xt(this,t)}var r}get closed(){return Bt(this)?this._closedPromise:d(Vt("closed"))}get desiredSize(){if(!Bt(this))throw Vt("desiredSize");if(void 0===this._ownerWritableStream)throw Ut("desiredSize");return function(e){const t=e._ownerWritableStream,r=t._state;if("errored"===r||"erroring"===r)return null;if("closed"===r)return 0;return $t(t._writableStreamController)}(this)}get ready(){return Bt(this)?this._readyPromise:d(Vt("ready"))}abort(e=void 0){return Bt(this)?void 0===this._ownerWritableStream?d(Ut("abort")):function(e,t){return wt(e._ownerWritableStream,t)}(this,e):d(Vt("abort"))}close(){if(!Bt(this))return d(Vt("close"));const e=this._ownerWritableStream;return void 0===e?d(Ut("close")):qt(e)?d(new TypeError("Cannot close an already-closing stream")):Ot(this)}releaseLock(){if(!Bt(this))throw Vt("releaseLock");void 0!==this._ownerWritableStream&&At(this)}write(e=void 0){return Bt(this)?void 0===this._ownerWritableStream?d(Ut("write to")):Dt(this,e):d(Vt("write"))}}function Bt(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof WritableStreamDefaultWriter)}function Ot(e){return Rt(e._ownerWritableStream)}function jt(e,t){"pending"===e._closedPromiseState?Jt(e,t):function(e,t){Xt(e,t)}(e,t)}function kt(e,t){"pending"===e._readyPromiseState?rr(e,t):function(e,t){er(e,t)}(e,t)}function At(e){const t=e._ownerWritableStream,r=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");kt(e,r),jt(e,r),t._writer=void 0,e._ownerWritableStream=void 0}function Dt(e,t){const r=e._ownerWritableStream,o=r._writableStreamController,n=function(e,t){try{return e._strategySizeAlgorithm(t)}catch(t){return Yt(e,t),1}}(o,t);if(r!==e._ownerWritableStream)return d(Ut("write to"));const a=r._state;if("errored"===a)return d(r._storedError);if(qt(r)||"closed"===a)return d(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return d(r._storedError);const i=function(e){return u(((t,r)=>{const o={_resolve:t,_reject:r};e._writeRequests.push(o)}))}(r);return function(e,t,r){try{ve(e,t,r)}catch(t){return void Yt(e,t)}const o=e._controlledWritableStream;if(!qt(o)&&"writable"===o._state){Wt(o,xt(e))}Mt(e)}(o,t,n),i}Object.defineProperties(WritableStreamDefaultWriter.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),a(WritableStreamDefaultWriter.prototype.abort,"abort"),a(WritableStreamDefaultWriter.prototype.close,"close"),a(WritableStreamDefaultWriter.prototype.releaseLock,"releaseLock"),a(WritableStreamDefaultWriter.prototype.write,"write"),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultWriter.prototype,t.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});const zt={};class WritableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get abortReason(){if(!It(this))throw Ht("abortReason");return this._abortReason}get signal(){if(!It(this))throw Ht("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal}error(e=void 0){if(!It(this))throw Ht("error");"writable"===this._controlledWritableStream._state&&Qt(this,e)}[w](e){const t=this._abortAlgorithm(e);return Ft(this),t}[R](){we(this)}}function It(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof WritableStreamDefaultController)}function Lt(e,t,r,o,n,a,i,l){t._controlledWritableStream=e,e._writableStreamController=t,t._queue=void 0,t._queueTotalSize=void 0,we(t),t._abortReason=void 0,t._abortController=function(){if(pt)return new AbortController}(),t._started=!1,t._strategySizeAlgorithm=l,t._strategyHWM=i,t._writeAlgorithm=o,t._closeAlgorithm=n,t._abortAlgorithm=a;const s=xt(t);Wt(e,s);b(c(r()),(()=>(t._started=!0,Mt(t),null)),(r=>(t._started=!0,Tt(e,r),null)))}function Ft(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function $t(e){return e._strategyHWM-e._queueTotalSize}function Mt(e){const t=e._controlledWritableStream;if(!e._started)return;if(void 0!==t._inFlightWriteRequest)return;if("erroring"===t._state)return void Pt(t);if(0===e._queue.length)return;const r=e._queue.peek().value;r===zt?function(e){const t=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(t),ge(e);const r=e._closeAlgorithm();Ft(e),b(r,(()=>(function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";const t=e._writer;void 0!==t&&Kt(t)}(t),null)),(e=>(function(e,t){e._inFlightCloseRequest._reject(t),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(t),e._pendingAbortRequest=void 0),Tt(e,t)}(t,e),null)))}(e):function(e,t){const r=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(r);const o=e._writeAlgorithm(t);b(o,(()=>{!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(r);const t=r._state;if(ge(e),!qt(r)&&"writable"===t){const t=xt(e);Wt(r,t)}return Mt(e),null}),(t=>("writable"===r._state&&Ft(e),function(e,t){e._inFlightWriteRequest._reject(t),e._inFlightWriteRequest=void 0,Tt(e,t)}(r,t),null)))}(e,r)}function Yt(e,t){"writable"===e._controlledWritableStream._state&&Qt(e,t)}function xt(e){return $t(e)<=0}function Qt(e,t){const r=e._controlledWritableStream;Ft(e),Ct(r,t)}function Nt(e){return new TypeError(`WritableStream.prototype.${e} can only be used on a WritableStream`)}function Ht(e){return new TypeError(`WritableStreamDefaultController.prototype.${e} can only be used on a WritableStreamDefaultController`)}function Vt(e){return new TypeError(`WritableStreamDefaultWriter.prototype.${e} can only be used on a WritableStreamDefaultWriter`)}function Ut(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function Gt(e){e._closedPromise=u(((t,r)=>{e._closedPromise_resolve=t,e._closedPromise_reject=r,e._closedPromiseState="pending"}))}function Xt(e,t){Gt(e),Jt(e,t)}function Jt(e,t){void 0!==e._closedPromise_reject&&(p(e._closedPromise),e._closedPromise_reject(t),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function Kt(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function Zt(e){e._readyPromise=u(((t,r)=>{e._readyPromise_resolve=t,e._readyPromise_reject=r})),e._readyPromiseState="pending"}function er(e,t){Zt(e),rr(e,t)}function tr(e){Zt(e),or(e)}function rr(e,t){void 0!==e._readyPromise_reject&&(p(e._readyPromise),e._readyPromise_reject(t),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function or(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(WritableStreamDefaultController.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(WritableStreamDefaultController.prototype,t.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});const nr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;const ar=function(){const e=null==nr?void 0:nr.DOMException;return function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(e)?e:void 0}()||function(){const e=function(e,t){this.message=e||"",this.name=t||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return a(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function ir(e,t,o,n,a,i){const l=H(e),s=yt(t);e._disturbed=!0;let _=!1,y=c(void 0);return u(((S,g)=>{let v;if(void 0!==i){if(v=()=>{const r=void 0!==i.reason?i.reason:new ar("Aborted","AbortError"),o=[];n||o.push((()=>"writable"===t._state?wt(t,r):c(void 0))),a||o.push((()=>"readable"===e._state?Br(e,r):c(void 0))),q((()=>Promise.all(o.map((e=>e())))),!0,r)},i.aborted)return void v();i.addEventListener("abort",v)}var w,R,T;if(P(e,l._closedPromise,(e=>(n?E(!0,e):q((()=>wt(t,e)),!0,e),null))),P(t,s._closedPromise,(t=>(a?E(!0,t):q((()=>Br(e,t)),!0,t),null))),w=e,R=l._closedPromise,T=()=>(o?E():q((()=>function(e){const t=e._ownerWritableStream,r=t._state;return qt(t)||"closed"===r?c(void 0):"errored"===r?d(t._storedError):Ot(e)}(s))),null),"closed"===w._state?T():h(R,T),qt(t)||"closed"===t._state){const t=new TypeError("the destination writable stream closed before all data could be piped to it");a?E(!0,t):q((()=>Br(e,t)),!0,t)}function C(){const e=y;return f(y,(()=>e!==y?C():void 0))}function P(e,t,r){"errored"===e._state?r(e._storedError):m(t,r)}function q(e,r,o){function n(){return b(e(),(()=>B(r,o)),(e=>B(!0,e))),null}_||(_=!0,"writable"!==t._state||qt(t)?n():h(C(),n))}function E(e,r){_||(_=!0,"writable"!==t._state||qt(t)?B(e,r):h(C(),(()=>B(e,r))))}function B(e,t){return At(s),W(l),void 0!==i&&i.removeEventListener("abort",v),e?g(t):S(void 0),null}p(u(((e,t)=>{!function o(n){n?e():f(_?c(!0):f(s._readyPromise,(()=>u(((e,t)=>{K(l,{_chunkSteps:t=>{y=f(Dt(s,t),void 0,r),e(!1)},_closeSteps:()=>e(!0),_errorSteps:t})})))),o,t)}(!1)})))}))}class ReadableStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!lr(this))throw pr("desiredSize");return hr(this)}close(){if(!lr(this))throw pr("close");if(!mr(this))throw new TypeError("The stream is not in a state that permits close");dr(this)}enqueue(e=void 0){if(!lr(this))throw pr("enqueue");if(!mr(this))throw new TypeError("The stream is not in a state that permits enqueue");return fr(this,e)}error(e=void 0){if(!lr(this))throw pr("error");br(this,e)}[T](e){we(this);const t=this._cancelAlgorithm(e);return cr(this),t}[C](e){const t=this._controlledReadableStream;if(this._queue.length>0){const r=ge(this);this._closeRequested&&0===this._queue.length?(cr(this),Or(t)):sr(this),e._chunkSteps(r)}else V(t,e),sr(this)}[P](){}}function lr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof ReadableStreamDefaultController)}function sr(e){if(!ur(e))return;if(e._pulling)return void(e._pullAgain=!0);e._pulling=!0;b(e._pullAlgorithm(),(()=>(e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,sr(e)),null)),(t=>(br(e,t),null)))}function ur(e){const t=e._controlledReadableStream;if(!mr(e))return!1;if(!e._started)return!1;if(Wr(t)&&G(t)>0)return!0;return hr(e)>0}function cr(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function dr(e){if(!mr(e))return;const t=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(cr(e),Or(t))}function fr(e,t){if(!mr(e))return;const r=e._controlledReadableStream;if(Wr(r)&&G(r)>0)U(r,t,!1);else{let r;try{r=e._strategySizeAlgorithm(t)}catch(t){throw br(e,t),t}try{ve(e,t,r)}catch(t){throw br(e,t),t}}sr(e)}function br(e,t){const r=e._controlledReadableStream;"readable"===r._state&&(we(e),cr(e),jr(r,t))}function hr(e){const t=e._controlledReadableStream._state;return"errored"===t?null:"closed"===t?0:e._strategyHWM-e._queueTotalSize}function mr(e){const t=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===t}function _r(e,t,r,o,n,a,i){t._controlledReadableStream=e,t._queue=void 0,t._queueTotalSize=void 0,we(t),t._started=!1,t._closeRequested=!1,t._pullAgain=!1,t._pulling=!1,t._strategySizeAlgorithm=i,t._strategyHWM=a,t._pullAlgorithm=o,t._cancelAlgorithm=n,e._readableStreamController=t;b(c(r()),(()=>(t._started=!0,sr(t),null)),(e=>(br(t,e),null)))}function pr(e){return new TypeError(`ReadableStreamDefaultController.prototype.${e} can only be used on a ReadableStreamDefaultController`)}function yr(e,t){return Te(e._readableStreamController)?function(e){let t,r,o,n,a,i=H(e),l=!1,s=!1,d=!1,f=!1,b=!1;const h=u((e=>{a=e}));function _(e){m(e._closedPromise,(t=>(e!==i||(Qe(o._readableStreamController,t),Qe(n._readableStreamController,t),f&&b||a(void 0)),null)))}function p(){nt(i)&&(W(i),i=H(e),_(i));K(i,{_chunkSteps:t=>{y((()=>{s=!1,d=!1;const r=t;let i=t;if(!f&&!b)try{i=Se(t)}catch(t){return Qe(o._readableStreamController,t),Qe(n._readableStreamController,t),void a(Br(e,t))}f||xe(o._readableStreamController,r),b||xe(n._readableStreamController,i),l=!1,s?g():d&&v()}))},_closeSteps:()=>{l=!1,f||Ye(o._readableStreamController),b||Ye(n._readableStreamController),o._readableStreamController._pendingPullIntos.length>0&&Ue(o._readableStreamController,0),n._readableStreamController._pendingPullIntos.length>0&&Ue(n._readableStreamController,0),f&&b||a(void 0)},_errorSteps:()=>{l=!1}})}function S(t,r){J(i)&&(W(i),i=et(e),_(i));const u=r?n:o,c=r?o:n;at(i,t,1,{_chunkSteps:t=>{y((()=>{s=!1,d=!1;const o=r?b:f;if(r?f:b)o||Ge(u._readableStreamController,t);else{let r;try{r=Se(t)}catch(t){return Qe(u._readableStreamController,t),Qe(c._readableStreamController,t),void a(Br(e,t))}o||Ge(u._readableStreamController,t),xe(c._readableStreamController,r)}l=!1,s?g():d&&v()}))},_closeSteps:e=>{l=!1;const t=r?b:f,o=r?f:b;t||Ye(u._readableStreamController),o||Ye(c._readableStreamController),void 0!==e&&(t||Ge(u._readableStreamController,e),!o&&c._readableStreamController._pendingPullIntos.length>0&&Ue(c._readableStreamController,0)),t&&o||a(void 0)},_errorSteps:()=>{l=!1}})}function g(){if(l)return s=!0,c(void 0);l=!0;const e=He(o._readableStreamController);return null===e?p():S(e._view,!1),c(void 0)}function v(){if(l)return d=!0,c(void 0);l=!0;const e=He(n._readableStreamController);return null===e?p():S(e._view,!0),c(void 0)}function w(o){if(f=!0,t=o,b){const o=de([t,r]),n=Br(e,o);a(n)}return h}function R(o){if(b=!0,r=o,f){const o=de([t,r]),n=Br(e,o);a(n)}return h}function T(){}return o=Pr(T,g,w),n=Pr(T,v,R),_(i),[o,n]}(e):function(e,t){const r=H(e);let o,n,a,i,l,s=!1,d=!1,f=!1,b=!1;const h=u((e=>{l=e}));function _(){if(s)return d=!0,c(void 0);s=!0;return K(r,{_chunkSteps:e=>{y((()=>{d=!1;const t=e,r=e;f||fr(a._readableStreamController,t),b||fr(i._readableStreamController,r),s=!1,d&&_()}))},_closeSteps:()=>{s=!1,f||dr(a._readableStreamController),b||dr(i._readableStreamController),f&&b||l(void 0)},_errorSteps:()=>{s=!1}}),c(void 0)}function p(t){if(f=!0,o=t,b){const t=de([o,n]),r=Br(e,t);l(r)}return h}function S(t){if(b=!0,n=t,f){const t=de([o,n]),r=Br(e,t);l(r)}return h}function g(){}return a=Cr(g,_,p),i=Cr(g,_,S),m(r._closedPromise,(e=>(br(a._readableStreamController,e),br(i._readableStreamController,e),f&&b||l(void 0),null))),[a,i]}(e)}function Sr(e){return o(t=e)&&void 0!==t.getReader?function(e){let t;function n(){let r;try{r=e.read()}catch(e){return d(e)}return _(r,(e=>{if(!o(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)dr(t._readableStreamController);else{const r=e.value;fr(t._readableStreamController,r)}}))}function a(t){try{return c(e.cancel(t))}catch(e){return d(e)}}return t=Cr(r,n,a,0),t}(e.getReader()):function(e){let t;const n=ye(e,"async");function a(){let e;try{e=function(e){const t=S(e.nextMethod,e.iterator,[]);if(!o(t))throw new TypeError("The iterator.next() method must return an object");return t}(n)}catch(e){return d(e)}return _(c(e),(e=>{if(!o(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");const r=function(e){return Boolean(e.done)}(e);if(r)dr(t._readableStreamController);else{const r=function(e){return e.value}(e);fr(t._readableStreamController,r)}}))}function i(e){const t=n.iterator;let r,a;try{r=_e(t,"return")}catch(e){return d(e)}if(void 0===r)return c(void 0);try{a=S(r,t,[e])}catch(e){return d(e)}return _(c(a),(e=>{if(!o(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return t=Cr(r,a,i,0),t}(e);var t}function gr(e,t,r){return L(e,r),r=>g(e,t,[r])}function vr(e,t,r){return L(e,r),r=>g(e,t,[r])}function wr(e,t,r){return L(e,r),r=>S(e,t,[r])}function Rr(e,t){if("bytes"!==(e=`${e}`))throw new TypeError(`${t} '${e}' is not a valid enumeration value for ReadableStreamType`);return e}function Tr(e,t){I(e,t);const r=null==e?void 0:e.preventAbort,o=null==e?void 0:e.preventCancel,n=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,t){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError(`${t} is not an AbortSignal.`)}(a,`${t} has member 'signal' that`),{preventAbort:Boolean(r),preventCancel:Boolean(o),preventClose:Boolean(n),signal:a}}Object.defineProperties(ReadableStreamDefaultController.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),a(ReadableStreamDefaultController.prototype.close,"close"),a(ReadableStreamDefaultController.prototype.enqueue,"enqueue"),a(ReadableStreamDefaultController.prototype.error,"error"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStreamDefaultController.prototype,t.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});class ReadableStream{constructor(e={},t={}){void 0===e?e=null:F(e,"First parameter");const r=ct(t,"Second parameter"),o=function(e,t){I(e,t);const r=e,o=null==r?void 0:r.autoAllocateChunkSize,n=null==r?void 0:r.cancel,a=null==r?void 0:r.pull,i=null==r?void 0:r.start,l=null==r?void 0:r.type;return{autoAllocateChunkSize:void 0===o?void 0:Q(o,`${t} has member 'autoAllocateChunkSize' that`),cancel:void 0===n?void 0:gr(n,r,`${t} has member 'cancel' that`),pull:void 0===a?void 0:vr(a,r,`${t} has member 'pull' that`),start:void 0===i?void 0:wr(i,r,`${t} has member 'start' that`),type:void 0===l?void 0:Rr(l,`${t} has member 'type' that`)}}(e,"First parameter");if(qr(this),"bytes"===o.type){if(void 0!==r.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,t,r){const o=Object.create(ReadableByteStreamController.prototype);let n,a,i;n=void 0!==t.start?()=>t.start(o):()=>{},a=void 0!==t.pull?()=>t.pull(o):()=>c(void 0),i=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);const l=t.autoAllocateChunkSize;if(0===l)throw new TypeError("autoAllocateChunkSize must be greater than 0");Xe(e,o,n,a,i,r,l)}(this,o,st(r,0))}else{const e=ut(r);!function(e,t,r,o){const n=Object.create(ReadableStreamDefaultController.prototype);let a,i,l;a=void 0!==t.start?()=>t.start(n):()=>{},i=void 0!==t.pull?()=>t.pull(n):()=>c(void 0),l=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0),_r(e,n,a,i,l,r,o)}(this,o,st(r,1),e)}}get locked(){if(!Er(this))throw kr("locked");return Wr(this)}cancel(e=void 0){return Er(this)?Wr(this)?d(new TypeError("Cannot cancel a stream that already has a reader")):Br(this,e):d(kr("cancel"))}getReader(e=void 0){if(!Er(this))throw kr("getReader");return void 0===function(e,t){I(e,t);const r=null==e?void 0:e.mode;return{mode:void 0===r?void 0:Ze(r,`${t} has member 'mode' that`)}}(e,"First parameter").mode?H(this):et(this)}pipeThrough(e,t={}){if(!Er(this))throw kr("pipeThrough");$(e,1,"pipeThrough");const r=function(e,t){I(e,t);const r=null==e?void 0:e.readable;M(r,"readable","ReadableWritablePair"),N(r,`${t} has member 'readable' that`);const o=null==e?void 0:e.writable;return M(o,"writable","ReadableWritablePair"),_t(o,`${t} has member 'writable' that`),{readable:r,writable:o}}(e,"First parameter"),o=Tr(t,"Second parameter");if(Wr(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(vt(r.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return p(ir(this,r.writable,o.preventClose,o.preventAbort,o.preventCancel,o.signal)),r.readable}pipeTo(e,t={}){if(!Er(this))return d(kr("pipeTo"));if(void 0===e)return d("Parameter 1 is required in 'pipeTo'.");if(!gt(e))return d(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));let r;try{r=Tr(t,"Second parameter")}catch(e){return d(e)}return Wr(this)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):vt(e)?d(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):ir(this,e,r.preventClose,r.preventAbort,r.preventCancel,r.signal)}tee(){if(!Er(this))throw kr("tee");return de(yr(this))}values(e=void 0){if(!Er(this))throw kr("values");return function(e,t){const r=H(e),o=new re(r,t),n=Object.create(oe);return n._asyncIteratorImpl=o,n}(this,function(e,t){I(e,t);const r=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(r)}}(e,"First parameter").preventCancel)}static from(e){return Sr(e)}}function Cr(e,t,r,o=1,n=(()=>1)){const a=Object.create(ReadableStream.prototype);qr(a);return _r(a,Object.create(ReadableStreamDefaultController.prototype),e,t,r,o,n),a}function Pr(e,t,r){const o=Object.create(ReadableStream.prototype);qr(o);return Xe(o,Object.create(ReadableByteStreamController.prototype),e,t,r,0,void 0),o}function qr(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Er(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof ReadableStream)}function Wr(e){return void 0!==e._reader}function Br(e,t){if(e._disturbed=!0,"closed"===e._state)return c(void 0);if("errored"===e._state)return d(e._storedError);Or(e);const o=e._reader;if(void 0!==o&&nt(o)){const e=o._readIntoRequests;o._readIntoRequests=new v,e.forEach((e=>{e._closeSteps(void 0)}))}return _(e._readableStreamController[T](t),r)}function Or(e){e._state="closed";const t=e._reader;if(void 0!==t&&(A(t),J(t))){const e=t._readRequests;t._readRequests=new v,e.forEach((e=>{e._closeSteps()}))}}function jr(e,t){e._state="errored",e._storedError=t;const r=e._reader;void 0!==r&&(k(r,t),J(r)?Z(r,t):it(r,t))}function kr(e){return new TypeError(`ReadableStream.prototype.${e} can only be used on a ReadableStream`)}function Ar(e,t){I(e,t);const r=null==e?void 0:e.highWaterMark;return M(r,"highWaterMark","QueuingStrategyInit"),{highWaterMark:Y(r)}}Object.defineProperties(ReadableStream,{from:{enumerable:!0}}),Object.defineProperties(ReadableStream.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),a(ReadableStream.from,"from"),a(ReadableStream.prototype.cancel,"cancel"),a(ReadableStream.prototype.getReader,"getReader"),a(ReadableStream.prototype.pipeThrough,"pipeThrough"),a(ReadableStream.prototype.pipeTo,"pipeTo"),a(ReadableStream.prototype.tee,"tee"),a(ReadableStream.prototype.values,"values"),"symbol"==typeof t.toStringTag&&Object.defineProperty(ReadableStream.prototype,t.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof t.asyncIterator&&Object.defineProperty(ReadableStream.prototype,t.asyncIterator,{value:ReadableStream.prototype.values,writable:!0,configurable:!0});const Dr=e=>e.byteLength;a(Dr,"size");class ByteLengthQueuingStrategy{constructor(e){$(e,1,"ByteLengthQueuingStrategy"),e=Ar(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!Ir(this))throw zr("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark}get size(){if(!Ir(this))throw zr("size");return Dr}}function zr(e){return new TypeError(`ByteLengthQueuingStrategy.prototype.${e} can only be used on a ByteLengthQueuingStrategy`)}function Ir(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof ByteLengthQueuingStrategy)}Object.defineProperties(ByteLengthQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(ByteLengthQueuingStrategy.prototype,t.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});const Lr=()=>1;a(Lr,"size");class CountQueuingStrategy{constructor(e){$(e,1,"CountQueuingStrategy"),e=Ar(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}get highWaterMark(){if(!$r(this))throw Fr("highWaterMark");return this._countQueuingStrategyHighWaterMark}get size(){if(!$r(this))throw Fr("size");return Lr}}function Fr(e){return new TypeError(`CountQueuingStrategy.prototype.${e} can only be used on a CountQueuingStrategy`)}function $r(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof CountQueuingStrategy)}function Mr(e,t,r){return L(e,r),r=>g(e,t,[r])}function Yr(e,t,r){return L(e,r),r=>S(e,t,[r])}function xr(e,t,r){return L(e,r),(r,o)=>g(e,t,[r,o])}function Qr(e,t,r){return L(e,r),r=>g(e,t,[r])}Object.defineProperties(CountQueuingStrategy.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(CountQueuingStrategy.prototype,t.toStringTag,{value:"CountQueuingStrategy",configurable:!0});class TransformStream{constructor(e={},t={},r={}){void 0===e&&(e=null);const o=ct(t,"Second parameter"),n=ct(r,"Third parameter"),a=function(e,t){I(e,t);const r=null==e?void 0:e.cancel,o=null==e?void 0:e.flush,n=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,l=null==e?void 0:e.writableType;return{cancel:void 0===r?void 0:Qr(r,e,`${t} has member 'cancel' that`),flush:void 0===o?void 0:Mr(o,e,`${t} has member 'flush' that`),readableType:n,start:void 0===a?void 0:Yr(a,e,`${t} has member 'start' that`),transform:void 0===i?void 0:xr(i,e,`${t} has member 'transform' that`),writableType:l}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");const i=st(n,0),l=ut(n),s=st(o,1),f=ut(o);let h;!function(e,t,r,o,n,a){function i(){return t}function l(t){return function(e,t){const r=e._transformStreamController;if(e._backpressure){return _(e._backpressureChangePromise,(()=>{const o=e._writable;if("erroring"===o._state)throw o._storedError;return Zr(r,t)}))}return Zr(r,t)}(e,t)}function s(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._readable;r._finishPromise=u(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return Jr(r),b(n,(()=>("errored"===o._state?ro(r,o._storedError):(br(o._readableStreamController,t),to(r)),null)),(e=>(br(o._readableStreamController,e),ro(r,e),null))),r._finishPromise}(e,t)}function c(){return function(e){const t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;const r=e._readable;t._finishPromise=u(((e,r)=>{t._finishPromise_resolve=e,t._finishPromise_reject=r}));const o=t._flushAlgorithm();return Jr(t),b(o,(()=>("errored"===r._state?ro(t,r._storedError):(dr(r._readableStreamController),to(t)),null)),(e=>(br(r._readableStreamController,e),ro(t,e),null))),t._finishPromise}(e)}function d(){return function(e){return Gr(e,!1),e._backpressureChangePromise}(e)}function f(t){return function(e,t){const r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;const o=e._writable;r._finishPromise=u(((e,t)=>{r._finishPromise_resolve=e,r._finishPromise_reject=t}));const n=r._cancelAlgorithm(t);return Jr(r),b(n,(()=>("errored"===o._state?ro(r,o._storedError):(Yt(o._writableStreamController,t),Ur(e),to(r)),null)),(t=>(Yt(o._writableStreamController,t),Ur(e),ro(r,t),null))),r._finishPromise}(e,t)}e._writable=function(e,t,r,o,n=1,a=(()=>1)){const i=Object.create(WritableStream.prototype);return St(i),Lt(i,Object.create(WritableStreamDefaultController.prototype),e,t,r,o,n,a),i}(i,l,c,s,r,o),e._readable=Cr(i,d,f,n,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,Gr(e,!0),e._transformStreamController=void 0}(this,u((e=>{h=e})),s,f,i,l),function(e,t){const r=Object.create(TransformStreamDefaultController.prototype);let o,n,a;o=void 0!==t.transform?e=>t.transform(e,r):e=>{try{return Kr(r,e),c(void 0)}catch(e){return d(e)}};n=void 0!==t.flush?()=>t.flush(r):()=>c(void 0);a=void 0!==t.cancel?e=>t.cancel(e):()=>c(void 0);!function(e,t,r,o,n){t._controlledTransformStream=e,e._transformStreamController=t,t._transformAlgorithm=r,t._flushAlgorithm=o,t._cancelAlgorithm=n,t._finishPromise=void 0,t._finishPromise_resolve=void 0,t._finishPromise_reject=void 0}(e,r,o,n,a)}(this,a),void 0!==a.start?h(a.start(this._transformStreamController)):h(void 0)}get readable(){if(!Nr(this))throw oo("readable");return this._readable}get writable(){if(!Nr(this))throw oo("writable");return this._writable}}function Nr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof TransformStream)}function Hr(e,t){br(e._readable._readableStreamController,t),Vr(e,t)}function Vr(e,t){Jr(e._transformStreamController),Yt(e._writable._writableStreamController,t),Ur(e)}function Ur(e){e._backpressure&&Gr(e,!1)}function Gr(e,t){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=u((t=>{e._backpressureChangePromise_resolve=t})),e._backpressure=t}Object.defineProperties(TransformStream.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStream.prototype,t.toStringTag,{value:"TransformStream",configurable:!0});class TransformStreamDefaultController{constructor(){throw new TypeError("Illegal constructor")}get desiredSize(){if(!Xr(this))throw eo("desiredSize");return hr(this._controlledTransformStream._readable._readableStreamController)}enqueue(e=void 0){if(!Xr(this))throw eo("enqueue");Kr(this,e)}error(e=void 0){if(!Xr(this))throw eo("error");var t;t=e,Hr(this._controlledTransformStream,t)}terminate(){if(!Xr(this))throw eo("terminate");!function(e){const t=e._controlledTransformStream;dr(t._readable._readableStreamController);const r=new TypeError("TransformStream terminated");Vr(t,r)}(this)}}function Xr(e){return!!o(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof TransformStreamDefaultController)}function Jr(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function Kr(e,t){const r=e._controlledTransformStream,o=r._readable._readableStreamController;if(!mr(o))throw new TypeError("Readable side is not in a state that permits enqueue");try{fr(o,t)}catch(e){throw Vr(r,e),r._readable._storedError}const n=function(e){return!ur(e)}(o);n!==r._backpressure&&Gr(r,!0)}function Zr(e,t){return _(e._transformAlgorithm(t),void 0,(t=>{throw Hr(e._controlledTransformStream,t),t}))}function eo(e){return new TypeError(`TransformStreamDefaultController.prototype.${e} can only be used on a TransformStreamDefaultController`)}function to(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function ro(e,t){void 0!==e._finishPromise_reject&&(p(e._finishPromise),e._finishPromise_reject(t),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function oo(e){return new TypeError(`TransformStream.prototype.${e} can only be used on a TransformStream`)}Object.defineProperties(TransformStreamDefaultController.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),a(TransformStreamDefaultController.prototype.enqueue,"enqueue"),a(TransformStreamDefaultController.prototype.error,"error"),a(TransformStreamDefaultController.prototype.terminate,"terminate"),"symbol"==typeof t.toStringTag&&Object.defineProperty(TransformStreamDefaultController.prototype,t.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});const no={ReadableStream:ReadableStream,ReadableStreamDefaultController:ReadableStreamDefaultController,ReadableByteStreamController:ReadableByteStreamController,ReadableStreamBYOBRequest:ReadableStreamBYOBRequest,ReadableStreamDefaultReader:ReadableStreamDefaultReader,ReadableStreamBYOBReader:ReadableStreamBYOBReader,WritableStream:WritableStream,WritableStreamDefaultController:WritableStreamDefaultController,WritableStreamDefaultWriter:WritableStreamDefaultWriter,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream,TransformStreamDefaultController:TransformStreamDefaultController};if(void 0!==nr)for(const e in no)Object.prototype.hasOwnProperty.call(no,e)&&Object.defineProperty(nr,e,{value:no[e],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,e.CountQueuingStrategy=CountQueuingStrategy,e.ReadableByteStreamController=ReadableByteStreamController,e.ReadableStream=ReadableStream,e.ReadableStreamBYOBReader=ReadableStreamBYOBReader,e.ReadableStreamBYOBRequest=ReadableStreamBYOBRequest,e.ReadableStreamDefaultController=ReadableStreamDefaultController,e.ReadableStreamDefaultReader=ReadableStreamDefaultReader,e.TransformStream=TransformStream,e.TransformStreamDefaultController=TransformStreamDefaultController,e.WritableStream=WritableStream,e.WritableStreamDefaultController=WritableStreamDefaultController,e.WritableStreamDefaultWriter=WritableStreamDefaultWriter})); +//# sourceMappingURL=polyfill.es6.min.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map b/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map new file mode 100644 index 0000000..6720317 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.min.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["SymbolPolyfill","Symbol","iterator","description","noop","typeIsObject","x","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","value","configurable","_a","originalPromise","Promise","originalPromiseThen","prototype","then","originalPromiseReject","reject","bind","newPromise","executor","promiseResolvedWith","resolve","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","call","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise","cb","reflectCall","F","V","args","TypeError","Function","apply","promiseCall","SimpleQueue","constructor","this","_cursor","_size","_front","_elements","_next","_back","length","push","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","shift","oldFront","newFront","oldCursor","newCursor","elements","forEach","i","node","peek","front","cursor","AbortSteps","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","v","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","done","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","IsReadableStreamLocked","closed","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","e","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","AsyncIteratorPrototype","defineProperties","enumerable","toStringTag","asyncIterator","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","next","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","return","setPrototypeOf","NumberIsNaN","isNaN","__values","o","s","m","__await","__asyncGenerator","thisArg","_arguments","generator","g","q","verb","n","a","b","resume","r","fulfill","settle","f","__asyncValues","d","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","Uint8Array","set","SuppressedError","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","CreateAsyncFromSyncIterator","syncIteratorRecord","syncIterable","p","__asyncDelegator","nextMethod","GetIterator","hint","method","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","view","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","byobRequest","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","desiredSize","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","WritableStreamDefaultController","writeAlgorithm","closeAlgorithm","abortAlgorithm","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","locked","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","abortRequest","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","abortReason","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","getFromGlobal","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","actions","shutdownWithAction","all","map","action","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","AcquireReadableStreamAsyncIterator","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise_resolve","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","TransformStreamDefaultController","transformAlgorithm","flushAlgorithm","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"mappings":";;;;;;;0PAEA,MAAMA,EACc,mBAAXC,QAAoD,iBAApBA,OAAOC,SAC5CD,OACAE,GAAe,UAAUA,cCLbC,IAEhB,CCCM,SAAUC,EAAaC,GAC3B,MAAqB,iBAANA,GAAwB,OAANA,GAA4B,mBAANA,CACzD,CAEO,MAAMC,EAUPH,EAEU,SAAAI,EAAgBC,EAAcC,GAC5C,IACEC,OAAOC,eAAeH,EAAI,OAAQ,CAChCI,MAAOH,EACPI,cAAc,GAEjB,CAAC,MAAAC,GAGD,CACH,CC1BA,MAAMC,EAAkBC,QAClBC,EAAsBD,QAAQE,UAAUC,KACxCC,EAAwBJ,QAAQK,OAAOC,KAAKP,GAG5C,SAAUQ,EAAcC,GAI5B,OAAO,IAAIT,EAAgBS,EAC7B,CAGM,SAAUC,EAAuBb,GACrC,OAAOW,GAAWG,GAAWA,EAAQd,IACvC,CAGM,SAAUe,EAA+BC,GAC7C,OAAOR,EAAsBQ,EAC/B,UAEgBC,EACdC,EACAC,EACAC,GAGA,OAAOf,EAAoBgB,KAAKH,EAASC,EAAaC,EACxD,UAKgBE,EACdJ,EACAC,EACAC,GACAH,EACEA,EAAmBC,EAASC,EAAaC,QACzCG,EACA7B,EAEJ,CAEgB,SAAA8B,EAAmBN,EAAqBC,GACtDG,EAAYJ,EAASC,EACvB,CAEgB,SAAAM,EAAcP,EAA2BE,GACvDE,EAAYJ,OAASK,EAAWH,EAClC,UAEgBM,EACdR,EACAS,EACAC,GACA,OAAOX,EAAmBC,EAASS,EAAoBC,EACzD,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VlB,MAAMqsB,GAAU,CACd/F,8BACAtE,gEACA5R,0DACAZ,oDACA7H,wDACA4O,kDAEA2B,8BACAW,gEACAc,wDAEAoO,oDACAK,0CAEAQ,gCACAwC,mEAIF,QAAuB,IAAZ9L,GACT,IAAK,MAAMzR,KAAQwe,GACbxsB,OAAOQ,UAAU+I,eAAehI,KAAKirB,GAASxe,IAChDhO,OAAOC,eAAewf,GAASzR,EAAM,CACnC9N,MAAOssB,GAAQxe,GACfmS,UAAU,EACVhgB,cAAc","x_google_ignoreList":[15]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs b/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs new file mode 100644 index 0000000..a80612b --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs @@ -0,0 +1,4824 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +const PullSteps = SymbolPolyfill('[[PullSteps]]'); +const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +let AsyncIteratorPrototype; +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolPolyfill.asyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); +} + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +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; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +const exports = { + ReadableStream, + ReadableStreamDefaultController, + ReadableByteStreamController, + ReadableStreamBYOBRequest, + ReadableStreamDefaultReader, + ReadableStreamBYOBReader, + WritableStream, + WritableStreamDefaultController, + WritableStreamDefaultWriter, + ByteLengthQueuingStrategy, + CountQueuingStrategy, + TransformStream, + TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (const prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.es6.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map b/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map new file mode 100644 index 0000000..e4e1ca5 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.es6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.es6.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;AAAA;AAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;AACjE,IAAA,MAAM;AAC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KACR;AAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;AACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;ACzoBA,MAAM,OAAO,GAAG;IACd,cAAc;IACd,+BAA+B;IAC/B,4BAA4B;IAC5B,yBAAyB;IACzB,2BAA2B;IAC3B,wBAAwB;IAExB,cAAc;IACd,+BAA+B;IAC/B,2BAA2B;IAE3B,yBAAyB;IACzB,oBAAoB;IAEpB,eAAe;IACf,gCAAgC;CACjC,CAAC;AAEF;AACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;AAClC,IAAA,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE;AAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;AACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;AACnC,gBAAA,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;AAC9C,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,YAAY,EAAE,IAAI;AACnB,aAAA,CAAC,CAAC;SACJ;KACF;AACH;;;;","x_google_ignoreList":[15]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.js b/node_modules/web-streams-polyfill/dist/polyfill.js new file mode 100644 index 0000000..18d6df2 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.js @@ -0,0 +1,5012 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + 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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + 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; + }; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + var rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + var originalPromise = Promise; + var originalPromiseThen = Promise.prototype.then; + var originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + var QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; + }()); + + var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + var PullSteps = SymbolPolyfill('[[PullSteps]]'); + var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; + }()); + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); + } + + /// + var _a; + var AsyncIteratorPrototype; + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolPolyfill.asyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); + } + + /// + var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; + }()); + var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); + }; + var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; + } + function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; + }()); + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; + }()); + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; + }()); + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + var supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; + }()); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; + }()); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + var closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; + }()); + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + var globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + var DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; + }()); + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; + }()); + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; + }()); + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + var countSizeFunction = function () { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; + }()); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; + }()); + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; + }()); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); + } + + var exports$1 = { + ReadableStream: ReadableStream, + ReadableStreamDefaultController: ReadableStreamDefaultController, + ReadableByteStreamController: ReadableByteStreamController, + ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, + ReadableStreamDefaultReader: ReadableStreamDefaultReader, + ReadableStreamBYOBReader: ReadableStreamBYOBReader, + WritableStream: WritableStream, + WritableStreamDefaultController: WritableStreamDefaultController, + WritableStreamDefaultWriter: WritableStreamDefaultWriter, + ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, + CountQueuingStrategy: CountQueuingStrategy, + TransformStream: TransformStream, + TransformStreamDefaultController: TransformStreamDefaultController + }; + // Add classes to global scope + if (typeof globals !== 'undefined') { + for (var prop in exports$1) { + if (Object.prototype.hasOwnProperty.call(exports$1, prop)) { + Object.defineProperty(globals, prop, { + value: exports$1[prop], + writable: true, + configurable: true + }); + } + } + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=polyfill.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.js.map b/node_modules/web-streams-polyfill/dist/polyfill.js.map new file mode 100644 index 0000000..67a787f --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException","exports"],"mappings":";;;;;;;;;;;;;IAAA;IAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,IAAA,MAAM;QACN,UAAA,WAAW,IAAI,OAAA,SAAA,CAAA,MAAA,CAAU,WAAW,EAAoB,GAAA,CAAA,CAAA,EAAA;;ICL5D;IACA;AACA;IACA;IACA;AACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;AACA;AA4GA;IACO,SAAS,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE;IAC3C,IAAI,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,EAAE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AA,eAAA;IACf,IAAA,gCAAgC,EAAA,gCAAA;KACjC,CAAC;IAEF;IACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;IAClC,IAAA,KAAK,IAAM,IAAI,IAAIA,SAAO,EAAE;IAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAACA,SAAO,EAAE,IAAI,CAAC,EAAE;IACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;IACnC,gBAAA,KAAK,EAAEA,SAAO,CAAC,IAA8B,CAAC;IAC9C,gBAAA,QAAQ,EAAE,IAAI;IACd,gBAAA,YAAY,EAAE,IAAI;IACnB,aAAA,CAAC,CAAC;aACJ;SACF;IACH;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.min.js b/node_modules/web-streams-polyfill/dist/polyfill.min.js new file mode 100644 index 0000000..00905a8 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.min.js @@ -0,0 +1,9 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).WebStreamsPolyfill={})}(this,(function(e){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol:function(e){return"Symbol(".concat(e,")")};function t(e,r){var t,n,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function u(u){return function(l){return function(u){if(t)throw new TypeError("Generator is already executing.");for(;a&&(a=0,u[0]&&(i=0)),i;)try{if(t=1,n&&(o=2&u[0]?n.return:u[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,u[1])).done)return o;switch(n=0,o&&(u=[2&u[0],o.value]),u[0]){case 0:case 1:o=u;break;case 4:return i.label++,{value:u[1],done:!1};case 5:i.label++,n=u[1],u=[0];continue;case 7:u=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==u[0]&&2!==u[0])){i=0;continue}if(3===u[0]&&(!o||u[1]>o[0]&&u[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(r?"Object is not iterable.":"Symbol.iterator is not defined.")}function o(e){return this instanceof o?(this.v=e,this):new o(e)}function a(e,r,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,a=t.apply(e,r||[]),i=[];return n={},u("next"),u("throw"),u("return"),n[Symbol.asyncIterator]=function(){return this},n;function u(e){a[e]&&(n[e]=function(r){return new Promise((function(t,n){i.push([e,r,t,n])>1||l(e,r)}))})}function l(e,r){try{(t=a[e](r)).value instanceof o?Promise.resolve(t.value.v).then(s,c):f(i[0][2],t)}catch(e){f(i[0][3],e)}var t}function s(e){l("next",e)}function c(e){l("throw",e)}function f(e,r){e(r),i.shift(),i.length&&l(i[0][0],i[0][1])}}function i(e){var r,t;return r={},n("next"),n("throw",(function(e){throw e})),n("return"),r[Symbol.iterator]=function(){return this},r;function n(n,a){r[n]=e[n]?function(r){return(t=!t)?{value:o(e[n](r)),done:!1}:a?a(r):r}:a}}function u(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,t=e[Symbol.asyncIterator];return t?t.call(e):(e=n(e),r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r);function o(t){r[t]=e[t]&&function(r){return new Promise((function(n,o){(function(e,r,t,n){Promise.resolve(n).then((function(r){e({value:r,done:t})}),r)})(n,o,(r=e[t](r)).done,r.value)}))}}}function l(){}function s(e){return"object"==typeof e&&null!==e||"function"==typeof e}"function"==typeof SuppressedError&&SuppressedError;var c=l;function f(e,r){try{Object.defineProperty(e,"name",{value:r,configurable:!0})}catch(e){}}var d=Promise,b=Promise.prototype.then,p=Promise.reject.bind(d);function h(e){return new d(e)}function m(e){return h((function(r){return r(e)}))}function _(e){return p(e)}function y(e,r,t){return b.call(e,r,t)}function v(e,r,t){y(y(e,r,t),void 0,c)}function g(e,r){v(e,r)}function S(e,r){v(e,void 0,r)}function w(e,r,t){return y(e,r,t)}function R(e){y(e,void 0,c)}var T=function(e){if("function"==typeof queueMicrotask)T=queueMicrotask;else{var r=m(void 0);T=function(e){return y(r,e)}}return T(e)};function P(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}function C(e,r,t){try{return m(P(e,r,t))}catch(e){return _(e)}}var q=function(){function e(){this._cursor=0,this._size=0,this._front={_elements:[],_next:void 0},this._back=this._front,this._cursor=0,this._size=0}return Object.defineProperty(e.prototype,"length",{get:function(){return this._size},enumerable:!1,configurable:!0}),e.prototype.push=function(e){var r=this._back,t=r;16383===r._elements.length&&(t={_elements:[],_next:void 0}),r._elements.push(e),t!==r&&(this._back=t,r._next=t),++this._size},e.prototype.shift=function(){var e=this._front,r=e,t=this._cursor,n=t+1,o=e._elements,a=o[t];return 16384===n&&(r=e._next,n=0),--this._size,this._cursor=n,e!==r&&(this._front=r),o[t]=void 0,a},e.prototype.forEach=function(e){for(var r=this._cursor,t=this._front,n=t._elements;!(r===n.length&&void 0===t._next||r===n.length&&(r=0,0===(n=(t=t._next)._elements).length));)e(n[r]),++r},e.prototype.peek=function(){var e=this._front,r=this._cursor;return e._elements[r]},e}(),E=r("[[AbortSteps]]"),O=r("[[ErrorSteps]]"),W=r("[[CancelSteps]]"),j=r("[[PullSteps]]"),B=r("[[ReleaseSteps]]");function k(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?D(e):"closed"===r._state?function(e){D(e),M(e)}(e):L(e,r._storedError)}function A(e,r){return Yt(e._ownerReadableStream,r)}function z(e){var r=e._ownerReadableStream;"readable"===r._state?F(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):function(e,r){L(e,r)}(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),r._readableStreamController[B](),r._reader=void 0,e._ownerReadableStream=void 0}function I(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function D(e){e._closedPromise=h((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t}))}function L(e,r){D(e),F(e,r)}function F(e,r){void 0!==e._closedPromise_reject&&(R(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}function M(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0)}var x=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},Y=Math.trunc||function(e){return e<0?Math.ceil(e):Math.floor(e)};function Q(e,r){if(void 0!==e&&("object"!=typeof(t=e)&&"function"!=typeof t))throw new TypeError("".concat(r," is not an object."));var t}function N(e,r){if("function"!=typeof e)throw new TypeError("".concat(r," is not a function."))}function H(e,r){if(!function(e){return"object"==typeof e&&null!==e||"function"==typeof e}(e))throw new TypeError("".concat(r," is not an object."))}function V(e,r,t){if(void 0===e)throw new TypeError("Parameter ".concat(r," is required in '").concat(t,"'."))}function U(e,r,t){if(void 0===e)throw new TypeError("".concat(r," is required in '").concat(t,"'."))}function G(e){return Number(e)}function X(e){return 0===e?0:e}function J(e,r){var t=Number.MAX_SAFE_INTEGER,n=Number(e);if(n=X(n),!x(n))throw new TypeError("".concat(r," is not a finite number"));if((n=function(e){return X(Y(e))}(n))<0||n>t)throw new TypeError("".concat(r," is outside the accepted range of ").concat(0," to ").concat(t,", inclusive"));return x(n)&&0!==n?n:0}function K(e,r){if(!Mt(e))throw new TypeError("".concat(r," is not a ReadableStream."))}function Z(e){return new ae(e)}function $(e,r){e._reader._readRequests.push(r)}function ee(e,r,t){var n=e._reader._readRequests.shift();t?n._closeSteps():n._chunkSteps(r)}function re(e){return e._reader._readRequests.length}function te(e){var r=e._reader;return void 0!==r&&!!ie(r)}var ne,oe,ae=function(){function ReadableStreamDefaultReader(e){if(V(e,1,"ReadableStreamDefaultReader"),K(e,"First parameter"),xt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");k(this,e),this._readRequests=new q}return Object.defineProperty(ReadableStreamDefaultReader.prototype,"closed",{get:function(){return ie(this)?this._closedPromise:_(se("closed"))},enumerable:!1,configurable:!0}),ReadableStreamDefaultReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),ie(this)?void 0===this._ownerReadableStream?_(I("cancel")):A(this,e):_(se("cancel"))},ReadableStreamDefaultReader.prototype.read=function(){if(!ie(this))return _(se("read"));if(void 0===this._ownerReadableStream)return _(I("read from"));var e,r,t=h((function(t,n){e=t,r=n}));return ue(this,{_chunkSteps:function(r){return e({value:r,done:!1})},_closeSteps:function(){return e({value:void 0,done:!0})},_errorSteps:function(e){return r(e)}}),t},ReadableStreamDefaultReader.prototype.releaseLock=function(){if(!ie(this))throw se("releaseLock");void 0!==this._ownerReadableStream&&function(e){z(e);var r=new TypeError("Reader was released");le(e,r)}(this)},ReadableStreamDefaultReader}();function ie(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readRequests")&&e instanceof ae)}function ue(e,r){var t=e._ownerReadableStream;t._disturbed=!0,"closed"===t._state?r._closeSteps():"errored"===t._state?r._errorSteps(t._storedError):t._readableStreamController[j](r)}function le(e,r){var t=e._readRequests;e._readRequests=new q,t.forEach((function(e){e._errorSteps(r)}))}function se(e){return new TypeError("ReadableStreamDefaultReader.prototype.".concat(e," can only be used on a ReadableStreamDefaultReader"))}Object.defineProperties(ae.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),f(ae.prototype.cancel,"cancel"),f(ae.prototype.read,"read"),f(ae.prototype.releaseLock,"releaseLock"),"symbol"==typeof r.toStringTag&&Object.defineProperty(ae.prototype,r.toStringTag,{value:"ReadableStreamDefaultReader",configurable:!0}),"symbol"==typeof r.asyncIterator&&((ne={})[r.asyncIterator]=function(){return this},oe=ne,Object.defineProperty(oe,r.asyncIterator,{enumerable:!1}));var ce=function(){function e(e,r){this._ongoingPromise=void 0,this._isFinished=!1,this._reader=e,this._preventCancel=r}return e.prototype.next=function(){var e=this,r=function(){return e._nextSteps()};return this._ongoingPromise=this._ongoingPromise?w(this._ongoingPromise,r,r):r(),this._ongoingPromise},e.prototype.return=function(e){var r=this,t=function(){return r._returnSteps(e)};return this._ongoingPromise?w(this._ongoingPromise,t,t):t()},e.prototype._nextSteps=function(){var e=this;if(this._isFinished)return Promise.resolve({value:void 0,done:!0});var r,t,n=this._reader,o=h((function(e,n){r=e,t=n}));return ue(n,{_chunkSteps:function(t){e._ongoingPromise=void 0,T((function(){return r({value:t,done:!1})}))},_closeSteps:function(){e._ongoingPromise=void 0,e._isFinished=!0,z(n),r({value:void 0,done:!0})},_errorSteps:function(r){e._ongoingPromise=void 0,e._isFinished=!0,z(n),t(r)}}),o},e.prototype._returnSteps=function(e){if(this._isFinished)return Promise.resolve({value:e,done:!0});this._isFinished=!0;var r=this._reader;if(!this._preventCancel){var t=A(r,e);return z(r),w(t,(function(){return{value:e,done:!0}}))}return z(r),m({value:e,done:!0})},e}(),fe={next:function(){return de(this)?this._asyncIteratorImpl.next():_(be("next"))},return:function(e){return de(this)?this._asyncIteratorImpl.return(e):_(be("return"))}};function de(e){if(!s(e))return!1;if(!Object.prototype.hasOwnProperty.call(e,"_asyncIteratorImpl"))return!1;try{return e._asyncIteratorImpl instanceof ce}catch(e){return!1}}function be(e){return new TypeError("ReadableStreamAsyncIterator.".concat(e," can only be used on a ReadableSteamAsyncIterator"))}void 0!==oe&&Object.setPrototypeOf(fe,oe);var pe=Number.isNaN||function(e){return e!=e};function he(e){return e.slice()}function me(e,r,t,n,o){new Uint8Array(e).set(new Uint8Array(t,n,o),r)}var _e=function(e){return(_e="function"==typeof e.transfer?function(e){return e.transfer()}:"function"==typeof structuredClone?function(e){return structuredClone(e,{transfer:[e]})}:function(e){return e})(e)},ye=function(e){return(ye="boolean"==typeof e.detached?function(e){return e.detached}:function(e){return 0===e.byteLength})(e)};function ve(e,r,t){if(e.slice)return e.slice(r,t);var n=t-r,o=new ArrayBuffer(n);return me(o,0,e,r,n),o}function ge(e,r){var t=e[r];if(null!=t){if("function"!=typeof t)throw new TypeError("".concat(String(r)," is not a function"));return t}}function Se(e,l,c){if(void 0===l&&(l="sync"),void 0===c)if("async"===l){if(void 0===(c=ge(e,r.asyncIterator)))return function(e){var l,s=((l={})[r.iterator]=function(){return e.iterator},l),c=function(){return a(this,arguments,(function(){return t(this,(function(e){switch(e.label){case 0:return[5,n(i(u(s)))];case 1:case 2:return[4,o.apply(void 0,[e.sent()])];case 3:return[2,e.sent()]}}))}))}();return{iterator:c,nextMethod:c.next,done:!1}}(Se(e,"sync",ge(e,r.iterator)))}else c=ge(e,r.iterator);if(void 0===c)throw new TypeError("The object is not iterable");var f=P(c,e,[]);if(!s(f))throw new TypeError("The iterator method must return an object");return{iterator:f,nextMethod:f.next,done:!1}}function we(e){var r=ve(e.buffer,e.byteOffset,e.byteOffset+e.byteLength);return new Uint8Array(r)}function Re(e){var r=e._queue.shift();return e._queueTotalSize-=r.size,e._queueTotalSize<0&&(e._queueTotalSize=0),r.value}function Te(e,r,t){if("number"!=typeof(n=t)||pe(n)||n<0||t===1/0)throw new RangeError("Size must be a finite, non-NaN, non-negative number.");var n;e._queue.push({value:r,size:t}),e._queueTotalSize+=t}function Pe(e){e._queue=new q,e._queueTotalSize=0}function Ce(e){return e===DataView}var qe=function(){function ReadableStreamBYOBRequest(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamBYOBRequest.prototype,"view",{get:function(){if(!We(this))throw tr("view");return this._view},enumerable:!1,configurable:!0}),ReadableStreamBYOBRequest.prototype.respond=function(e){if(!We(this))throw tr("respond");if(V(e,1,"respond"),e=J(e,"First parameter"),void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(ye(this._view.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response");$e(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest.prototype.respondWithNewView=function(e){if(!We(this))throw tr("respondWithNewView");if(V(e,1,"respondWithNewView"),!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(ye(e.buffer))throw new TypeError("The given view's buffer has been detached and so cannot be used as a response");er(this._associatedReadableByteStreamController,e)},ReadableStreamBYOBRequest}();Object.defineProperties(qe.prototype,{respond:{enumerable:!0},respondWithNewView:{enumerable:!0},view:{enumerable:!0}}),f(qe.prototype.respond,"respond"),f(qe.prototype.respondWithNewView,"respondWithNewView"),"symbol"==typeof r.toStringTag&&Object.defineProperty(qe.prototype,r.toStringTag,{value:"ReadableStreamBYOBRequest",configurable:!0});var Ee=function(){function ReadableByteStreamController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableByteStreamController.prototype,"byobRequest",{get:function(){if(!Oe(this))throw nr("byobRequest");return Ke(this)},enumerable:!1,configurable:!0}),Object.defineProperty(ReadableByteStreamController.prototype,"desiredSize",{get:function(){if(!Oe(this))throw nr("desiredSize");return Ze(this)},enumerable:!1,configurable:!0}),ReadableByteStreamController.prototype.close=function(){if(!Oe(this))throw nr("close");if(this._closeRequested)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableByteStream._state;if("readable"!==e)throw new TypeError("The stream (in ".concat(e," state) is not in the readable state and cannot be closed"));Ue(this)},ReadableByteStreamController.prototype.enqueue=function(e){if(!Oe(this))throw nr("enqueue");if(V(e,1,"enqueue"),!ArrayBuffer.isView(e))throw new TypeError("chunk must be an array buffer view");if(0===e.byteLength)throw new TypeError("chunk must have non-zero byteLength");if(0===e.buffer.byteLength)throw new TypeError("chunk's buffer must have non-zero byteLength");if(this._closeRequested)throw new TypeError("stream is closed or draining");var r=this._controlledReadableByteStream._state;if("readable"!==r)throw new TypeError("The stream (in ".concat(r," state) is not in the readable state and cannot be enqueued to"));Ge(this,e)},ReadableByteStreamController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Oe(this))throw nr("error");Xe(this,e)},ReadableByteStreamController.prototype[W]=function(e){Be(this),Pe(this);var r=this._cancelAlgorithm(e);return Ve(this),r},ReadableByteStreamController.prototype[j]=function(e){var r=this._controlledReadableByteStream;if(this._queueTotalSize>0)Je(this,e);else{var t=this._autoAllocateChunkSize;if(void 0!==t){var n=void 0;try{n=new ArrayBuffer(t)}catch(r){return void e._errorSteps(r)}var o={buffer:n,bufferByteLength:t,byteOffset:0,byteLength:t,bytesFilled:0,minimumFill:1,elementSize:1,viewConstructor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}$(r,e),je(this)}},ReadableByteStreamController.prototype[B]=function(){if(this._pendingPullIntos.length>0){var e=this._pendingPullIntos.peek();e.readerType="none",this._pendingPullIntos=new q,this._pendingPullIntos.push(e)}},ReadableByteStreamController}();function Oe(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableByteStream")&&e instanceof Ee)}function We(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")&&e instanceof qe)}function je(e){var r=function(e){var r=e._controlledReadableByteStream;if("readable"!==r._state)return!1;if(e._closeRequested)return!1;if(!e._started)return!1;if(te(r)&&re(r)>0)return!0;if(lr(r)&&ur(r)>0)return!0;var t=Ze(e);if(t>0)return!0;return!1}(e);r&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,v(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,je(e)),null}),(function(r){return Xe(e,r),null}))))}function Be(e){xe(e),e._pendingPullIntos=new q}function ke(e,r){var t=!1;"closed"===e._state&&(t=!0);var n=Ae(r);"default"===r.readerType?ee(e,n,t):function(e,r,t){var n=e._reader,o=n._readIntoRequests.shift();t?o._closeSteps(r):o._chunkSteps(r)}(e,n,t)}function Ae(e){var r=e.bytesFilled,t=e.elementSize;return new e.viewConstructor(e.buffer,e.byteOffset,r/t)}function ze(e,r,t,n){e._queue.push({buffer:r,byteOffset:t,byteLength:n}),e._queueTotalSize+=n}function Ie(e,r,t,n){var o;try{o=ve(r,t,t+n)}catch(r){throw Xe(e,r),r}ze(e,o,0,n)}function De(e,r){r.bytesFilled>0&&Ie(e,r.buffer,r.byteOffset,r.bytesFilled),He(e)}function Le(e,r){var t=Math.min(e._queueTotalSize,r.byteLength-r.bytesFilled),n=r.bytesFilled+t,o=t,a=!1,i=n-n%r.elementSize;i>=r.minimumFill&&(o=i-r.bytesFilled,a=!0);for(var u=e._queue;o>0;){var l=u.peek(),s=Math.min(o,l.byteLength),c=r.byteOffset+r.bytesFilled;me(r.buffer,c,l.buffer,l.byteOffset,s),l.byteLength===s?u.shift():(l.byteOffset+=s,l.byteLength-=s),e._queueTotalSize-=s,Fe(e,s,r),o-=s}return a}function Fe(e,r,t){t.bytesFilled+=r}function Me(e){0===e._queueTotalSize&&e._closeRequested?(Ve(e),Qt(e._controlledReadableByteStream)):je(e)}function xe(e){null!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=null,e._byobRequest=null)}function Ye(e){for(;e._pendingPullIntos.length>0;){if(0===e._queueTotalSize)return;var r=e._pendingPullIntos.peek();Le(e,r)&&(He(e),ke(e._controlledReadableByteStream,r))}}function Qe(e,r,t,n){var o,a=e._controlledReadableByteStream,i=r.constructor,u=function(e){return Ce(e)?1:e.BYTES_PER_ELEMENT}(i),l=r.byteOffset,s=r.byteLength,c=t*u;try{o=_e(r.buffer)}catch(b){return void n._errorSteps(b)}var f={buffer:o,bufferByteLength:o.byteLength,byteOffset:l,byteLength:s,bytesFilled:0,minimumFill:c,elementSize:u,viewConstructor:i,readerType:"byob"};if(e._pendingPullIntos.length>0)return e._pendingPullIntos.push(f),void ir(a,n);if("closed"!==a._state){if(e._queueTotalSize>0){if(Le(e,f)){var d=Ae(f);return Me(e),void n._chunkSteps(d)}if(e._closeRequested){var b=new TypeError("Insufficient bytes to fill elements in the given buffer");return Xe(e,b),void n._errorSteps(b)}}e._pendingPullIntos.push(f),ir(a,n),je(e)}else{var p=new i(f.buffer,f.byteOffset,0);n._closeSteps(p)}}function Ne(e,r){var t=e._pendingPullIntos.peek();xe(e),"closed"===e._controlledReadableByteStream._state?function(e,r){"none"===r.readerType&&He(e);var t=e._controlledReadableByteStream;if(lr(t))for(;ur(t)>0;)ke(t,He(e))}(e,t):function(e,r,t){if(Fe(0,r,t),"none"===t.readerType)return De(e,t),void Ye(e);if(!(t.bytesFilled0){var o=t.byteOffset+t.bytesFilled;Ie(e,t.buffer,o-n,n)}t.bytesFilled-=n,ke(e._controlledReadableByteStream,t),Ye(e)}}(e,r,t),je(e)}function He(e){return e._pendingPullIntos.shift()}function Ve(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0}function Ue(e){var r=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===r._state)if(e._queueTotalSize>0)e._closeRequested=!0;else{if(e._pendingPullIntos.length>0){var t=e._pendingPullIntos.peek();if(t.bytesFilled%t.elementSize!=0){var n=new TypeError("Insufficient bytes to fill elements in the given buffer");throw Xe(e,n),n}}Ve(e),Qt(r)}}function Ge(e,r){var t=e._controlledReadableByteStream;if(!e._closeRequested&&"readable"===t._state){var n=r.buffer,o=r.byteOffset,a=r.byteLength;if(ye(n))throw new TypeError("chunk's buffer is detached and so cannot be enqueued");var i=_e(n);if(e._pendingPullIntos.length>0){var u=e._pendingPullIntos.peek();if(ye(u.buffer))throw new TypeError("The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk");xe(e),u.buffer=_e(u.buffer),"none"===u.readerType&&De(e,u)}if(te(t))if(function(e){for(var r=e._controlledReadableByteStream._reader;r._readRequests.length>0;){if(0===e._queueTotalSize)return;Je(e,r._readRequests.shift())}}(e),0===re(t))ze(e,i,o,a);else e._pendingPullIntos.length>0&&He(e),ee(t,new Uint8Array(i,o,a),!1);else lr(t)?(ze(e,i,o,a),Ye(e)):ze(e,i,o,a);je(e)}}function Xe(e,r){var t=e._controlledReadableByteStream;"readable"===t._state&&(Be(e),Pe(e),Ve(e),Nt(t,r))}function Je(e,r){var t=e._queue.shift();e._queueTotalSize-=t.byteLength,Me(e);var n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);r._chunkSteps(n)}function Ke(e){if(null===e._byobRequest&&e._pendingPullIntos.length>0){var r=e._pendingPullIntos.peek(),t=new Uint8Array(r.buffer,r.byteOffset+r.bytesFilled,r.byteLength-r.bytesFilled),n=Object.create(qe.prototype);!function(e,r,t){e._associatedReadableByteStreamController=r,e._view=t}(n,e,t),e._byobRequest=n}return e._byobRequest}function Ze(e){var r=e._controlledReadableByteStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function $e(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream")}else{if(0===r)throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream");if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range")}t.buffer=_e(t.buffer),Ne(e,r)}function er(e,r){var t=e._pendingPullIntos.peek();if("closed"===e._controlledReadableByteStream._state){if(0!==r.byteLength)throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream")}else if(0===r.byteLength)throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream");if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.bufferByteLength!==r.buffer.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");if(t.bytesFilled+r.byteLength>t.byteLength)throw new RangeError("The region specified by view is larger than byobRequest");var n=r.byteLength;t.buffer=_e(r.buffer),Ne(e,n)}function rr(e,r,t,n,o,a,i){r._controlledReadableByteStream=e,r._pullAgain=!1,r._pulling=!1,r._byobRequest=null,r._queue=r._queueTotalSize=void 0,Pe(r),r._closeRequested=!1,r._started=!1,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,r._autoAllocateChunkSize=i,r._pendingPullIntos=new q,e._readableStreamController=r,v(m(t()),(function(){return r._started=!0,je(r),null}),(function(e){return Xe(r,e),null}))}function tr(e){return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(e," can only be used on a ReadableStreamBYOBRequest"))}function nr(e){return new TypeError("ReadableByteStreamController.prototype.".concat(e," can only be used on a ReadableByteStreamController"))}function or(e,r){if("byob"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamReaderMode"));return e}function ar(e){return new sr(e)}function ir(e,r){e._reader._readIntoRequests.push(r)}function ur(e){return e._reader._readIntoRequests.length}function lr(e){var r=e._reader;return void 0!==r&&!!cr(r)}Object.defineProperties(Ee.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},byobRequest:{enumerable:!0},desiredSize:{enumerable:!0}}),f(Ee.prototype.close,"close"),f(Ee.prototype.enqueue,"enqueue"),f(Ee.prototype.error,"error"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Ee.prototype,r.toStringTag,{value:"ReadableByteStreamController",configurable:!0});var sr=function(){function ReadableStreamBYOBReader(e){if(V(e,1,"ReadableStreamBYOBReader"),K(e,"First parameter"),xt(e))throw new TypeError("This stream has already been locked for exclusive reading by another reader");if(!Oe(e._readableStreamController))throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source");k(this,e),this._readIntoRequests=new q}return Object.defineProperty(ReadableStreamBYOBReader.prototype,"closed",{get:function(){return cr(this)?this._closedPromise:_(br("closed"))},enumerable:!1,configurable:!0}),ReadableStreamBYOBReader.prototype.cancel=function(e){return void 0===e&&(e=void 0),cr(this)?void 0===this._ownerReadableStream?_(I("cancel")):A(this,e):_(br("cancel"))},ReadableStreamBYOBReader.prototype.read=function(e,r){if(void 0===r&&(r={}),!cr(this))return _(br("read"));if(!ArrayBuffer.isView(e))return _(new TypeError("view must be an array buffer view"));if(0===e.byteLength)return _(new TypeError("view must have non-zero byteLength"));if(0===e.buffer.byteLength)return _(new TypeError("view's buffer must have non-zero byteLength"));if(ye(e.buffer))return _(new TypeError("view's buffer has been detached"));var t;try{t=function(e,r){var t;return Q(e,r),{min:J(null!==(t=null==e?void 0:e.min)&&void 0!==t?t:1,"".concat(r," has member 'min' that"))}}(r,"options")}catch(e){return _(e)}var n,o,a=t.min;if(0===a)return _(new TypeError("options.min must be greater than 0"));if(function(e){return Ce(e.constructor)}(e)){if(a>e.byteLength)return _(new RangeError("options.min must be less than or equal to view's byteLength"))}else if(a>e.length)return _(new RangeError("options.min must be less than or equal to view's length"));if(void 0===this._ownerReadableStream)return _(I("read from"));var i=h((function(e,r){n=e,o=r}));return fr(this,e,a,{_chunkSteps:function(e){return n({value:e,done:!1})},_closeSteps:function(e){return n({value:e,done:!0})},_errorSteps:function(e){return o(e)}}),i},ReadableStreamBYOBReader.prototype.releaseLock=function(){if(!cr(this))throw br("releaseLock");void 0!==this._ownerReadableStream&&function(e){z(e);var r=new TypeError("Reader was released");dr(e,r)}(this)},ReadableStreamBYOBReader}();function cr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")&&e instanceof sr)}function fr(e,r,t,n){var o=e._ownerReadableStream;o._disturbed=!0,"errored"===o._state?n._errorSteps(o._storedError):Qe(o._readableStreamController,r,t,n)}function dr(e,r){var t=e._readIntoRequests;e._readIntoRequests=new q,t.forEach((function(e){e._errorSteps(r)}))}function br(e){return new TypeError("ReadableStreamBYOBReader.prototype.".concat(e," can only be used on a ReadableStreamBYOBReader"))}function pr(e,r){var t=e.highWaterMark;if(void 0===t)return r;if(pe(t)||t<0)throw new RangeError("Invalid highWaterMark");return t}function hr(e){var r=e.size;return r||function(){return 1}}function mr(e,r){Q(e,r);var t=null==e?void 0:e.highWaterMark,n=null==e?void 0:e.size;return{highWaterMark:void 0===t?void 0:G(t),size:void 0===n?void 0:_r(n,"".concat(r," has member 'size' that"))}}function _r(e,r){return N(e,r),function(r){return G(e(r))}}function yr(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function vr(e,r,t){return N(e,t),function(){return C(e,r,[])}}function gr(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function Sr(e,r,t){return N(e,t),function(t,n){return C(e,r,[t,n])}}function wr(e,r){if(!qr(e))throw new TypeError("".concat(r," is not a WritableStream."))}Object.defineProperties(sr.prototype,{cancel:{enumerable:!0},read:{enumerable:!0},releaseLock:{enumerable:!0},closed:{enumerable:!0}}),f(sr.prototype.cancel,"cancel"),f(sr.prototype.read,"read"),f(sr.prototype.releaseLock,"releaseLock"),"symbol"==typeof r.toStringTag&&Object.defineProperty(sr.prototype,r.toStringTag,{value:"ReadableStreamBYOBReader",configurable:!0});var Rr="function"==typeof AbortController;var Tr=function(){function WritableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:H(e,"First parameter");var t=mr(r,"Second parameter"),n=function(e,r){Q(e,r);var t=null==e?void 0:e.abort,n=null==e?void 0:e.close,o=null==e?void 0:e.start,a=null==e?void 0:e.type,i=null==e?void 0:e.write;return{abort:void 0===t?void 0:yr(t,e,"".concat(r," has member 'abort' that")),close:void 0===n?void 0:vr(n,e,"".concat(r," has member 'close' that")),start:void 0===o?void 0:gr(o,e,"".concat(r," has member 'start' that")),write:void 0===i?void 0:Sr(i,e,"".concat(r," has member 'write' that")),type:a}}(e,"First parameter");if(Cr(this),void 0!==n.type)throw new RangeError("Invalid type is specified");var o=hr(t);!function(e,r,t,n){var o,a,i,u,l=Object.create(Hr.prototype);o=void 0!==r.start?function(){return r.start(l)}:function(){};a=void 0!==r.write?function(e){return r.write(e,l)}:function(){return m(void 0)};i=void 0!==r.close?function(){return r.close()}:function(){return m(void 0)};u=void 0!==r.abort?function(e){return r.abort(e)}:function(){return m(void 0)};Ur(e,l,o,a,i,u,t,n)}(this,n,pr(t,1),o)}return Object.defineProperty(WritableStream.prototype,"locked",{get:function(){if(!qr(this))throw et("locked");return Er(this)},enumerable:!1,configurable:!0}),WritableStream.prototype.abort=function(e){return void 0===e&&(e=void 0),qr(this)?Er(this)?_(new TypeError("Cannot abort a stream that already has a writer")):Or(this,e):_(et("abort"))},WritableStream.prototype.close=function(){return qr(this)?Er(this)?_(new TypeError("Cannot close a stream that already has a writer")):Ar(this)?_(new TypeError("Cannot close an already-closing stream")):Wr(this):_(et("close"))},WritableStream.prototype.getWriter=function(){if(!qr(this))throw et("getWriter");return Pr(this)},WritableStream}();function Pr(e){return new Dr(e)}function Cr(e){e._state="writable",e._storedError=void 0,e._writer=void 0,e._writableStreamController=void 0,e._writeRequests=new q,e._inFlightWriteRequest=void 0,e._closeRequest=void 0,e._inFlightCloseRequest=void 0,e._pendingAbortRequest=void 0,e._backpressure=!1}function qr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")&&e instanceof Tr)}function Er(e){return void 0!==e._writer}function Or(e,r){var t;if("closed"===e._state||"errored"===e._state)return m(void 0);e._writableStreamController._abortReason=r,null===(t=e._writableStreamController._abortController)||void 0===t||t.abort(r);var n=e._state;if("closed"===n||"errored"===n)return m(void 0);if(void 0!==e._pendingAbortRequest)return e._pendingAbortRequest._promise;var o=!1;"erroring"===n&&(o=!0,r=void 0);var a=h((function(t,n){e._pendingAbortRequest={_promise:void 0,_resolve:t,_reject:n,_reason:r,_wasAlreadyErroring:o}}));return e._pendingAbortRequest._promise=a,o||Br(e,r),a}function Wr(e){var r=e._state;if("closed"===r||"errored"===r)return _(new TypeError("The stream (in ".concat(r," state) is not in the writable state and cannot be closed")));var t,n=h((function(r,t){var n={_resolve:r,_reject:t};e._closeRequest=n})),o=e._writer;return void 0!==o&&e._backpressure&&"writable"===r&&dt(o),Te(t=e._writableStreamController,Nr,0),Jr(t),n}function jr(e,r){"writable"!==e._state?kr(e):Br(e,r)}function Br(e,r){var t=e._writableStreamController;e._state="erroring",e._storedError=r;var n=e._writer;void 0!==n&&xr(n,r),!function(e){if(void 0===e._inFlightWriteRequest&&void 0===e._inFlightCloseRequest)return!1;return!0}(e)&&t._started&&kr(e)}function kr(e){e._state="errored",e._writableStreamController[O]();var r=e._storedError;if(e._writeRequests.forEach((function(e){e._reject(r)})),e._writeRequests=new q,void 0!==e._pendingAbortRequest){var t=e._pendingAbortRequest;if(e._pendingAbortRequest=void 0,t._wasAlreadyErroring)return t._reject(r),void zr(e);v(e._writableStreamController[E](t._reason),(function(){return t._resolve(),zr(e),null}),(function(r){return t._reject(r),zr(e),null}))}else zr(e)}function Ar(e){return void 0!==e._closeRequest||void 0!==e._inFlightCloseRequest}function zr(e){void 0!==e._closeRequest&&(e._closeRequest._reject(e._storedError),e._closeRequest=void 0);var r=e._writer;void 0!==r&&it(r,e._storedError)}function Ir(e,r){var t=e._writer;void 0!==t&&r!==e._backpressure&&(r?function(e){lt(e)}(t):dt(t)),e._backpressure=r}Object.defineProperties(Tr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},getWriter:{enumerable:!0},locked:{enumerable:!0}}),f(Tr.prototype.abort,"abort"),f(Tr.prototype.close,"close"),f(Tr.prototype.getWriter,"getWriter"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Tr.prototype,r.toStringTag,{value:"WritableStream",configurable:!0});var Dr=function(){function WritableStreamDefaultWriter(e){if(V(e,1,"WritableStreamDefaultWriter"),wr(e,"First parameter"),Er(e))throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=e,e._writer=this;var r,t=e._state;if("writable"===t)!Ar(e)&&e._backpressure?lt(this):ct(this),ot(this);else if("erroring"===t)st(this,e._storedError),ot(this);else if("closed"===t)ct(this),ot(r=this),ut(r);else{var n=e._storedError;st(this,n),at(this,n)}}return Object.defineProperty(WritableStreamDefaultWriter.prototype,"closed",{get:function(){return Lr(this)?this._closedPromise:_(tt("closed"))},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"desiredSize",{get:function(){if(!Lr(this))throw tt("desiredSize");if(void 0===this._ownerWritableStream)throw nt("desiredSize");return function(e){var r=e._ownerWritableStream,t=r._state;if("errored"===t||"erroring"===t)return null;if("closed"===t)return 0;return Xr(r._writableStreamController)}(this)},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultWriter.prototype,"ready",{get:function(){return Lr(this)?this._readyPromise:_(tt("ready"))},enumerable:!1,configurable:!0}),WritableStreamDefaultWriter.prototype.abort=function(e){return void 0===e&&(e=void 0),Lr(this)?void 0===this._ownerWritableStream?_(nt("abort")):function(e,r){return Or(e._ownerWritableStream,r)}(this,e):_(tt("abort"))},WritableStreamDefaultWriter.prototype.close=function(){if(!Lr(this))return _(tt("close"));var e=this._ownerWritableStream;return void 0===e?_(nt("close")):Ar(e)?_(new TypeError("Cannot close an already-closing stream")):Fr(this)},WritableStreamDefaultWriter.prototype.releaseLock=function(){if(!Lr(this))throw tt("releaseLock");void 0!==this._ownerWritableStream&&Yr(this)},WritableStreamDefaultWriter.prototype.write=function(e){return void 0===e&&(e=void 0),Lr(this)?void 0===this._ownerWritableStream?_(nt("write to")):Qr(this,e):_(tt("write"))},WritableStreamDefaultWriter}();function Lr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")&&e instanceof Dr)}function Fr(e){return Wr(e._ownerWritableStream)}function Mr(e,r){"pending"===e._closedPromiseState?it(e,r):function(e,r){at(e,r)}(e,r)}function xr(e,r){"pending"===e._readyPromiseState?ft(e,r):function(e,r){st(e,r)}(e,r)}function Yr(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness");xr(e,t),Mr(e,t),r._writer=void 0,e._ownerWritableStream=void 0}function Qr(e,r){var t=e._ownerWritableStream,n=t._writableStreamController,o=function(e,r){try{return e._strategySizeAlgorithm(r)}catch(r){return Kr(e,r),1}}(n,r);if(t!==e._ownerWritableStream)return _(nt("write to"));var a=t._state;if("errored"===a)return _(t._storedError);if(Ar(t)||"closed"===a)return _(new TypeError("The stream is closing or closed and cannot be written to"));if("erroring"===a)return _(t._storedError);var i=function(e){return h((function(r,t){var n={_resolve:r,_reject:t};e._writeRequests.push(n)}))}(t);return function(e,r,t){try{Te(e,r,t)}catch(r){return void Kr(e,r)}var n=e._controlledWritableStream;if(!Ar(n)&&"writable"===n._state){Ir(n,Zr(e))}Jr(e)}(n,r,o),i}Object.defineProperties(Dr.prototype,{abort:{enumerable:!0},close:{enumerable:!0},releaseLock:{enumerable:!0},write:{enumerable:!0},closed:{enumerable:!0},desiredSize:{enumerable:!0},ready:{enumerable:!0}}),f(Dr.prototype.abort,"abort"),f(Dr.prototype.close,"close"),f(Dr.prototype.releaseLock,"releaseLock"),f(Dr.prototype.write,"write"),"symbol"==typeof r.toStringTag&&Object.defineProperty(Dr.prototype,r.toStringTag,{value:"WritableStreamDefaultWriter",configurable:!0});var Nr={},Hr=function(){function WritableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(WritableStreamDefaultController.prototype,"abortReason",{get:function(){if(!Vr(this))throw rt("abortReason");return this._abortReason},enumerable:!1,configurable:!0}),Object.defineProperty(WritableStreamDefaultController.prototype,"signal",{get:function(){if(!Vr(this))throw rt("signal");if(void 0===this._abortController)throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported");return this._abortController.signal},enumerable:!1,configurable:!0}),WritableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!Vr(this))throw rt("error");"writable"===this._controlledWritableStream._state&&$r(this,e)},WritableStreamDefaultController.prototype[E]=function(e){var r=this._abortAlgorithm(e);return Gr(this),r},WritableStreamDefaultController.prototype[O]=function(){Pe(this)},WritableStreamDefaultController}();function Vr(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledWritableStream")&&e instanceof Hr)}function Ur(e,r,t,n,o,a,i,u){r._controlledWritableStream=e,e._writableStreamController=r,r._queue=void 0,r._queueTotalSize=void 0,Pe(r),r._abortReason=void 0,r._abortController=function(){if(Rr)return new AbortController}(),r._started=!1,r._strategySizeAlgorithm=u,r._strategyHWM=i,r._writeAlgorithm=n,r._closeAlgorithm=o,r._abortAlgorithm=a;var l=Zr(r);Ir(e,l),v(m(t()),(function(){return r._started=!0,Jr(r),null}),(function(t){return r._started=!0,jr(e,t),null}))}function Gr(e){e._writeAlgorithm=void 0,e._closeAlgorithm=void 0,e._abortAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function Xr(e){return e._strategyHWM-e._queueTotalSize}function Jr(e){var r=e._controlledWritableStream;if(e._started&&void 0===r._inFlightWriteRequest)if("erroring"!==r._state){if(0!==e._queue.length){var t=e._queue.peek().value;t===Nr?function(e){var r=e._controlledWritableStream;(function(e){e._inFlightCloseRequest=e._closeRequest,e._closeRequest=void 0})(r),Re(e);var t=e._closeAlgorithm();Gr(e),v(t,(function(){return function(e){e._inFlightCloseRequest._resolve(void 0),e._inFlightCloseRequest=void 0,"erroring"===e._state&&(e._storedError=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)),e._state="closed";var r=e._writer;void 0!==r&&ut(r)}(r),null}),(function(e){return function(e,r){e._inFlightCloseRequest._reject(r),e._inFlightCloseRequest=void 0,void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._reject(r),e._pendingAbortRequest=void 0),jr(e,r)}(r,e),null}))}(e):function(e,r){var t=e._controlledWritableStream;!function(e){e._inFlightWriteRequest=e._writeRequests.shift()}(t);var n=e._writeAlgorithm(r);v(n,(function(){!function(e){e._inFlightWriteRequest._resolve(void 0),e._inFlightWriteRequest=void 0}(t);var r=t._state;if(Re(e),!Ar(t)&&"writable"===r){var n=Zr(e);Ir(t,n)}return Jr(e),null}),(function(r){return"writable"===t._state&&Gr(e),function(e,r){e._inFlightWriteRequest._reject(r),e._inFlightWriteRequest=void 0,jr(e,r)}(t,r),null}))}(e,t)}}else kr(r)}function Kr(e,r){"writable"===e._controlledWritableStream._state&&$r(e,r)}function Zr(e){return Xr(e)<=0}function $r(e,r){var t=e._controlledWritableStream;Gr(e),Br(t,r)}function et(e){return new TypeError("WritableStream.prototype.".concat(e," can only be used on a WritableStream"))}function rt(e){return new TypeError("WritableStreamDefaultController.prototype.".concat(e," can only be used on a WritableStreamDefaultController"))}function tt(e){return new TypeError("WritableStreamDefaultWriter.prototype.".concat(e," can only be used on a WritableStreamDefaultWriter"))}function nt(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function ot(e){e._closedPromise=h((function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t,e._closedPromiseState="pending"}))}function at(e,r){ot(e),it(e,r)}function it(e,r){void 0!==e._closedPromise_reject&&(R(e._closedPromise),e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="rejected")}function ut(e){void 0!==e._closedPromise_resolve&&(e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0,e._closedPromiseState="resolved")}function lt(e){e._readyPromise=h((function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})),e._readyPromiseState="pending"}function st(e,r){lt(e),ft(e,r)}function ct(e){lt(e),dt(e)}function ft(e,r){void 0!==e._readyPromise_reject&&(R(e._readyPromise),e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="rejected")}function dt(e){void 0!==e._readyPromise_resolve&&(e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0,e._readyPromiseState="fulfilled")}Object.defineProperties(Hr.prototype,{abortReason:{enumerable:!0},signal:{enumerable:!0},error:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Hr.prototype,r.toStringTag,{value:"WritableStreamDefaultController",configurable:!0});var bt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var pt,ht=(function(e){if("function"!=typeof e&&"object"!=typeof e)return!1;if("DOMException"!==e.name)return!1;try{return new e,!0}catch(e){return!1}}(pt=null==bt?void 0:bt.DOMException)?pt:void 0)||function(){var e=function(e,r){this.message=e||"",this.name=r||"Error",Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)};return f(e,"DOMException"),e.prototype=Object.create(Error.prototype),Object.defineProperty(e.prototype,"constructor",{value:e,writable:!0,configurable:!0}),e}();function mt(e,r,t,n,o,a){var i=Z(e),u=Pr(r);e._disturbed=!0;var s=!1,c=m(void 0);return h((function(f,d){var b,p,w,T;if(void 0!==a){if(b=function(){var t=void 0!==a.reason?a.reason:new ht("Aborted","AbortError"),i=[];n||i.push((function(){return"writable"===r._state?Or(r,t):m(void 0)})),o||i.push((function(){return"readable"===e._state?Yt(e,t):m(void 0)})),E((function(){return Promise.all(i.map((function(e){return e()})))}),!0,t)},a.aborted)return void b();a.addEventListener("abort",b)}if(q(e,i._closedPromise,(function(e){return n?O(!0,e):E((function(){return Or(r,e)}),!0,e),null})),q(r,u._closedPromise,(function(r){return o?O(!0,r):E((function(){return Yt(e,r)}),!0,r),null})),p=e,w=i._closedPromise,T=function(){return t?O():E((function(){return function(e){var r=e._ownerWritableStream,t=r._state;return Ar(r)||"closed"===t?m(void 0):"errored"===t?_(r._storedError):Fr(e)}(u)})),null},"closed"===p._state?T():g(w,T),Ar(r)||"closed"===r._state){var P=new TypeError("the destination writable stream closed before all data could be piped to it");o?O(!0,P):E((function(){return Yt(e,P)}),!0,P)}function C(){var e=c;return y(c,(function(){return e!==c?C():void 0}))}function q(e,r,t){"errored"===e._state?t(e._storedError):S(r,t)}function E(e,t,n){function o(){return v(e(),(function(){return W(t,n)}),(function(e){return W(!0,e)})),null}s||(s=!0,"writable"!==r._state||Ar(r)?o():g(C(),o))}function O(e,t){s||(s=!0,"writable"!==r._state||Ar(r)?W(e,t):g(C(),(function(){return W(e,t)})))}function W(e,r){return Yr(u),z(i),void 0!==a&&a.removeEventListener("abort",b),e?d(r):f(void 0),null}R(h((function(e,r){!function t(n){n?e():y(s?m(!0):y(u._readyPromise,(function(){return h((function(e,r){ue(i,{_chunkSteps:function(r){c=y(Qr(u,r),void 0,l),e(!1)},_closeSteps:function(){return e(!0)},_errorSteps:r})}))})),t,r)}(!1)})))}))}var _t=function(){function ReadableStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(ReadableStreamDefaultController.prototype,"desiredSize",{get:function(){if(!yt(this))throw Et("desiredSize");return Pt(this)},enumerable:!1,configurable:!0}),ReadableStreamDefaultController.prototype.close=function(){if(!yt(this))throw Et("close");if(!Ct(this))throw new TypeError("The stream is not in a state that permits close");wt(this)},ReadableStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!yt(this))throw Et("enqueue");if(!Ct(this))throw new TypeError("The stream is not in a state that permits enqueue");return Rt(this,e)},ReadableStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!yt(this))throw Et("error");Tt(this,e)},ReadableStreamDefaultController.prototype[W]=function(e){Pe(this);var r=this._cancelAlgorithm(e);return St(this),r},ReadableStreamDefaultController.prototype[j]=function(e){var r=this._controlledReadableStream;if(this._queue.length>0){var t=Re(this);this._closeRequested&&0===this._queue.length?(St(this),Qt(r)):vt(this),e._chunkSteps(t)}else $(r,e),vt(this)},ReadableStreamDefaultController.prototype[B]=function(){},ReadableStreamDefaultController}();function yt(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledReadableStream")&&e instanceof _t)}function vt(e){gt(e)&&(e._pulling?e._pullAgain=!0:(e._pulling=!0,v(e._pullAlgorithm(),(function(){return e._pulling=!1,e._pullAgain&&(e._pullAgain=!1,vt(e)),null}),(function(r){return Tt(e,r),null}))))}function gt(e){var r=e._controlledReadableStream;return!!Ct(e)&&(!!e._started&&(!!(xt(r)&&re(r)>0)||Pt(e)>0))}function St(e){e._pullAlgorithm=void 0,e._cancelAlgorithm=void 0,e._strategySizeAlgorithm=void 0}function wt(e){if(Ct(e)){var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&(St(e),Qt(r))}}function Rt(e,r){if(Ct(e)){var t=e._controlledReadableStream;if(xt(t)&&re(t)>0)ee(t,r,!1);else{var n=void 0;try{n=e._strategySizeAlgorithm(r)}catch(r){throw Tt(e,r),r}try{Te(e,r,n)}catch(r){throw Tt(e,r),r}}vt(e)}}function Tt(e,r){var t=e._controlledReadableStream;"readable"===t._state&&(Pe(e),St(e),Nt(t,r))}function Pt(e){var r=e._controlledReadableStream._state;return"errored"===r?null:"closed"===r?0:e._strategyHWM-e._queueTotalSize}function Ct(e){var r=e._controlledReadableStream._state;return!e._closeRequested&&"readable"===r}function qt(e,r,t,n,o,a,i){r._controlledReadableStream=e,r._queue=void 0,r._queueTotalSize=void 0,Pe(r),r._started=!1,r._closeRequested=!1,r._pullAgain=!1,r._pulling=!1,r._strategySizeAlgorithm=i,r._strategyHWM=a,r._pullAlgorithm=n,r._cancelAlgorithm=o,e._readableStreamController=r,v(m(t()),(function(){return r._started=!0,vt(r),null}),(function(e){return Tt(r,e),null}))}function Et(e){return new TypeError("ReadableStreamDefaultController.prototype.".concat(e," can only be used on a ReadableStreamDefaultController"))}function Ot(e,r){return Oe(e._readableStreamController)?function(e){var r,t,n,o,a,i=Z(e),u=!1,l=!1,s=!1,c=!1,f=!1,d=h((function(e){a=e}));function b(e){S(e._closedPromise,(function(r){return e!==i||(Xe(n._readableStreamController,r),Xe(o._readableStreamController,r),c&&f||a(void 0)),null}))}function p(){cr(i)&&(z(i),b(i=Z(e))),ue(i,{_chunkSteps:function(r){T((function(){l=!1,s=!1;var t=r,i=r;if(!c&&!f)try{i=we(r)}catch(r){return Xe(n._readableStreamController,r),Xe(o._readableStreamController,r),void a(Yt(e,r))}c||Ge(n._readableStreamController,t),f||Ge(o._readableStreamController,i),u=!1,l?y():s&&v()}))},_closeSteps:function(){u=!1,c||Ue(n._readableStreamController),f||Ue(o._readableStreamController),n._readableStreamController._pendingPullIntos.length>0&&$e(n._readableStreamController,0),o._readableStreamController._pendingPullIntos.length>0&&$e(o._readableStreamController,0),c&&f||a(void 0)},_errorSteps:function(){u=!1}})}function _(r,t){ie(i)&&(z(i),b(i=ar(e)));var d=t?o:n,p=t?n:o;fr(i,r,1,{_chunkSteps:function(r){T((function(){l=!1,s=!1;var n=t?f:c;if(t?c:f)n||er(d._readableStreamController,r);else{var o=void 0;try{o=we(r)}catch(r){return Xe(d._readableStreamController,r),Xe(p._readableStreamController,r),void a(Yt(e,r))}n||er(d._readableStreamController,r),Ge(p._readableStreamController,o)}u=!1,l?y():s&&v()}))},_closeSteps:function(e){u=!1;var r=t?f:c,n=t?c:f;r||Ue(d._readableStreamController),n||Ue(p._readableStreamController),void 0!==e&&(r||er(d._readableStreamController,e),!n&&p._readableStreamController._pendingPullIntos.length>0&&$e(p._readableStreamController,0)),r&&n||a(void 0)},_errorSteps:function(){u=!1}})}function y(){if(u)return l=!0,m(void 0);u=!0;var e=Ke(n._readableStreamController);return null===e?p():_(e._view,!1),m(void 0)}function v(){if(u)return s=!0,m(void 0);u=!0;var e=Ke(o._readableStreamController);return null===e?p():_(e._view,!0),m(void 0)}function g(n){if(c=!0,r=n,f){var o=he([r,t]),i=Yt(e,o);a(i)}return d}function w(n){if(f=!0,t=n,c){var o=he([r,t]),i=Yt(e,o);a(i)}return d}function R(){}return n=Lt(R,y,g),o=Lt(R,v,w),b(i),[n,o]}(e):function(e,r){var t,n,o,a,i,u=Z(e),l=!1,s=!1,c=!1,f=!1,d=h((function(e){i=e}));function b(){return l?(s=!0,m(void 0)):(l=!0,ue(u,{_chunkSteps:function(e){T((function(){s=!1;var r=e,t=e;c||Rt(o._readableStreamController,r),f||Rt(a._readableStreamController,t),l=!1,s&&b()}))},_closeSteps:function(){l=!1,c||wt(o._readableStreamController),f||wt(a._readableStreamController),c&&f||i(void 0)},_errorSteps:function(){l=!1}}),m(void 0))}function p(r){if(c=!0,t=r,f){var o=he([t,n]),a=Yt(e,o);i(a)}return d}function _(r){if(f=!0,n=r,c){var o=he([t,n]),a=Yt(e,o);i(a)}return d}function y(){}return o=Dt(y,b,p),a=Dt(y,b,_),S(u._closedPromise,(function(e){return Tt(o._readableStreamController,e),Tt(a._readableStreamController,e),c&&f||i(void 0),null})),[o,a]}(e)}function Wt(e){return s(r=e)&&void 0!==r.getReader?function(e){var r;function t(){var t;try{t=e.read()}catch(e){return _(e)}return w(t,(function(e){if(!s(e))throw new TypeError("The promise returned by the reader.read() method must fulfill with an object");if(e.done)wt(r._readableStreamController);else{var t=e.value;Rt(r._readableStreamController,t)}}))}function n(r){try{return m(e.cancel(r))}catch(e){return _(e)}}return r=Dt(l,t,n,0),r}(e.getReader()):function(e){var r,t=Se(e,"async");function n(){var e;try{e=function(e){var r=P(e.nextMethod,e.iterator,[]);if(!s(r))throw new TypeError("The iterator.next() method must return an object");return r}(t)}catch(e){return _(e)}return w(m(e),(function(e){if(!s(e))throw new TypeError("The promise returned by the iterator.next() method must fulfill with an object");var t=function(e){return Boolean(e.done)}(e);if(t)wt(r._readableStreamController);else{var n=function(e){return e.value}(e);Rt(r._readableStreamController,n)}}))}function o(e){var r,n,o=t.iterator;try{r=ge(o,"return")}catch(e){return _(e)}if(void 0===r)return m(void 0);try{n=P(r,o,[e])}catch(e){return _(e)}return w(m(n),(function(e){if(!s(e))throw new TypeError("The promise returned by the iterator.return() method must fulfill with an object")}))}return r=Dt(l,n,o,0),r}(e);var r}function jt(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function Bt(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function kt(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function At(e,r){if("bytes"!==(e="".concat(e)))throw new TypeError("".concat(r," '").concat(e,"' is not a valid enumeration value for ReadableStreamType"));return e}function zt(e,r){Q(e,r);var t=null==e?void 0:e.preventAbort,n=null==e?void 0:e.preventCancel,o=null==e?void 0:e.preventClose,a=null==e?void 0:e.signal;return void 0!==a&&function(e,r){if(!function(e){if("object"!=typeof e||null===e)return!1;try{return"boolean"==typeof e.aborted}catch(e){return!1}}(e))throw new TypeError("".concat(r," is not an AbortSignal."))}(a,"".concat(r," has member 'signal' that")),{preventAbort:Boolean(t),preventCancel:Boolean(n),preventClose:Boolean(o),signal:a}}Object.defineProperties(_t.prototype,{close:{enumerable:!0},enqueue:{enumerable:!0},error:{enumerable:!0},desiredSize:{enumerable:!0}}),f(_t.prototype.close,"close"),f(_t.prototype.enqueue,"enqueue"),f(_t.prototype.error,"error"),"symbol"==typeof r.toStringTag&&Object.defineProperty(_t.prototype,r.toStringTag,{value:"ReadableStreamDefaultController",configurable:!0});var It=function(){function ReadableStream(e,r){void 0===e&&(e={}),void 0===r&&(r={}),void 0===e?e=null:H(e,"First parameter");var t=mr(r,"Second parameter"),n=function(e,r){Q(e,r);var t=e,n=null==t?void 0:t.autoAllocateChunkSize,o=null==t?void 0:t.cancel,a=null==t?void 0:t.pull,i=null==t?void 0:t.start,u=null==t?void 0:t.type;return{autoAllocateChunkSize:void 0===n?void 0:J(n,"".concat(r," has member 'autoAllocateChunkSize' that")),cancel:void 0===o?void 0:jt(o,t,"".concat(r," has member 'cancel' that")),pull:void 0===a?void 0:Bt(a,t,"".concat(r," has member 'pull' that")),start:void 0===i?void 0:kt(i,t,"".concat(r," has member 'start' that")),type:void 0===u?void 0:At(u,"".concat(r," has member 'type' that"))}}(e,"First parameter");if(Ft(this),"bytes"===n.type){if(void 0!==t.size)throw new RangeError("The strategy for a byte stream cannot have a size function");!function(e,r,t){var n,o,a,i=Object.create(Ee.prototype);n=void 0!==r.start?function(){return r.start(i)}:function(){},o=void 0!==r.pull?function(){return r.pull(i)}:function(){return m(void 0)},a=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)};var u=r.autoAllocateChunkSize;if(0===u)throw new TypeError("autoAllocateChunkSize must be greater than 0");rr(e,i,n,o,a,t,u)}(this,n,pr(t,0))}else{var o=hr(t);!function(e,r,t,n){var o,a,i,u=Object.create(_t.prototype);o=void 0!==r.start?function(){return r.start(u)}:function(){},a=void 0!==r.pull?function(){return r.pull(u)}:function(){return m(void 0)},i=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)},qt(e,u,o,a,i,t,n)}(this,n,pr(t,1),o)}}return Object.defineProperty(ReadableStream.prototype,"locked",{get:function(){if(!Mt(this))throw Ht("locked");return xt(this)},enumerable:!1,configurable:!0}),ReadableStream.prototype.cancel=function(e){return void 0===e&&(e=void 0),Mt(this)?xt(this)?_(new TypeError("Cannot cancel a stream that already has a reader")):Yt(this,e):_(Ht("cancel"))},ReadableStream.prototype.getReader=function(e){if(void 0===e&&(e=void 0),!Mt(this))throw Ht("getReader");return void 0===function(e,r){Q(e,r);var t=null==e?void 0:e.mode;return{mode:void 0===t?void 0:or(t,"".concat(r," has member 'mode' that"))}}(e,"First parameter").mode?Z(this):ar(this)},ReadableStream.prototype.pipeThrough=function(e,r){if(void 0===r&&(r={}),!Mt(this))throw Ht("pipeThrough");V(e,1,"pipeThrough");var t=function(e,r){Q(e,r);var t=null==e?void 0:e.readable;U(t,"readable","ReadableWritablePair"),K(t,"".concat(r," has member 'readable' that"));var n=null==e?void 0:e.writable;return U(n,"writable","ReadableWritablePair"),wr(n,"".concat(r," has member 'writable' that")),{readable:t,writable:n}}(e,"First parameter"),n=zt(r,"Second parameter");if(xt(this))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream");if(Er(t.writable))throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream");return R(mt(this,t.writable,n.preventClose,n.preventAbort,n.preventCancel,n.signal)),t.readable},ReadableStream.prototype.pipeTo=function(e,r){if(void 0===r&&(r={}),!Mt(this))return _(Ht("pipeTo"));if(void 0===e)return _("Parameter 1 is required in 'pipeTo'.");if(!qr(e))return _(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));var t;try{t=zt(r,"Second parameter")}catch(e){return _(e)}return xt(this)?_(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")):Er(e)?_(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")):mt(this,e,t.preventClose,t.preventAbort,t.preventCancel,t.signal)},ReadableStream.prototype.tee=function(){if(!Mt(this))throw Ht("tee");return he(Ot(this))},ReadableStream.prototype.values=function(e){if(void 0===e&&(e=void 0),!Mt(this))throw Ht("values");var r,t,n,o,a,i=function(e,r){Q(e,r);var t=null==e?void 0:e.preventCancel;return{preventCancel:Boolean(t)}}(e,"First parameter");return r=this,t=i.preventCancel,n=Z(r),o=new ce(n,t),(a=Object.create(fe))._asyncIteratorImpl=o,a},ReadableStream.from=function(e){return Wt(e)},ReadableStream}();function Dt(e,r,t,n,o){void 0===n&&(n=1),void 0===o&&(o=function(){return 1});var a=Object.create(It.prototype);return Ft(a),qt(a,Object.create(_t.prototype),e,r,t,n,o),a}function Lt(e,r,t){var n=Object.create(It.prototype);return Ft(n),rr(n,Object.create(Ee.prototype),e,r,t,0,void 0),n}function Ft(e){e._state="readable",e._reader=void 0,e._storedError=void 0,e._disturbed=!1}function Mt(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")&&e instanceof It)}function xt(e){return void 0!==e._reader}function Yt(e,r){if(e._disturbed=!0,"closed"===e._state)return m(void 0);if("errored"===e._state)return _(e._storedError);Qt(e);var t=e._reader;if(void 0!==t&&cr(t)){var n=t._readIntoRequests;t._readIntoRequests=new q,n.forEach((function(e){e._closeSteps(void 0)}))}return w(e._readableStreamController[W](r),l)}function Qt(e){e._state="closed";var r=e._reader;if(void 0!==r&&(M(r),ie(r))){var t=r._readRequests;r._readRequests=new q,t.forEach((function(e){e._closeSteps()}))}}function Nt(e,r){e._state="errored",e._storedError=r;var t=e._reader;void 0!==t&&(F(t,r),ie(t)?le(t,r):dr(t,r))}function Ht(e){return new TypeError("ReadableStream.prototype.".concat(e," can only be used on a ReadableStream"))}function Vt(e,r){Q(e,r);var t=null==e?void 0:e.highWaterMark;return U(t,"highWaterMark","QueuingStrategyInit"),{highWaterMark:G(t)}}Object.defineProperties(It,{from:{enumerable:!0}}),Object.defineProperties(It.prototype,{cancel:{enumerable:!0},getReader:{enumerable:!0},pipeThrough:{enumerable:!0},pipeTo:{enumerable:!0},tee:{enumerable:!0},values:{enumerable:!0},locked:{enumerable:!0}}),f(It.from,"from"),f(It.prototype.cancel,"cancel"),f(It.prototype.getReader,"getReader"),f(It.prototype.pipeThrough,"pipeThrough"),f(It.prototype.pipeTo,"pipeTo"),f(It.prototype.tee,"tee"),f(It.prototype.values,"values"),"symbol"==typeof r.toStringTag&&Object.defineProperty(It.prototype,r.toStringTag,{value:"ReadableStream",configurable:!0}),"symbol"==typeof r.asyncIterator&&Object.defineProperty(It.prototype,r.asyncIterator,{value:It.prototype.values,writable:!0,configurable:!0});var Ut=function(e){return e.byteLength};f(Ut,"size");var Gt=function(){function ByteLengthQueuingStrategy(e){V(e,1,"ByteLengthQueuingStrategy"),e=Vt(e,"First parameter"),this._byteLengthQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(ByteLengthQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!Jt(this))throw Xt("highWaterMark");return this._byteLengthQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(ByteLengthQueuingStrategy.prototype,"size",{get:function(){if(!Jt(this))throw Xt("size");return Ut},enumerable:!1,configurable:!0}),ByteLengthQueuingStrategy}();function Xt(e){return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(e," can only be used on a ByteLengthQueuingStrategy"))}function Jt(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_byteLengthQueuingStrategyHighWaterMark")&&e instanceof Gt)}Object.defineProperties(Gt.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Gt.prototype,r.toStringTag,{value:"ByteLengthQueuingStrategy",configurable:!0});var Kt=function(){return 1};f(Kt,"size");var Zt=function(){function CountQueuingStrategy(e){V(e,1,"CountQueuingStrategy"),e=Vt(e,"First parameter"),this._countQueuingStrategyHighWaterMark=e.highWaterMark}return Object.defineProperty(CountQueuingStrategy.prototype,"highWaterMark",{get:function(){if(!en(this))throw $t("highWaterMark");return this._countQueuingStrategyHighWaterMark},enumerable:!1,configurable:!0}),Object.defineProperty(CountQueuingStrategy.prototype,"size",{get:function(){if(!en(this))throw $t("size");return Kt},enumerable:!1,configurable:!0}),CountQueuingStrategy}();function $t(e){return new TypeError("CountQueuingStrategy.prototype.".concat(e," can only be used on a CountQueuingStrategy"))}function en(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_countQueuingStrategyHighWaterMark")&&e instanceof Zt)}function rn(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}function tn(e,r,t){return N(e,t),function(t){return P(e,r,[t])}}function nn(e,r,t){return N(e,t),function(t,n){return C(e,r,[t,n])}}function on(e,r,t){return N(e,t),function(t){return C(e,r,[t])}}Object.defineProperties(Zt.prototype,{highWaterMark:{enumerable:!0},size:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(Zt.prototype,r.toStringTag,{value:"CountQueuingStrategy",configurable:!0});var an=function(){function TransformStream(e,r,t){void 0===e&&(e={}),void 0===r&&(r={}),void 0===t&&(t={}),void 0===e&&(e=null);var n=mr(r,"Second parameter"),o=mr(t,"Third parameter"),a=function(e,r){Q(e,r);var t=null==e?void 0:e.cancel,n=null==e?void 0:e.flush,o=null==e?void 0:e.readableType,a=null==e?void 0:e.start,i=null==e?void 0:e.transform,u=null==e?void 0:e.writableType;return{cancel:void 0===t?void 0:on(t,e,"".concat(r," has member 'cancel' that")),flush:void 0===n?void 0:rn(n,e,"".concat(r," has member 'flush' that")),readableType:o,start:void 0===a?void 0:tn(a,e,"".concat(r," has member 'start' that")),transform:void 0===i?void 0:nn(i,e,"".concat(r," has member 'transform' that")),writableType:u}}(e,"First parameter");if(void 0!==a.readableType)throw new RangeError("Invalid readableType specified");if(void 0!==a.writableType)throw new RangeError("Invalid writableType specified");var i,u=pr(o,0),l=hr(o),s=pr(n,1),c=hr(n);!function(e,r,t,n,o,a){function i(){return r}function u(r){return function(e,r){var t=e._transformStreamController;if(e._backpressure){return w(e._backpressureChangePromise,(function(){var n=e._writable;if("erroring"===n._state)throw n._storedError;return mn(t,r)}))}return mn(t,r)}(e,r)}function l(r){return function(e,r){var t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;var n=e._readable;t._finishPromise=h((function(e,r){t._finishPromise_resolve=e,t._finishPromise_reject=r}));var o=t._cancelAlgorithm(r);return pn(t),v(o,(function(){return"errored"===n._state?vn(t,n._storedError):(Tt(n._readableStreamController,r),yn(t)),null}),(function(e){return Tt(n._readableStreamController,e),vn(t,e),null})),t._finishPromise}(e,r)}function s(){return function(e){var r=e._transformStreamController;if(void 0!==r._finishPromise)return r._finishPromise;var t=e._readable;r._finishPromise=h((function(e,t){r._finishPromise_resolve=e,r._finishPromise_reject=t}));var n=r._flushAlgorithm();return pn(r),v(n,(function(){return"errored"===t._state?vn(r,t._storedError):(wt(t._readableStreamController),yn(r)),null}),(function(e){return Tt(t._readableStreamController,e),vn(r,e),null})),r._finishPromise}(e)}function c(){return function(e){return fn(e,!1),e._backpressureChangePromise}(e)}function f(r){return function(e,r){var t=e._transformStreamController;if(void 0!==t._finishPromise)return t._finishPromise;var n=e._writable;t._finishPromise=h((function(e,r){t._finishPromise_resolve=e,t._finishPromise_reject=r}));var o=t._cancelAlgorithm(r);return pn(t),v(o,(function(){return"errored"===n._state?vn(t,n._storedError):(Kr(n._writableStreamController,r),cn(e),yn(t)),null}),(function(r){return Kr(n._writableStreamController,r),cn(e),vn(t,r),null})),t._finishPromise}(e,r)}e._writable=function(e,r,t,n,o,a){void 0===o&&(o=1),void 0===a&&(a=function(){return 1});var i=Object.create(Tr.prototype);return Cr(i),Ur(i,Object.create(Hr.prototype),e,r,t,n,o,a),i}(i,u,s,l,t,n),e._readable=Dt(i,c,f,o,a),e._backpressure=void 0,e._backpressureChangePromise=void 0,e._backpressureChangePromise_resolve=void 0,fn(e,!0),e._transformStreamController=void 0}(this,h((function(e){i=e})),s,c,u,l),function(e,r){var t,n,o,a=Object.create(dn.prototype);t=void 0!==r.transform?function(e){return r.transform(e,a)}:function(e){try{return hn(a,e),m(void 0)}catch(e){return _(e)}};n=void 0!==r.flush?function(){return r.flush(a)}:function(){return m(void 0)};o=void 0!==r.cancel?function(e){return r.cancel(e)}:function(){return m(void 0)};!function(e,r,t,n,o){r._controlledTransformStream=e,e._transformStreamController=r,r._transformAlgorithm=t,r._flushAlgorithm=n,r._cancelAlgorithm=o,r._finishPromise=void 0,r._finishPromise_resolve=void 0,r._finishPromise_reject=void 0}(e,a,t,n,o)}(this,a),void 0!==a.start?i(a.start(this._transformStreamController)):i(void 0)}return Object.defineProperty(TransformStream.prototype,"readable",{get:function(){if(!un(this))throw gn("readable");return this._readable},enumerable:!1,configurable:!0}),Object.defineProperty(TransformStream.prototype,"writable",{get:function(){if(!un(this))throw gn("writable");return this._writable},enumerable:!1,configurable:!0}),TransformStream}();function un(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_transformStreamController")&&e instanceof an)}function ln(e,r){Tt(e._readable._readableStreamController,r),sn(e,r)}function sn(e,r){pn(e._transformStreamController),Kr(e._writable._writableStreamController,r),cn(e)}function cn(e){e._backpressure&&fn(e,!1)}function fn(e,r){void 0!==e._backpressureChangePromise&&e._backpressureChangePromise_resolve(),e._backpressureChangePromise=h((function(r){e._backpressureChangePromise_resolve=r})),e._backpressure=r}Object.defineProperties(an.prototype,{readable:{enumerable:!0},writable:{enumerable:!0}}),"symbol"==typeof r.toStringTag&&Object.defineProperty(an.prototype,r.toStringTag,{value:"TransformStream",configurable:!0});var dn=function(){function TransformStreamDefaultController(){throw new TypeError("Illegal constructor")}return Object.defineProperty(TransformStreamDefaultController.prototype,"desiredSize",{get:function(){if(!bn(this))throw _n("desiredSize");return Pt(this._controlledTransformStream._readable._readableStreamController)},enumerable:!1,configurable:!0}),TransformStreamDefaultController.prototype.enqueue=function(e){if(void 0===e&&(e=void 0),!bn(this))throw _n("enqueue");hn(this,e)},TransformStreamDefaultController.prototype.error=function(e){if(void 0===e&&(e=void 0),!bn(this))throw _n("error");var r;r=e,ln(this._controlledTransformStream,r)},TransformStreamDefaultController.prototype.terminate=function(){if(!bn(this))throw _n("terminate");!function(e){var r=e._controlledTransformStream;wt(r._readable._readableStreamController);var t=new TypeError("TransformStream terminated");sn(r,t)}(this)},TransformStreamDefaultController}();function bn(e){return!!s(e)&&(!!Object.prototype.hasOwnProperty.call(e,"_controlledTransformStream")&&e instanceof dn)}function pn(e){e._transformAlgorithm=void 0,e._flushAlgorithm=void 0,e._cancelAlgorithm=void 0}function hn(e,r){var t=e._controlledTransformStream,n=t._readable._readableStreamController;if(!Ct(n))throw new TypeError("Readable side is not in a state that permits enqueue");try{Rt(n,r)}catch(e){throw sn(t,e),t._readable._storedError}var o=function(e){return!gt(e)}(n);o!==t._backpressure&&fn(t,!0)}function mn(e,r){return w(e._transformAlgorithm(r),void 0,(function(r){throw ln(e._controlledTransformStream,r),r}))}function _n(e){return new TypeError("TransformStreamDefaultController.prototype.".concat(e," can only be used on a TransformStreamDefaultController"))}function yn(e){void 0!==e._finishPromise_resolve&&(e._finishPromise_resolve(),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function vn(e,r){void 0!==e._finishPromise_reject&&(R(e._finishPromise),e._finishPromise_reject(r),e._finishPromise_resolve=void 0,e._finishPromise_reject=void 0)}function gn(e){return new TypeError("TransformStream.prototype.".concat(e," can only be used on a TransformStream"))}Object.defineProperties(dn.prototype,{enqueue:{enumerable:!0},error:{enumerable:!0},terminate:{enumerable:!0},desiredSize:{enumerable:!0}}),f(dn.prototype.enqueue,"enqueue"),f(dn.prototype.error,"error"),f(dn.prototype.terminate,"terminate"),"symbol"==typeof r.toStringTag&&Object.defineProperty(dn.prototype,r.toStringTag,{value:"TransformStreamDefaultController",configurable:!0});var Sn={ReadableStream:It,ReadableStreamDefaultController:_t,ReadableByteStreamController:Ee,ReadableStreamBYOBRequest:qe,ReadableStreamDefaultReader:ae,ReadableStreamBYOBReader:sr,WritableStream:Tr,WritableStreamDefaultController:Hr,WritableStreamDefaultWriter:Dr,ByteLengthQueuingStrategy:Gt,CountQueuingStrategy:Zt,TransformStream:an,TransformStreamDefaultController:dn};if(void 0!==bt)for(var wn in Sn)Object.prototype.hasOwnProperty.call(Sn,wn)&&Object.defineProperty(bt,wn,{value:Sn[wn],writable:!0,configurable:!0});e.ByteLengthQueuingStrategy=Gt,e.CountQueuingStrategy=Zt,e.ReadableByteStreamController=Ee,e.ReadableStream=It,e.ReadableStreamBYOBReader=sr,e.ReadableStreamBYOBRequest=qe,e.ReadableStreamDefaultController=_t,e.ReadableStreamDefaultReader=ae,e.TransformStream=an,e.TransformStreamDefaultController=dn,e.WritableStream=Tr,e.WritableStreamDefaultController=Hr,e.WritableStreamDefaultWriter=Dr})); +//# sourceMappingURL=polyfill.min.js.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.min.js.map b/node_modules/web-streams-polyfill/dist/polyfill.min.js.map new file mode 100644 index 0000000..ced2e1a --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.min.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/validators/reader-options.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/from.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/pipe-options.ts","../src/lib/readable-stream.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["SymbolPolyfill","Symbol","iterator","description","concat","__generator","thisArg","body","f","y","t","g","_","label","sent","trys","ops","next","verb","throw","return","this","n","v","op","TypeError","call","done","value","pop","length","push","e","step","__values","o","s","m","i","__await","__asyncGenerator","_arguments","generator","asyncIterator","apply","q","Promise","a","b","resume","r","resolve","then","fulfill","reject","settle","shift","__asyncDelegator","p","__asyncValues","d","noop","typeIsObject","x","SuppressedError","rethrowAssertionErrorRejection","setFunctionName","fn","name","Object","defineProperty","configurable","_a","originalPromise","originalPromiseThen","prototype","originalPromiseReject","bind","newPromise","executor","promiseResolvedWith","promiseRejectedWith","reason","PerformPromiseThen","promise","onFulfilled","onRejected","uponPromise","undefined","uponFulfillment","uponRejection","transformPromiseWith","fulfillmentHandler","rejectionHandler","setPromiseIsHandledToTrue","_queueMicrotask","callback","queueMicrotask","resolvedPromise_1","cb","reflectCall","F","V","args","Function","promiseCall","SimpleQueue","_cursor","_size","_front","_elements","_next","_back","get","element","oldBack","newBack","QUEUE_MAX_ARRAY_SIZE","oldFront","newFront","oldCursor","newCursor","elements","forEach","node","peek","front","cursor","AbortSteps","ErrorSteps","CancelSteps","PullSteps","ReleaseSteps","ReadableStreamReaderGenericInitialize","reader","stream","_ownerReadableStream","_reader","_state","defaultReaderClosedPromiseInitialize","defaultReaderClosedPromiseResolve","defaultReaderClosedPromiseInitializeAsResolved","defaultReaderClosedPromiseInitializeAsRejected","_storedError","ReadableStreamReaderGenericCancel","ReadableStreamCancel","ReadableStreamReaderGenericRelease","defaultReaderClosedPromiseReject","defaultReaderClosedPromiseResetToRejected","_readableStreamController","readerLockException","_closedPromise","_closedPromise_resolve","_closedPromise_reject","NumberIsFinite","Number","isFinite","MathTrunc","Math","trunc","ceil","floor","assertDictionary","obj","context","assertFunction","assertObject","isObject","assertRequiredArgument","position","assertRequiredField","field","convertUnrestrictedDouble","censorNegativeZero","convertUnsignedLongLongWithEnforceRange","upperBound","MAX_SAFE_INTEGER","integerPart","assertReadableStream","IsReadableStream","AcquireReadableStreamDefaultReader","ReadableStreamDefaultReader","ReadableStreamAddReadRequest","readRequest","_readRequests","ReadableStreamFulfillReadRequest","chunk","_closeSteps","_chunkSteps","ReadableStreamGetNumReadRequests","ReadableStreamHasDefaultReader","IsReadableStreamDefaultReader","AsyncIteratorPrototype","IsReadableStreamLocked","defaultReaderBrandCheckException","cancel","read","resolvePromise","rejectPromise","ReadableStreamDefaultReaderRead","_errorSteps","releaseLock","ReadableStreamDefaultReaderErrorReadRequests","ReadableStreamDefaultReaderRelease","hasOwnProperty","_disturbed","readRequests","defineProperties","enumerable","closed","toStringTag","ReadableStreamAsyncIteratorImpl","preventCancel","_ongoingPromise","_isFinished","_preventCancel","_this","nextSteps","_nextSteps","returnSteps","_returnSteps","result","ReadableStreamAsyncIteratorPrototype","IsReadableStreamAsyncIterator","_asyncIteratorImpl","streamAsyncIteratorBrandCheckException","setPrototypeOf","NumberIsNaN","isNaN","CreateArrayFromList","slice","CopyDataBlockBytes","dest","destOffset","src","srcOffset","Uint8Array","set","TransferArrayBuffer","O","transfer","buffer","structuredClone","IsDetachedBuffer","detached","byteLength","ArrayBufferSlice","begin","end","ArrayBuffer","GetMethod","receiver","prop","func","String","GetIterator","hint","method","syncIteratorRecord","syncIterable","nextMethod","CreateAsyncFromSyncIterator","CloneAsUint8Array","byteOffset","DequeueValue","container","pair","_queue","_queueTotalSize","size","EnqueueValueWithSize","Infinity","RangeError","ResetQueue","isDataViewConstructor","ctor","DataView","ReadableStreamBYOBRequest","IsReadableStreamBYOBRequest","byobRequestBrandCheckException","_view","respond","bytesWritten","_associatedReadableByteStreamController","ReadableByteStreamControllerRespond","respondWithNewView","view","isView","ReadableByteStreamControllerRespondWithNewView","ReadableByteStreamController","IsReadableByteStreamController","byteStreamControllerBrandCheckException","ReadableByteStreamControllerGetBYOBRequest","ReadableByteStreamControllerGetDesiredSize","close","_closeRequested","state","_controlledReadableByteStream","ReadableByteStreamControllerClose","enqueue","ReadableByteStreamControllerEnqueue","error","ReadableByteStreamControllerError","ReadableByteStreamControllerClearPendingPullIntos","_cancelAlgorithm","ReadableByteStreamControllerClearAlgorithms","ReadableByteStreamControllerFillReadRequestFromQueue","autoAllocateChunkSize","_autoAllocateChunkSize","bufferE","pullIntoDescriptor","bufferByteLength","bytesFilled","minimumFill","elementSize","viewConstructor","readerType","_pendingPullIntos","ReadableByteStreamControllerCallPullIfNeeded","firstPullInto","controller","shouldPull","_started","ReadableStreamHasBYOBReader","ReadableStreamGetNumReadIntoRequests","desiredSize","ReadableByteStreamControllerShouldCallPull","_pulling","_pullAgain","_pullAlgorithm","ReadableByteStreamControllerInvalidateBYOBRequest","ReadableByteStreamControllerCommitPullIntoDescriptor","filledView","ReadableByteStreamControllerConvertPullIntoDescriptor","readIntoRequest","_readIntoRequests","ReadableStreamFulfillReadIntoRequest","ReadableByteStreamControllerEnqueueChunkToQueue","ReadableByteStreamControllerEnqueueClonedChunkToQueue","clonedChunk","cloneE","ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue","firstDescriptor","ReadableByteStreamControllerShiftPendingPullInto","ReadableByteStreamControllerFillPullIntoDescriptorFromQueue","maxBytesToCopy","min","maxBytesFilled","totalBytesToCopyRemaining","ready","maxAlignedBytes","queue","headOfQueue","bytesToCopy","destStart","ReadableByteStreamControllerFillHeadPullIntoDescriptor","ReadableByteStreamControllerHandleQueueDrain","ReadableStreamClose","_byobRequest","ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue","ReadableByteStreamControllerPullInto","constructor","BYTES_PER_ELEMENT","arrayBufferViewElementSize","ReadableStreamAddReadIntoRequest","emptyView","ReadableByteStreamControllerRespondInternal","ReadableByteStreamControllerRespondInClosedState","remainderSize","ReadableByteStreamControllerRespondInReadableState","firstPendingPullInto","transferredBuffer","ReadableByteStreamControllerProcessReadRequestsUsingQueue","ReadableStreamError","entry","byobRequest","create","request","SetUpReadableStreamBYOBRequest","_strategyHWM","viewByteLength","SetUpReadableByteStreamController","startAlgorithm","pullAlgorithm","cancelAlgorithm","highWaterMark","convertReadableStreamReaderMode","mode","AcquireReadableStreamBYOBReader","ReadableStreamBYOBReader","IsReadableStreamBYOBReader","byobReaderBrandCheckException","rawOptions","options","convertByobReadOptions","isDataView","ReadableStreamBYOBReaderRead","ReadableStreamBYOBReaderErrorReadIntoRequests","ReadableStreamBYOBReaderRelease","readIntoRequests","ExtractHighWaterMark","strategy","defaultHWM","ExtractSizeAlgorithm","convertQueuingStrategy","init","convertQueuingStrategySize","convertUnderlyingSinkAbortCallback","original","convertUnderlyingSinkCloseCallback","convertUnderlyingSinkStartCallback","convertUnderlyingSinkWriteCallback","assertWritableStream","IsWritableStream","supportsAbortController","AbortController","WritableStream","rawUnderlyingSink","rawStrategy","underlyingSink","abort","start","type","write","convertUnderlyingSink","InitializeWritableStream","sizeAlgorithm","writeAlgorithm","closeAlgorithm","abortAlgorithm","WritableStreamDefaultController","SetUpWritableStreamDefaultController","SetUpWritableStreamDefaultControllerFromUnderlyingSink","streamBrandCheckException","IsWritableStreamLocked","WritableStreamAbort","WritableStreamCloseQueuedOrInFlight","WritableStreamClose","getWriter","AcquireWritableStreamDefaultWriter","WritableStreamDefaultWriter","_writer","_writableStreamController","_writeRequests","_inFlightWriteRequest","_closeRequest","_inFlightCloseRequest","_pendingAbortRequest","_backpressure","_abortReason","_abortController","_promise","wasAlreadyErroring","_resolve","_reject","_reason","_wasAlreadyErroring","WritableStreamStartErroring","closeRequest","writer","defaultWriterReadyPromiseResolve","closeSentinel","WritableStreamDefaultControllerAdvanceQueueIfNeeded","WritableStreamDealWithRejection","WritableStreamFinishErroring","WritableStreamDefaultWriterEnsureReadyPromiseRejected","WritableStreamHasOperationMarkedInFlight","storedError","writeRequest","abortRequest","WritableStreamRejectCloseAndClosedPromiseIfNeeded","defaultWriterClosedPromiseReject","WritableStreamUpdateBackpressure","backpressure","defaultWriterReadyPromiseInitialize","defaultWriterReadyPromiseReset","locked","_ownerWritableStream","defaultWriterReadyPromiseInitializeAsResolved","defaultWriterClosedPromiseInitialize","defaultWriterReadyPromiseInitializeAsRejected","defaultWriterClosedPromiseResolve","defaultWriterClosedPromiseInitializeAsRejected","IsWritableStreamDefaultWriter","defaultWriterBrandCheckException","defaultWriterLockException","WritableStreamDefaultControllerGetDesiredSize","WritableStreamDefaultWriterGetDesiredSize","_readyPromise","WritableStreamDefaultWriterAbort","WritableStreamDefaultWriterClose","WritableStreamDefaultWriterRelease","WritableStreamDefaultWriterWrite","WritableStreamDefaultWriterEnsureClosedPromiseRejected","_closedPromiseState","defaultWriterClosedPromiseResetToRejected","_readyPromiseState","defaultWriterReadyPromiseReject","defaultWriterReadyPromiseResetToRejected","releasedError","chunkSize","_strategySizeAlgorithm","chunkSizeE","WritableStreamDefaultControllerErrorIfNeeded","WritableStreamDefaultControllerGetChunkSize","WritableStreamAddWriteRequest","enqueueE","_controlledWritableStream","WritableStreamDefaultControllerGetBackpressure","WritableStreamDefaultControllerWrite","IsWritableStreamDefaultController","defaultControllerBrandCheckException","signal","WritableStreamDefaultControllerError","_abortAlgorithm","WritableStreamDefaultControllerClearAlgorithms","createAbortController","_writeAlgorithm","_closeAlgorithm","WritableStreamMarkCloseRequestInFlight","sinkClosePromise","WritableStreamFinishInFlightClose","WritableStreamFinishInFlightCloseWithError","WritableStreamDefaultControllerProcessClose","WritableStreamMarkFirstWriteRequestInFlight","sinkWritePromise","WritableStreamFinishInFlightWrite","WritableStreamFinishInFlightWriteWithError","WritableStreamDefaultControllerProcessWrite","_readyPromise_resolve","_readyPromise_reject","abortReason","globals","globalThis","self","global","DOMException","isDOMExceptionConstructor","message","Error","captureStackTrace","writable","createPolyfill","ReadableStreamPipeTo","source","preventClose","preventAbort","shuttingDown","currentWrite","action","actions","shutdownWithAction","all","map","aborted","addEventListener","isOrBecomesErrored","shutdown","WritableStreamDefaultWriterCloseWithErrorPropagation","destClosed_1","waitForWritesToFinish","oldCurrentWrite","originalIsError","originalError","doTheRest","finalize","newError","isError","removeEventListener","resolveLoop","rejectLoop","resolveRead","rejectRead","ReadableStreamDefaultController","IsReadableStreamDefaultController","ReadableStreamDefaultControllerGetDesiredSize","ReadableStreamDefaultControllerCanCloseOrEnqueue","ReadableStreamDefaultControllerClose","ReadableStreamDefaultControllerEnqueue","ReadableStreamDefaultControllerError","ReadableStreamDefaultControllerClearAlgorithms","_controlledReadableStream","ReadableStreamDefaultControllerCallPullIfNeeded","ReadableStreamDefaultControllerShouldCallPull","SetUpReadableStreamDefaultController","ReadableStreamTee","cloneForBranch2","reason1","reason2","branch1","branch2","resolveCancelPromise","reading","readAgainForBranch1","readAgainForBranch2","canceled1","canceled2","cancelPromise","forwardReaderError","thisReader","pullWithDefaultReader","chunk1","chunk2","pull1Algorithm","pull2Algorithm","pullWithBYOBReader","forBranch2","byobBranch","otherBranch","byobCanceled","otherCanceled","cancel1Algorithm","compositeReason","cancelResult","cancel2Algorithm","CreateReadableByteStream","ReadableByteStreamTee","readAgain","CreateReadableStream","ReadableStreamDefaultTee","ReadableStreamFrom","getReader","readPromise","readResult","ReadableStreamFromDefaultReader","asyncIterable","iteratorRecord","nextResult","IteratorNext","iterResult","Boolean","IteratorComplete","IteratorValue","returnMethod","returnResult","ReadableStreamFromIterable","convertUnderlyingSourceCancelCallback","convertUnderlyingSourcePullCallback","convertUnderlyingSourceStartCallback","convertReadableStreamType","convertPipeOptions","isAbortSignal","assertAbortSignal","ReadableStream","rawUnderlyingSource","underlyingSource","pull","convertUnderlyingDefaultOrByteSource","InitializeReadableStream","underlyingByteSource","SetUpReadableByteStreamControllerFromUnderlyingSource","SetUpReadableStreamDefaultControllerFromUnderlyingSource","convertReaderOptions","pipeThrough","rawTransform","transform","readable","convertReadableWritablePair","pipeTo","destination","tee","values","impl","convertIteratorOptions","from","convertQueuingStrategyInit","byteLengthSizeFunction","ByteLengthQueuingStrategy","_byteLengthQueuingStrategyHighWaterMark","IsByteLengthQueuingStrategy","byteLengthBrandCheckException","countSizeFunction","CountQueuingStrategy","_countQueuingStrategyHighWaterMark","IsCountQueuingStrategy","countBrandCheckException","convertTransformerFlushCallback","convertTransformerStartCallback","convertTransformerTransformCallback","convertTransformerCancelCallback","TransformStream","rawTransformer","rawWritableStrategy","rawReadableStrategy","writableStrategy","readableStrategy","transformer","flush","readableType","writableType","convertTransformer","startPromise_resolve","readableHighWaterMark","readableSizeAlgorithm","writableHighWaterMark","writableSizeAlgorithm","startPromise","_transformStreamController","_backpressureChangePromise","_writable","TransformStreamDefaultControllerPerformTransform","TransformStreamDefaultSinkWriteAlgorithm","_finishPromise","_readable","_finishPromise_resolve","_finishPromise_reject","TransformStreamDefaultControllerClearAlgorithms","defaultControllerFinishPromiseReject","defaultControllerFinishPromiseResolve","TransformStreamDefaultSinkAbortAlgorithm","flushPromise","_flushAlgorithm","TransformStreamDefaultSinkCloseAlgorithm","TransformStreamSetBackpressure","TransformStreamDefaultSourcePullAlgorithm","TransformStreamUnblockWrite","TransformStreamDefaultSourceCancelAlgorithm","CreateWritableStream","_backpressureChangePromise_resolve","InitializeTransformStream","transformAlgorithm","flushAlgorithm","TransformStreamDefaultController","TransformStreamDefaultControllerEnqueue","transformResultE","_controlledTransformStream","_transformAlgorithm","SetUpTransformStreamDefaultController","SetUpTransformStreamDefaultControllerFromTransformer","IsTransformStream","TransformStreamError","TransformStreamErrorWritableAndUnblockWrite","IsTransformStreamDefaultController","terminate","TransformStreamDefaultControllerTerminate","readableController","ReadableStreamDefaultControllerHasBackpressure","exports"],"mappings":";;;;;;;0PAEA,IAAMA,EACc,mBAAXC,QAAoD,iBAApBA,OAAOC,SAC5CD,OACA,SAAAE,GAAe,MAAA,UAAAC,OAAUD,EAA+B,IAAA,ECuHrD,SAASE,EAAYC,EAASC,GACjC,IAAsGC,EAAGC,EAAGC,EAAGC,EAA3GC,EAAI,CAAEC,MAAO,EAAGC,KAAM,WAAa,GAAW,EAAPJ,EAAE,GAAQ,MAAMA,EAAE,GAAI,OAAOA,EAAE,EAAK,EAAEK,KAAM,GAAIC,IAAK,IAChG,OAAOL,EAAI,CAAEM,KAAMC,EAAK,GAAIC,MAASD,EAAK,GAAIE,OAAUF,EAAK,IAAwB,mBAAXjB,SAA0BU,EAAEV,OAAOC,UAAY,WAAa,OAAOmB,IAAO,GAAGV,EACvJ,SAASO,EAAKI,GAAK,OAAO,SAAUC,GAAK,OACzC,SAAcC,GACV,GAAIhB,EAAG,MAAM,IAAIiB,UAAU,mCAC3B,KAAOd,IAAMA,EAAI,EAAGa,EAAG,KAAOZ,EAAI,IAAKA,OACnC,GAAIJ,EAAI,EAAGC,IAAMC,EAAY,EAARc,EAAG,GAASf,EAAU,OAAIe,EAAG,GAAKf,EAAS,SAAOC,EAAID,EAAU,SAAMC,EAAEgB,KAAKjB,GAAI,GAAKA,EAAEQ,SAAWP,EAAIA,EAAEgB,KAAKjB,EAAGe,EAAG,KAAKG,KAAM,OAAOjB,EAE3J,OADID,EAAI,EAAGC,IAAGc,EAAK,CAAS,EAARA,EAAG,GAAQd,EAAEkB,QACzBJ,EAAG,IACP,KAAK,EAAG,KAAK,EAAGd,EAAIc,EAAI,MACxB,KAAK,EAAc,OAAXZ,EAAEC,QAAgB,C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,UAAW,CAAE7gB,YAAY,GACzBqH,YAAa,CAAErH,YAAY,KAE7B9I,EAAgBgpB,GAAiCvoB,UAAUgO,QAAS,WACpEzO,EAAgBgpB,GAAiCvoB,UAAUkO,MAAO,SAClE3O,EAAgBgpB,GAAiCvoB,UAAUkpB,UAAW,aACpC,iBAAvB5tB,EAAOiN,aAChB7I,OAAOC,eAAe4oB,GAAiCvoB,UAAW1E,EAAOiN,YAAa,CACpFtL,MAAO,mCACP2C,cAAc,IClVlB,IAAM0pB,GAAU,CACd9F,eAAcA,GACdtE,gCAA+BA,GAC/B5R,6BAA4BA,GAC5BZ,0BAAyBA,GACzBhG,4BAA2BA,GAC3BgN,yBAAwBA,GAExB2B,eAAcA,GACdc,gCAA+BA,GAC/BU,4BAA2BA,GAE3BmO,0BAAyBA,GACzBK,qBAAoBA,GAEpBQ,gBAAeA,GACf0C,iCAAgCA,IAIlC,QAAuB,IAAZ9L,GACT,IAAK,IAAMxR,MAAQqe,GACb5pB,OAAOM,UAAUiI,eAAelL,KAAKusB,GAASre,KAChDvL,OAAOC,eAAe8c,GAASxR,GAAM,CACnChO,MAAOqsB,GAAQre,IACfiS,UAAU,EACVtd,cAAc","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/polyfill.mjs b/node_modules/web-streams-polyfill/dist/polyfill.mjs new file mode 100644 index 0000000..1b5eda8 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.mjs @@ -0,0 +1,4992 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +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; +}; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +var rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +var originalPromise = Promise; +var originalPromiseThen = Promise.prototype.then; +var originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +var QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; +}()); + +var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +var PullSteps = SymbolPolyfill('[[PullSteps]]'); +var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; +}()); +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); +} + +/// +var _a; +var AsyncIteratorPrototype; +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolPolyfill.asyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); +} + +/// +var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; +}()); +var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); +}; +var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; +} +function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; +}()); +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; +}()); +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; +}()); +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +var supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; +}()); +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; +}()); +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +var closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; +}()); +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +var globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +var DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; +}()); +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; +}()); +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; +}()); +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +var countSizeFunction = function () { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; +}()); +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; +}()); +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; +}()); +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); +} + +var exports = { + ReadableStream: ReadableStream, + ReadableStreamDefaultController: ReadableStreamDefaultController, + ReadableByteStreamController: ReadableByteStreamController, + ReadableStreamBYOBRequest: ReadableStreamBYOBRequest, + ReadableStreamDefaultReader: ReadableStreamDefaultReader, + ReadableStreamBYOBReader: ReadableStreamBYOBReader, + WritableStream: WritableStream, + WritableStreamDefaultController: WritableStreamDefaultController, + WritableStreamDefaultWriter: WritableStreamDefaultWriter, + ByteLengthQueuingStrategy: ByteLengthQueuingStrategy, + CountQueuingStrategy: CountQueuingStrategy, + TransformStream: TransformStream, + TransformStreamDefaultController: TransformStreamDefaultController +}; +// Add classes to global scope +if (typeof globals !== 'undefined') { + for (var prop in exports) { + if (Object.prototype.hasOwnProperty.call(exports, prop)) { + Object.defineProperty(globals, prop, { + value: exports[prop], + writable: true, + configurable: true + }); + } + } +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=polyfill.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/polyfill.mjs.map b/node_modules/web-streams-polyfill/dist/polyfill.mjs.map new file mode 100644 index 0000000..03e63be --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/polyfill.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"polyfill.mjs","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts","../src/polyfill.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n","import {\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n ReadableByteStreamController,\n ReadableStream,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultController,\n ReadableStreamDefaultReader,\n TransformStream,\n TransformStreamDefaultController,\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter\n} from './ponyfill';\nimport { globals } from './globals';\n\n// Export\nexport * from './ponyfill';\n\nconst exports = {\n ReadableStream,\n ReadableStreamDefaultController,\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader,\n\n WritableStream,\n WritableStreamDefaultController,\n WritableStreamDefaultWriter,\n\n ByteLengthQueuingStrategy,\n CountQueuingStrategy,\n\n TransformStream,\n TransformStreamDefaultController\n};\n\n// Add classes to global scope\nif (typeof globals !== 'undefined') {\n for (const prop in exports) {\n if (Object.prototype.hasOwnProperty.call(exports, prop)) {\n Object.defineProperty(globals, prop, {\n value: exports[prop as (keyof typeof exports)],\n writable: true,\n configurable: true\n });\n }\n }\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;AAAA;AAEA,IAAM,cAAc,G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B,IAAA,yBAAyB,EAAA,yBAAA;AACzB,IAAA,2BAA2B,EAAA,2BAAA;AAC3B,IAAA,wBAAwB,EAAA,wBAAA;AAExB,IAAA,cAAc,EAAA,cAAA;AACd,IAAA,+BAA+B,EAAA,+BAAA;AAC/B,IAAA,2BAA2B,EAAA,2BAAA;AAE3B,IAAA,yBAAyB,EAAA,yBAAA;AACzB,IAAA,oBAAoB,EAAA,oBAAA;AAEpB,IAAA,eAAe,EAAA,eAAA;AACf,IAAA,gCAAgC,EAAA,gCAAA;CACjC,CAAC;AAEF;AACA,IAAI,OAAO,OAAO,KAAK,WAAW,EAAE;AAClC,IAAA,KAAK,IAAM,IAAI,IAAI,OAAO,EAAE;AAC1B,QAAA,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,EAAE;AACvD,YAAA,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,IAAI,EAAE;AACnC,gBAAA,KAAK,EAAE,OAAO,CAAC,IAA8B,CAAC;AAC9C,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,YAAY,EAAE,IAAI;AACnB,aAAA,CAAC,CAAC;SACJ;KACF;AACH;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js new file mode 100644 index 0000000..e1e5cec --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js @@ -0,0 +1,4739 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + /* eslint-disable @typescript-eslint/no-empty-function */ + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.es2018.js.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map new file mode 100644 index 0000000..7ec3dbf --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es2018.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;;;;;;;IAAA;IAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,IAAA,MAAM;IACN,IAAA,WAAW,IAAI,CAAU,OAAA,EAAA,WAAW,GAAoB;;aCL5C,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,M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;IACnC,CAAC;IAED;IAEA,SAAS,oCAAoC,CAAC,IAAY,EAAA;IACxD,IAAA,OAAO,IAAI,SAAS,CAClB,8CAA8C,IAAI,CAAA,uDAAA,CAAyD,CAAC,CAAC;IACjH,CAAC;IAEK,SAAU,qCAAqC,CAAC,UAAiD,EAAA;IACrG,IAAA,IAAI,UAAU,CAAC,sBAAsB,KAAK,SAAS,EAAE;YACnD,OAAO;SACR;QAED,UAAU,CAAC,sBAAsB,EAAE,CAAC;IACpC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;IACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;YAClD,OAAO;SACR;IAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;IACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs new file mode 100644 index 0000000..a3bd000 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs @@ -0,0 +1,4719 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +const PullSteps = SymbolPolyfill('[[PullSteps]]'); +const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +/* eslint-disable @typescript-eslint/no-empty-function */ +const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { }).prototype); + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (async function* () { + return yield* syncIterable; + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.es2018.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map new file mode 100644 index 0000000..3e65262 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es2018.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es2018.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es2018/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\n/* eslint-disable @typescript-eslint/no-empty-function */\nexport const AsyncIteratorPrototype: AsyncIterable | undefined =\n Object.getPrototypeOf(Object.getPrototypeOf(async function* (): AsyncIterableIterator {}).prototype);\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;AAAA;AAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;AACjE,IAAA,MAAM;AACN,IAAA,WAAW,IAAI,CAAU,OAAA,EAAA,WAAW,GAAoB;;SCL5C,IAAI,GAAA;AAClB,IAAA,OAAO,SAAS,CAAC;AACnB;;ACCM,SAAU,YAAY,CAAC,CAAM,EAAA;AACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;AAC1E,CAAC;AAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;AAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;AACxD,IAAA,IAAI;AACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;AAChC,YAAA,KAAK,EAAE,IAAI;AACX,YAAA,YAAY,EAAE,IAAI;AACnB,SAAA,CAAC,CAAC;K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AC,qBAAqB,KAAK,SAAS,EAAE;QAClD,OAAO;KACR;AAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;AACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;"} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es6.js b/node_modules/web-streams-polyfill/dist/ponyfill.es6.js new file mode 100644 index 0000000..3673a6a --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es6.js @@ -0,0 +1,4816 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + const rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + const QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + + const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + const PullSteps = SymbolPolyfill('[[PullSteps]]'); + const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + + /// + let AsyncIteratorPrototype; + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolPolyfill.asyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); + } + + /// + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + 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; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); + }; + let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; + } + function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + const supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + const globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + const DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } + } + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + const countSizeFunction = () => { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.es6.js.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map b/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map new file mode 100644 index 0000000..f002ae0 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es6.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es6.js","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;;;;;;;IAAA;IAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;IACjE,IAAA,MAAM;IACN,IAAA,WAAW,IAAI,CAAU,OAAA,EAAA,WAAW,GAAoB;;aCL5C,IAAI,GAAA;IAClB,IAAA,OAAO,SAAS,CAAC;IACnB;;ICCM,SAAU,YAAY,CAAC,CAAM,EAAA;IACjC,IAAA,OAAO,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,KAAK,UAAU,CAAC;IAC1E,CAAC;IAEM,MAAM,8BAA8B,GAUrC,IAAI,CAAC;IAEK,SAAA,eAAe,CAAC,EAAY,EAAE,IAAY,EAAA;IACxD,IAAA,IAAI;IACF,QAAA,MAAM,CAAC,cAAc,CAAC,EAAE,EAAE,MAAM,EAAE;IAChC,YAAA,KAAK,EAAE,IAAI;IACX,YAAA,YAAY,EAAE,IAAI;IACnB,SAAA,CAAC,CAAC;SACJ;IAAC,IAAA,O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C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[15]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs b/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs new file mode 100644 index 0000000..8b0b073 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs @@ -0,0 +1,4796 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +const SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + description => `Symbol(${description})`; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +const rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +const originalPromise = Promise; +const originalPromiseThen = Promise.prototype.then; +const originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(resolve => resolve(value)); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +let _queueMicrotask = callback => { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + const resolvedPromise = promiseResolvedWith(undefined); + _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb); + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +const QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + get length() { + return this._size; + } + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + shift() { // must not be called on an empty queue + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + } + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + forEach(callback) { + let i = this._cursor; + let node = this._front; + let elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + } + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + peek() { // must not be called on an empty queue + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } +} + +const AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +const ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +const CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +const PullSteps = SymbolPolyfill('[[PullSteps]]'); +const ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + const stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +const NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +const MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError(`${context} is not a function.`); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError(`${context} is not an object.`); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError(`${field} is required in '${context}'.`); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError(`${context} is not a finite number`); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: undefined, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); +} + +/// +let AsyncIteratorPrototype; +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = { + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + [SymbolPolyfill.asyncIterator]() { + return this; + } + }; + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); +} + +/// +class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + const reader = this._reader; + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: chunk => { + this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: reason => { + this._ongoingPromise = undefined; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } +} +const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +const NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +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; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +let TransferArrayBuffer = (O) => { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = buffer => buffer.transfer(); + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] }); + } + else { + // Not implemented correctly + TransferArrayBuffer = buffer => buffer; + } + return TransferArrayBuffer(O); +}; +let IsDetachedBuffer = (O) => { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = buffer => buffer.detached; + } + else { + // Not implemented correctly + IsDetachedBuffer = buffer => buffer.byteLength === 0; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + const func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError(`${String(prop)} is not a function`); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + const syncIterable = { + [SymbolPolyfill.iterator]: () => syncIteratorRecord.iterator + }; + // Create an async generator function and immediately invoke it. + const asyncIterator = (function () { + return __asyncGenerator(this, arguments, function* () { + return yield __await(yield __await(yield* __asyncDelegator(__asyncValues(syncIterable)))); + }); + }()); + // Return as an async iterator record. + const nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod, done: false }; +} +function GetIterator(obj, hint = 'sync', method) { + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + const syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + const syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + const iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + const nextMethod = iterator.next; + return { iterator, nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } +} +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +class ReadableByteStreamController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + const state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + /** @internal */ + [ReleaseSteps]() { + if (this._pendingPullIntos.length > 0) { + const firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + } +} +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === 'closed') { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + let clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + const maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + const reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + const ctor = view.constructor; + const elementSize = arrayBufferViewElementSize(ctor); + const { byteOffset, byteLength } = view; + const minimumFill = min * elementSize; + let buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset, + byteLength, + bytesFilled: 0, + minimumFill, + elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + const e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + const { buffer, byteOffset, byteLength } = chunk; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + const entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingByteSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== 'byob') { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + const min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, `${context} has member 'min' that`) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason = undefined) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view, rawOptions = {}) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + let options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + const min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }), + _closeSteps: chunk => resolvePromise({ value: chunk, done: true }), + _errorSteps: e => rejectPromise(e) + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + } + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + } +} +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + const e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return chunk => convertUnrestrictedDouble(fn(chunk)); +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError(`${context} is not a WritableStream.`); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +const supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + } + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason = undefined) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + } + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + } + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + } +} +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + const state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach(writeRequest => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + const state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + const writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + } + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + } + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + } + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + const stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = undefined) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } +} +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + const state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +const closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +class WritableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + } + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + } + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e = undefined) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + const state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + } + /** @internal */ + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [ErrorSteps]() { + ResetQueue(this); + } +} +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, r => { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm; + let writeAlgorithm; + let closeAlgorithm; + let abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = () => underlyingSink.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = chunk => underlyingSink.write(chunk, controller); + } + else { + writeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = () => underlyingSink.close(); + } + else { + closeAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = reason => underlyingSink.abort(reason); + } + else { + abortAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + const state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + return null; + }, reason => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, reason => { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +const globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + const ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + const ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +const DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + let currentWrite = promiseResolvedWith(undefined); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = () => { + const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: chunk => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, storedError => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, storedError => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } + else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), newError => finalize(true, newError)); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +class ReadableStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e = undefined) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + } + /** @internal */ + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + /** @internal */ + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + /** @internal */ + [ReleaseSteps]() { + // Do nothing. + } +} +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, e => { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + const stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, r => { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm; + let pullAlgorithm; + let cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = () => underlyingSource.start(controller); + } + else { + startAlgorithm = () => undefined; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + else { + pullAlgorithm = () => promiseResolvedWith(undefined); + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = reason => underlyingSource.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise(resolve => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, r => { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: chunk => { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: chunk => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + let stream; + const iteratorRecord = GetIterator(asyncIterable, 'async'); + const startAlgorithm = noop; + function pullAlgorithm() { + let nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + const nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + const done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + const iterator = iteratorRecord.iterator; + let returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + let returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + const returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, iterResult => { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + let stream; + const startAlgorithm = noop; + function pullAlgorithm() { + let readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, readResult => { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + const value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== 'bytes') { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +class ReadableStream { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + } + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason = undefined) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + const options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + const transform = convertReadableWritablePair(rawTransform, 'First parameter'); + const options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = undefined) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + const options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable) { + return ReadableStreamFrom(asyncIterable); + } +} +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + const readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(readIntoRequest => { + readIntoRequest._closeSteps(undefined); + }); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + const readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(readRequest => { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + const reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + } +} +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +const countSizeFunction = () => { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + } + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + } +} +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, `${context} has member 'cancel' that`), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === undefined) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + const transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise(resolve => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + /** + * The readable side of the transform stream. + */ + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + } + /** + * The writable side of the transform stream. + */ + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + } +} +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(resolve => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +class TransformStreamDefaultController { + constructor() { + throw new TypeError('Illegal constructor'); + } + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason = undefined) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + } + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + } +} +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm; + let flushAlgorithm; + let cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = chunk => transformer.transform(chunk, controller); + } + else { + transformAlgorithm = chunk => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = () => transformer.flush(controller); + } + else { + flushAlgorithm = () => promiseResolvedWith(undefined); + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = reason => transformer.cancel(reason); + } + else { + cancelAlgorithm = () => promiseResolvedWith(undefined); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, r => { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + const readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, () => { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + const controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + const writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise((resolve, reject) => { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + const cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, () => { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, r => { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.es6.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map b/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map new file mode 100644 index 0000000..6aed30b --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.es6.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.es6.mjs","sources":["../src/stub/symbol.ts","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../node_modules/tslib/tslib.es6.js","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;AAAA;AAEA,MAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;AACjE,IAAA,M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,OAAO;KACR;AAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;AACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,6BAA6B,IAAI,CAAA,sCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;","x_google_ignoreList":[15]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.js b/node_modules/web-streams-polyfill/dist/ponyfill.js new file mode 100644 index 0000000..a75e540 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.js @@ -0,0 +1,4984 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.WebStreamsPolyfill = {})); +})(this, (function (exports) { 'use strict'; + + /// + var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol */ + + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + 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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + } + + 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; + }; + + function noop() { + return undefined; + } + + function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + var rethrowAssertionErrorRejection = noop; + function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } + } + + var originalPromise = Promise; + var originalPromiseThen = Promise.prototype.then; + var originalPromiseReject = Promise.reject.bind(originalPromise); + // https://webidl.spec.whatwg.org/#a-new-promise + function newPromise(executor) { + return new originalPromise(executor); + } + // https://webidl.spec.whatwg.org/#a-promise-resolved-with + function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); + } + // https://webidl.spec.whatwg.org/#a-promise-rejected-with + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + // Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned + // from that handler. To prevent this, return null instead of void from all handlers. + // http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); + } + var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); + }; + function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); + } + function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } + } + + // Original from Chromium + // https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js + var QUEUE_MAX_ARRAY_SIZE = 16384; + /** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ + var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; + }()); + + var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); + var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); + var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); + var PullSteps = SymbolPolyfill('[[PullSteps]]'); + var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + // A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state + // check. + function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; + } + // Helper functions for the readers. + function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill + var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); + }; + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill + var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + + // https://heycam.github.io/webidl/#idl-dictionaries + function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; + } + function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + // https://heycam.github.io/webidl/#idl-callback-functions + function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } + } + // https://heycam.github.io/webidl/#idl-object + function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; + } + function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } + } + function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } + } + function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } + } + // https://heycam.github.io/webidl/#idl-unrestricted-double + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x) { + return x === 0 ? 0 : x; + } + function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); + } + // https://heycam.github.io/webidl/#idl-unsigned-long-long + function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; + } + + function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + /** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; + }()); + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); + setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamDefaultReader. + function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); + } + + /// + var _a; + var AsyncIteratorPrototype; + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolPolyfill.asyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); + } + + /// + var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; + }()); + var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + // Abstract operations for the ReadableStream. + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } + } + // Helper functions for the ReadableStream. + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); + } + + /// + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill + var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; + }; + + function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); + }; + var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); + }; + function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; + } + function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; + } + function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; + } + function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; + } + function IteratorComplete(iterResult) { + return Boolean(iterResult.done); + } + function IteratorValue(iterResult) { + return iterResult.value; + } + + function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + + function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + + function isDataViewConstructor(ctor) { + return ctor === DataView; + } + function isDataView(view) { + return isDataViewConstructor(view.constructor); + } + function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; + } + + /** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ + var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; + }()); + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); + setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); + } + /** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ + var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; + }()); + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableByteStreamController.prototype.close, 'close'); + setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableByteStreamController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); + } + // Abstract operations for the ReadableByteStreamController. + function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); + } + function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } + } + function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + // A client of ReadableByteStreamController may use these functions directly to bypass state check. + function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; + } + // Helper functions for the ReadableStreamBYOBRequest. + function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); + } + // Helper functions for the ReadableByteStreamController. + function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); + } + + function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; + } + function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; + } + + // Abstract operations for the ReadableStream. + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + // ReadableStream API exposed for controllers. + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + /** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ + var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; + }()); + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); + setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); + setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); + } + // Abstract operations for the readers. + function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } + } + function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); + } + // Helper functions for the ReadableStreamBYOBReader. + function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); + } + + function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; + } + + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; + } + + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + + function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } + } + + function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } + } + var supportsAbortController = typeof AbortController === 'function'; + /** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; + } + + /** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ + var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; + }()); + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(WritableStream.prototype.abort, 'abort'); + setFunctionName(WritableStream.prototype.close, 'close'); + setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); + } + // Abstract operations for the WritableStream. + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + // Throws if and only if startAlgorithm throws. + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; + } + function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + // WritableStream API exposed for controllers. + function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); + } + // TODO(ricea): Fix alphabetical order. + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + /** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ + var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; + }()); + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); + setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); + setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); + setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); + } + // Abstract operations for the WritableStreamDefaultWriter. + function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; + } + // A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. + function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + var closeSentinel = {}; + /** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ + var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; + }()); + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); + } + // Abstract operations implementing interface required by the WritableStream. + function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + // ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + // Abstract operations for the WritableStreamDefaultController. + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + // A client of WritableStreamDefaultController may use these functions directly to bypass state check. + function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + // Helper functions for the WritableStream. + function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); + } + // Helper functions for the WritableStreamDefaultController. + function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); + } + // Helper functions for the WritableStreamDefaultWriter. + function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); + } + function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; + } + + /// + function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; + } + var globals = getGlobals(); + + /// + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } + } + /** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ + function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; + } + /** + * Support: + * - All platforms + */ + function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; + } + // eslint-disable-next-line @typescript-eslint/no-redeclare + var DOMException = getFromGlobal() || createPolyfill(); + + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); + } + + /** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ + var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; + }()); + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); + setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); + } + // Abstract operations for the ReadableStreamDefaultController. + function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; + } + // A client of ReadableStreamDefaultController may use these functions directly to bypass state check. + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + // This is used in the implementation of TransformStream. + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + // Helper functions for the ReadableStreamDefaultController. + function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); + } + + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + + function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; + } + + function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); + } + function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; + } + + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; + } + + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + + function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } + } + + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; + } + + /** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ + var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; + }()); + Object.defineProperties(ReadableStream, { + from: { enumerable: true } + }); + Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + setFunctionName(ReadableStream.from, 'from'); + setFunctionName(ReadableStream.prototype.cancel, 'cancel'); + setFunctionName(ReadableStream.prototype.getReader, 'getReader'); + setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); + setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); + setFunctionName(ReadableStream.prototype.tee, 'tee'); + setFunctionName(ReadableStream.prototype.values, 'values'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); + } + // Abstract operations for the ReadableStream. + // Throws if and only if startAlgorithm throws. + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + // Throws if and only if startAlgorithm throws. + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; + } + function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; + } + // ReadableStream API exposed for controllers. + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); + } + function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } + } + function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } + } + // Helper functions for the ReadableStream. + function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); + } + + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + + // The size function must not have a prototype property nor be a constructor + var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; + }; + setFunctionName(byteLengthSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ + var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; + }()); + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); + } + // Helper functions for the ByteLengthQueuingStrategy. + function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); + } + function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; + } + + // The size function must not have a prototype property nor be a constructor + var countSizeFunction = function () { + return 1; + }; + setFunctionName(countSizeFunction, 'size'); + /** + * A queuing strategy that counts the number of chunks. + * + * @public + */ + var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; + }()); + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); + } + // Helper functions for the CountQueuingStrategy. + function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); + } + function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; + } + + function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; + } + function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; + } + + // Class TransformStream + /** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ + var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; + }()); + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; + } + function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; + } + // This is a no-op if both sides are already errored. + function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); + } + function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + // Class TransformStreamDefaultController + /** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ + var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; + }()); + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); + setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); + setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); + if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); + } + // Transform Stream Default Controller Abstract Operations + function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + // TransformStreamDefaultSink Algorithms + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // TransformStreamDefaultSource Algorithms + function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; + } + function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; + } + // Helper functions for the TransformStreamDefaultController. + function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); + } + function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; + } + // Helper functions for the TransformStream. + function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); + } + + exports.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports.CountQueuingStrategy = CountQueuingStrategy; + exports.ReadableByteStreamController = ReadableByteStreamController; + exports.ReadableStream = ReadableStream; + exports.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports.TransformStream = TransformStream; + exports.TransformStreamDefaultController = TransformStreamDefaultController; + exports.WritableStream = WritableStream; + exports.WritableStreamDefaultController = WritableStreamDefaultController; + exports.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + +})); +//# sourceMappingURL=ponyfill.js.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.js.map b/node_modules/web-streams-polyfill/dist/ponyfill.js.map new file mode 100644 index 0000000..cb9ef38 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.js","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultController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AAG,SAAS,CAAC;IAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;IAC/C,CAAC;IAED;IAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;IAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,oCAA6B,IAAI,EAAA,wCAAA,CAAwC,CAAC,CAAC;IAC/E;;;;;;;;;;;;;;;;;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.mjs b/node_modules/web-streams-polyfill/dist/ponyfill.mjs new file mode 100644 index 0000000..57fd3b1 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.mjs @@ -0,0 +1,4964 @@ +/** + * @license + * web-streams-polyfill v3.3.2 + * Copyright 2024 Mattias Buelens, Diwank Singh Tomer and other contributors. + * This code is released under the MIT license. + * SPDX-License-Identifier: MIT + */ +/// +var SymbolPolyfill = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? + Symbol : + function (description) { return "Symbol(".concat(description, ")"); }; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +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; +}; + +function noop() { + return undefined; +} + +function typeIsObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +var rethrowAssertionErrorRejection = noop; +function setFunctionName(fn, name) { + try { + Object.defineProperty(fn, 'name', { + value: name, + configurable: true + }); + } + catch (_a) { + // This property is non-configurable in older browsers, so ignore if this throws. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility + } +} + +var originalPromise = Promise; +var originalPromiseThen = Promise.prototype.then; +var originalPromiseReject = Promise.reject.bind(originalPromise); +// https://webidl.spec.whatwg.org/#a-new-promise +function newPromise(executor) { + return new originalPromise(executor); +} +// https://webidl.spec.whatwg.org/#a-promise-resolved-with +function promiseResolvedWith(value) { + return newPromise(function (resolve) { return resolve(value); }); +} +// https://webidl.spec.whatwg.org/#a-promise-rejected-with +function promiseRejectedWith(reason) { + return originalPromiseReject(reason); +} +function PerformPromiseThen(promise, onFulfilled, onRejected) { + // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an + // approximation. + return originalPromiseThen.call(promise, onFulfilled, onRejected); +} +// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned +// from that handler. To prevent this, return null instead of void from all handlers. +// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it +function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), undefined, rethrowAssertionErrorRejection); +} +function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); +} +function uponRejection(promise, onRejected) { + uponPromise(promise, undefined, onRejected); +} +function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); +} +function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection); +} +var _queueMicrotask = function (callback) { + if (typeof queueMicrotask === 'function') { + _queueMicrotask = queueMicrotask; + } + else { + var resolvedPromise_1 = promiseResolvedWith(undefined); + _queueMicrotask = function (cb) { return PerformPromiseThen(resolvedPromise_1, cb); }; + } + return _queueMicrotask(callback); +}; +function reflectCall(F, V, args) { + if (typeof F !== 'function') { + throw new TypeError('Argument is not a function'); + } + return Function.prototype.apply.call(F, V, args); +} +function promiseCall(F, V, args) { + try { + return promiseResolvedWith(reflectCall(F, V, args)); + } + catch (value) { + return promiseRejectedWith(value); + } +} + +// Original from Chromium +// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js +var QUEUE_MAX_ARRAY_SIZE = 16384; +/** + * Simple queue structure. + * + * Avoids scalability issues with using a packed array directly by using + * multiple arrays in a linked list and keeping the array size bounded. + */ +var SimpleQueue = /** @class */ (function () { + function SimpleQueue() { + this._cursor = 0; + this._size = 0; + // _front and _back are always defined. + this._front = { + _elements: [], + _next: undefined + }; + this._back = this._front; + // The cursor is used to avoid calling Array.shift(). + // It contains the index of the front element of the array inside the + // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE). + this._cursor = 0; + // When there is only one node, size === elements.length - cursor. + this._size = 0; + } + Object.defineProperty(SimpleQueue.prototype, "length", { + get: function () { + return this._size; + }, + enumerable: false, + configurable: true + }); + // For exception safety, this method is structured in order: + // 1. Read state + // 2. Calculate required state mutations + // 3. Perform state mutations + SimpleQueue.prototype.push = function (element) { + var oldBack = this._back; + var newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: undefined + }; + } + // push() is the mutation most likely to throw an exception, so it + // goes first. + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + }; + // Like push(), shift() follows the read -> calculate -> mutate pattern for + // exception safety. + SimpleQueue.prototype.shift = function () { // must not be called on an empty queue + var oldFront = this._front; + var newFront = oldFront; + var oldCursor = this._cursor; + var newCursor = oldCursor + 1; + var elements = oldFront._elements; + var element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + // No mutations before this point. + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + // Permit shifted element to be garbage collected. + elements[oldCursor] = undefined; + return element; + }; + // The tricky thing about forEach() is that it can be called + // re-entrantly. The queue may be mutated inside the callback. It is easy to + // see that push() within the callback has no negative effects since the end + // of the queue is checked for on every iteration. If shift() is called + // repeatedly within the callback then the next iteration may return an + // element that has been removed. In this case the callback will be called + // with undefined values until we either "catch up" with elements that still + // exist or reach the back of the queue. + SimpleQueue.prototype.forEach = function (callback) { + var i = this._cursor; + var node = this._front; + var elements = node._elements; + while (i !== elements.length || node._next !== undefined) { + if (i === elements.length) { + node = node._next; + elements = node._elements; + i = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i]); + ++i; + } + }; + // Return the element that would be returned if shift() was called now, + // without modifying the queue. + SimpleQueue.prototype.peek = function () { // must not be called on an empty queue + var front = this._front; + var cursor = this._cursor; + return front._elements[cursor]; + }; + return SimpleQueue; +}()); + +var AbortSteps = SymbolPolyfill('[[AbortSteps]]'); +var ErrorSteps = SymbolPolyfill('[[ErrorSteps]]'); +var CancelSteps = SymbolPolyfill('[[CancelSteps]]'); +var PullSteps = SymbolPolyfill('[[PullSteps]]'); +var ReleaseSteps = SymbolPolyfill('[[ReleaseSteps]]'); + +function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === 'readable') { + defaultReaderClosedPromiseInitialize(reader); + } + else if (stream._state === 'closed') { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } + else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } +} +// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state +// check. +function ReadableStreamReaderGenericCancel(reader, reason) { + var stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); +} +function ReadableStreamReaderGenericRelease(reader) { + var stream = reader._ownerReadableStream; + if (stream._state === 'readable') { + defaultReaderClosedPromiseReject(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")); + } + stream._readableStreamController[ReleaseSteps](); + stream._reader = undefined; + reader._ownerReadableStream = undefined; +} +// Helper functions for the readers. +function readerLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released reader'); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise(function (resolve, reject) { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); +} +function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); +} +function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); +} +function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} +function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); +} +function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === undefined) { + return; + } + reader._closedPromise_resolve(undefined); + reader._closedPromise_resolve = undefined; + reader._closedPromise_reject = undefined; +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill +var NumberIsFinite = Number.isFinite || function (x) { + return typeof x === 'number' && isFinite(x); +}; + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill +var MathTrunc = Math.trunc || function (v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); +}; + +// https://heycam.github.io/webidl/#idl-dictionaries +function isDictionary(x) { + return typeof x === 'object' || typeof x === 'function'; +} +function assertDictionary(obj, context) { + if (obj !== undefined && !isDictionary(obj)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +// https://heycam.github.io/webidl/#idl-callback-functions +function assertFunction(x, context) { + if (typeof x !== 'function') { + throw new TypeError("".concat(context, " is not a function.")); + } +} +// https://heycam.github.io/webidl/#idl-object +function isObject(x) { + return (typeof x === 'object' && x !== null) || typeof x === 'function'; +} +function assertObject(x, context) { + if (!isObject(x)) { + throw new TypeError("".concat(context, " is not an object.")); + } +} +function assertRequiredArgument(x, position, context) { + if (x === undefined) { + throw new TypeError("Parameter ".concat(position, " is required in '").concat(context, "'.")); + } +} +function assertRequiredField(x, field, context) { + if (x === undefined) { + throw new TypeError("".concat(field, " is required in '").concat(context, "'.")); + } +} +// https://heycam.github.io/webidl/#idl-unrestricted-double +function convertUnrestrictedDouble(value) { + return Number(value); +} +function censorNegativeZero(x) { + return x === 0 ? 0 : x; +} +function integerPart(x) { + return censorNegativeZero(MathTrunc(x)); +} +// https://heycam.github.io/webidl/#idl-unsigned-long-long +function convertUnsignedLongLongWithEnforceRange(value, context) { + var lowerBound = 0; + var upperBound = Number.MAX_SAFE_INTEGER; + var x = Number(value); + x = censorNegativeZero(x); + if (!NumberIsFinite(x)) { + throw new TypeError("".concat(context, " is not a finite number")); + } + x = integerPart(x); + if (x < lowerBound || x > upperBound) { + throw new TypeError("".concat(context, " is outside the accepted range of ").concat(lowerBound, " to ").concat(upperBound, ", inclusive")); + } + if (!NumberIsFinite(x) || x === 0) { + return 0; + } + // TODO Use BigInt if supported? + // let xBigInt = BigInt(integerPart(x)); + // xBigInt = BigInt.asUintN(64, xBigInt); + // return Number(xBigInt); + return x; +} + +function assertReadableStream(x, context) { + if (!IsReadableStream(x)) { + throw new TypeError("".concat(context, " is not a ReadableStream.")); + } +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); +} +function ReadableStreamFulfillReadRequest(stream, chunk, done) { + var reader = stream._reader; + var readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } + else { + readRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; +} +function ReadableStreamHasDefaultReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamDefaultReader = /** @class */ (function () { + function ReadableStreamDefaultReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamDefaultReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamDefaultReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + ReadableStreamDefaultReader.prototype.read = function () { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException('read')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function () { return resolvePromise({ value: undefined, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamDefaultReader.prototype.releaseLock = function () { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamDefaultReaderRelease(this); + }; + return ReadableStreamDefaultReader; +}()); +Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamDefaultReader.prototype.read, 'read'); +setFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamDefaultReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) { + return false; + } + return x instanceof ReadableStreamDefaultReader; +} +function ReadableStreamDefaultReaderRead(reader, readRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'closed') { + readRequest._closeSteps(); + } + else if (stream._state === 'errored') { + readRequest._errorSteps(stream._storedError); + } + else { + stream._readableStreamController[PullSteps](readRequest); + } +} +function ReadableStreamDefaultReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamDefaultReaderErrorReadRequests(reader, e); +} +function ReadableStreamDefaultReaderErrorReadRequests(reader, e) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamDefaultReader. +function defaultReaderBrandCheckException(name) { + return new TypeError("ReadableStreamDefaultReader.prototype.".concat(name, " can only be used on a ReadableStreamDefaultReader")); +} + +/// +var _a; +var AsyncIteratorPrototype; +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + // We're running inside a ES2018+ environment, but we're compiling to an older syntax. + // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it. + AsyncIteratorPrototype = (_a = {}, + // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( ) + // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator + _a[SymbolPolyfill.asyncIterator] = function () { + return this; + }, + _a); + Object.defineProperty(AsyncIteratorPrototype, SymbolPolyfill.asyncIterator, { enumerable: false }); +} + +/// +var ReadableStreamAsyncIteratorImpl = /** @class */ (function () { + function ReadableStreamAsyncIteratorImpl(reader, preventCancel) { + this._ongoingPromise = undefined; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + ReadableStreamAsyncIteratorImpl.prototype.next = function () { + var _this = this; + var nextSteps = function () { return _this._nextSteps(); }; + this._ongoingPromise = this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : + nextSteps(); + return this._ongoingPromise; + }; + ReadableStreamAsyncIteratorImpl.prototype.return = function (value) { + var _this = this; + var returnSteps = function () { return _this._returnSteps(value); }; + return this._ongoingPromise ? + transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : + returnSteps(); + }; + ReadableStreamAsyncIteratorImpl.prototype._nextSteps = function () { + var _this = this; + if (this._isFinished) { + return Promise.resolve({ value: undefined, done: true }); + } + var reader = this._reader; + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readRequest = { + _chunkSteps: function (chunk) { + _this._ongoingPromise = undefined; + // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test. + // FIXME Is this a bug in the specification, or in the test? + _queueMicrotask(function () { return resolvePromise({ value: chunk, done: false }); }); + }, + _closeSteps: function () { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: undefined, done: true }); + }, + _errorSteps: function (reason) { + _this._ongoingPromise = undefined; + _this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + }; + ReadableStreamAsyncIteratorImpl.prototype._returnSteps = function (value) { + if (this._isFinished) { + return Promise.resolve({ value: value, done: true }); + } + this._isFinished = true; + var reader = this._reader; + if (!this._preventCancel) { + var result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, function () { return ({ value: value, done: true }); }); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value: value, done: true }); + }; + return ReadableStreamAsyncIteratorImpl; +}()); +var ReadableStreamAsyncIteratorPrototype = { + next: function () { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next')); + } + return this._asyncIteratorImpl.next(); + }, + return: function (value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return')); + } + return this._asyncIteratorImpl.return(value); + } +}; +if (AsyncIteratorPrototype !== undefined) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); +} +// Abstract operations for the ReadableStream. +function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + var reader = AcquireReadableStreamDefaultReader(stream); + var impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + var iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; +} +function IsReadableStreamAsyncIterator(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) { + return false; + } + try { + // noinspection SuspiciousTypeOfGuard + return x._asyncIteratorImpl instanceof + ReadableStreamAsyncIteratorImpl; + } + catch (_a) { + return false; + } +} +// Helper functions for the ReadableStream. +function streamAsyncIteratorBrandCheckException(name) { + return new TypeError("ReadableStreamAsyncIterator.".concat(name, " can only be used on a ReadableSteamAsyncIterator")); +} + +/// +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill +var NumberIsNaN = Number.isNaN || function (x) { + // eslint-disable-next-line no-self-compare + return x !== x; +}; + +function CreateArrayFromList(elements) { + // We use arrays to represent lists, so this is basically a no-op. + // Do a slice though just in case we happen to depend on the unique-ness. + return elements.slice(); +} +function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); +} +var TransferArrayBuffer = function (O) { + if (typeof O.transfer === 'function') { + TransferArrayBuffer = function (buffer) { return buffer.transfer(); }; + } + else if (typeof structuredClone === 'function') { + TransferArrayBuffer = function (buffer) { return structuredClone(buffer, { transfer: [buffer] }); }; + } + else { + // Not implemented correctly + TransferArrayBuffer = function (buffer) { return buffer; }; + } + return TransferArrayBuffer(O); +}; +var IsDetachedBuffer = function (O) { + if (typeof O.detached === 'boolean') { + IsDetachedBuffer = function (buffer) { return buffer.detached; }; + } + else { + // Not implemented correctly + IsDetachedBuffer = function (buffer) { return buffer.byteLength === 0; }; + } + return IsDetachedBuffer(O); +}; +function ArrayBufferSlice(buffer, begin, end) { + // ArrayBuffer.prototype.slice is not available on IE10 + // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice + if (buffer.slice) { + return buffer.slice(begin, end); + } + var length = end - begin; + var slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; +} +function GetMethod(receiver, prop) { + var func = receiver[prop]; + if (func === undefined || func === null) { + return undefined; + } + if (typeof func !== 'function') { + throw new TypeError("".concat(String(prop), " is not a function")); + } + return func; +} +function CreateAsyncFromSyncIterator(syncIteratorRecord) { + // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%, + // we use yield* inside an async generator function to achieve the same result. + var _a; + // Wrap the sync iterator inside a sync iterable, so we can use it with yield*. + var syncIterable = (_a = {}, + _a[SymbolPolyfill.iterator] = function () { return syncIteratorRecord.iterator; }, + _a); + // Create an async generator function and immediately invoke it. + var asyncIterator = (function () { + return __asyncGenerator(this, arguments, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [5 /*yield**/, __values(__asyncDelegator(__asyncValues(syncIterable)))]; + case 1: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 2: return [4 /*yield*/, __await.apply(void 0, [_a.sent()])]; + case 3: return [2 /*return*/, _a.sent()]; + } + }); + }); + }()); + // Return as an async iterator record. + var nextMethod = asyncIterator.next; + return { iterator: asyncIterator, nextMethod: nextMethod, done: false }; +} +function GetIterator(obj, hint, method) { + if (hint === void 0) { hint = 'sync'; } + if (method === undefined) { + if (hint === 'async') { + method = GetMethod(obj, SymbolPolyfill.asyncIterator); + if (method === undefined) { + var syncMethod = GetMethod(obj, SymbolPolyfill.iterator); + var syncIteratorRecord = GetIterator(obj, 'sync', syncMethod); + return CreateAsyncFromSyncIterator(syncIteratorRecord); + } + } + else { + method = GetMethod(obj, SymbolPolyfill.iterator); + } + } + if (method === undefined) { + throw new TypeError('The object is not iterable'); + } + var iterator = reflectCall(method, obj, []); + if (!typeIsObject(iterator)) { + throw new TypeError('The iterator method must return an object'); + } + var nextMethod = iterator.next; + return { iterator: iterator, nextMethod: nextMethod, done: false }; +} +function IteratorNext(iteratorRecord) { + var result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []); + if (!typeIsObject(result)) { + throw new TypeError('The iterator.next() method must return an object'); + } + return result; +} +function IteratorComplete(iterResult) { + return Boolean(iterResult.done); +} +function IteratorValue(iterResult) { + return iterResult.value; +} + +function IsNonNegativeNumber(v) { + if (typeof v !== 'number') { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; +} +function CloneAsUint8Array(O) { + var buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); +} + +function DequeueValue(container) { + var pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; +} +function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError('Size must be a finite, non-NaN, non-negative number.'); + } + container._queue.push({ value: value, size: size }); + container._queueTotalSize += size; +} +function PeekQueueValue(container) { + var pair = container._queue.peek(); + return pair.value; +} +function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; +} + +function isDataViewConstructor(ctor) { + return ctor === DataView; +} +function isDataView(view) { + return isDataViewConstructor(view.constructor); +} +function arrayBufferViewElementSize(ctor) { + if (isDataViewConstructor(ctor)) { + return 1; + } + return ctor.BYTES_PER_ELEMENT; +} + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +var ReadableStreamBYOBRequest = /** @class */ (function () { + function ReadableStreamBYOBRequest() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamBYOBRequest.prototype, "view", { + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get: function () { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('view'); + } + return this._view; + }, + enumerable: false, + configurable: true + }); + ReadableStreamBYOBRequest.prototype.respond = function (bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respond'); + } + assertRequiredArgument(bytesWritten, 1, 'respond'); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter'); + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(this._view.buffer)) { + throw new TypeError("The BYOB request's buffer has been detached and so cannot be used as a response"); + } + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + }; + ReadableStreamBYOBRequest.prototype.respondWithNewView = function (view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException('respondWithNewView'); + } + assertRequiredArgument(view, 1, 'respondWithNewView'); + if (!ArrayBuffer.isView(view)) { + throw new TypeError('You can only respond with array buffer views'); + } + if (this._associatedReadableByteStreamController === undefined) { + throw new TypeError('This BYOB request has been invalidated'); + } + if (IsDetachedBuffer(view.buffer)) { + throw new TypeError('The given view\'s buffer has been detached and so cannot be used as a response'); + } + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + }; + return ReadableStreamBYOBRequest; +}()); +Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond'); +setFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBRequest', + configurable: true + }); +} +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +var ReadableByteStreamController = /** @class */ (function () { + function ReadableByteStreamController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableByteStreamController.prototype, "byobRequest", { + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('byobRequest'); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ReadableByteStreamController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('desiredSize'); + } + return ReadableByteStreamControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableByteStreamController.prototype.close = function () { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('close'); + } + if (this._closeRequested) { + throw new TypeError('The stream has already been closed; do not close it again!'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be closed")); + } + ReadableByteStreamControllerClose(this); + }; + ReadableByteStreamController.prototype.enqueue = function (chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('enqueue'); + } + assertRequiredArgument(chunk, 1, 'enqueue'); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError('chunk must be an array buffer view'); + } + if (chunk.byteLength === 0) { + throw new TypeError('chunk must have non-zero byteLength'); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError("chunk's buffer must have non-zero byteLength"); + } + if (this._closeRequested) { + throw new TypeError('stream is closed or draining'); + } + var state = this._controlledReadableByteStream._state; + if (state !== 'readable') { + throw new TypeError("The stream (in ".concat(state, " state) is not in the readable state and cannot be enqueued to")); + } + ReadableByteStreamControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableByteStreamController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException('error'); + } + ReadableByteStreamControllerError(this, e); + }; + /** @internal */ + ReadableByteStreamController.prototype[CancelSteps] = function (reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableByteStreamController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest); + return; + } + var autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== undefined) { + var buffer = void 0; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } + catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + minimumFill: 1, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: 'default' + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + }; + /** @internal */ + ReadableByteStreamController.prototype[ReleaseSteps] = function () { + if (this._pendingPullIntos.length > 0) { + var firstPullInto = this._pendingPullIntos.peek(); + firstPullInto.readerType = 'none'; + this._pendingPullIntos = new SimpleQueue(); + this._pendingPullIntos.push(firstPullInto); + } + }; + return ReadableByteStreamController; +}()); +Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableByteStreamController.prototype.close, 'close'); +setFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableByteStreamController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableByteStreamController', + configurable: true + }); +} +// Abstract operations for the ReadableByteStreamController. +function IsReadableByteStreamController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) { + return false; + } + return x instanceof ReadableByteStreamController; +} +function IsReadableStreamBYOBRequest(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) { + return false; + } + return x instanceof ReadableStreamBYOBRequest; +} +function ReadableByteStreamControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + // TODO: Test controller argument + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableByteStreamControllerError(controller, e); + return null; + }); +} +function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); +} +function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + var done = false; + if (stream._state === 'closed') { + done = true; + } + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'default') { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } + else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } +} +function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + var bytesFilled = pullIntoDescriptor.bytesFilled; + var elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); +} +function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer: buffer, byteOffset: byteOffset, byteLength: byteLength }); + controller._queueTotalSize += byteLength; +} +function ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, buffer, byteOffset, byteLength) { + var clonedChunk; + try { + clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength); + } + catch (cloneE) { + ReadableByteStreamControllerError(controller, cloneE); + throw cloneE; + } + ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength); +} +function ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstDescriptor) { + if (firstDescriptor.bytesFilled > 0) { + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, firstDescriptor.buffer, firstDescriptor.byteOffset, firstDescriptor.bytesFilled); + } + ReadableByteStreamControllerShiftPendingPullInto(controller); +} +function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + var maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + var maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + var totalBytesToCopyRemaining = maxBytesToCopy; + var ready = false; + var remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize; + var maxAlignedBytes = maxBytesFilled - remainderBytes; + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + var queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + var headOfQueue = queue.peek(); + var bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + var destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } + else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; +} +function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; +} +function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } + else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } +} +function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = undefined; + controller._byobRequest._view = null; + controller._byobRequest = null; +} +function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller) { + var reader = controller._controlledReadableByteStream._reader; + while (reader._readRequests.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + var readRequest = reader._readRequests.shift(); + ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest); + } +} +function ReadableByteStreamControllerPullInto(controller, view, min, readIntoRequest) { + var stream = controller._controlledReadableByteStream; + var ctor = view.constructor; + var elementSize = arrayBufferViewElementSize(ctor); + var byteOffset = view.byteOffset, byteLength = view.byteLength; + var minimumFill = min * elementSize; + var buffer; + try { + buffer = TransferArrayBuffer(view.buffer); + } + catch (e) { + readIntoRequest._errorSteps(e); + return; + } + var pullIntoDescriptor = { + buffer: buffer, + bufferByteLength: buffer.byteLength, + byteOffset: byteOffset, + byteLength: byteLength, + bytesFilled: 0, + minimumFill: minimumFill, + elementSize: elementSize, + viewConstructor: ctor, + readerType: 'byob' + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + // No ReadableByteStreamControllerCallPullIfNeeded() call since: + // - No change happens on desiredSize + // - The source has already been notified of that there's at least 1 pending read(view) + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === 'closed') { + var emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + var filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + readIntoRequest._errorSteps(e); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + if (firstDescriptor.readerType === 'none') { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + var pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } +} +function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + return; + } + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) { + // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head + // of the queue, so the underlying source can keep filling it. + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + var remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + var end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor.buffer, end - remainderSize, remainderSize); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); +} +function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor); + } + else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerShiftPendingPullInto(controller) { + var descriptor = controller._pendingPullIntos.shift(); + return descriptor; +} +function ReadableByteStreamControllerShouldCallPull(controller) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +// A client of ReadableByteStreamController may use these functions directly to bypass state check. +function ReadableByteStreamControllerClose(controller) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) { + var e = new TypeError('Insufficient bytes to fill elements in the given buffer'); + ReadableByteStreamControllerError(controller, e); + throw e; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); +} +function ReadableByteStreamControllerEnqueue(controller, chunk) { + var stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== 'readable') { + return; + } + var buffer = chunk.buffer, byteOffset = chunk.byteOffset, byteLength = chunk.byteLength; + if (IsDetachedBuffer(buffer)) { + throw new TypeError('chunk\'s buffer is detached and so cannot be enqueued'); + } + var transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + var firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) { + throw new TypeError('The BYOB request\'s buffer has been detached and so cannot be filled with an enqueued chunk'); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + if (firstPendingPullInto.readerType === 'none') { + ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto); + } + } + if (ReadableStreamHasDefaultReader(stream)) { + ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller); + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + var transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } + else if (ReadableStreamHasBYOBReader(stream)) { + // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully. + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); +} +function ReadableByteStreamControllerError(controller, e) { + var stream = controller._controlledReadableByteStream; + if (stream._state !== 'readable') { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest) { + var entry = controller._queue.shift(); + controller._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(controller); + var view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); +} +function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + var byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; +} +function ReadableByteStreamControllerGetDesiredSize(controller) { + var state = controller._controlledReadableByteStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +function ReadableByteStreamControllerRespond(controller, bytesWritten) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (bytesWritten !== 0) { + throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream'); + } + } + else { + if (bytesWritten === 0) { + throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream'); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError('bytesWritten out of range'); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); +} +function ReadableByteStreamControllerRespondWithNewView(controller, view) { + var firstDescriptor = controller._pendingPullIntos.peek(); + var state = controller._controlledReadableByteStream._state; + if (state === 'closed') { + if (view.byteLength !== 0) { + throw new TypeError('The view\'s length must be 0 when calling respondWithNewView() on a closed stream'); + } + } + else { + if (view.byteLength === 0) { + throw new TypeError('The view\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError('The region specified by view does not match byobRequest'); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError('The buffer of view has different capacity than byobRequest'); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError('The region specified by view is larger than byobRequest'); + } + var viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); +} +function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableByteStreamControllerError(controller, r); + return null; + }); +} +function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + var controller = Object.create(ReadableByteStreamController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingByteSource.start !== undefined) { + startAlgorithm = function () { return underlyingByteSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingByteSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingByteSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingByteSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingByteSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + var autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError('autoAllocateChunkSize must be greater than 0'); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); +} +function SetUpReadableStreamBYOBRequest(request, controller, view) { + request._associatedReadableByteStreamController = controller; + request._view = view; +} +// Helper functions for the ReadableStreamBYOBRequest. +function byobRequestBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBRequest.prototype.".concat(name, " can only be used on a ReadableStreamBYOBRequest")); +} +// Helper functions for the ReadableByteStreamController. +function byteStreamControllerBrandCheckException(name) { + return new TypeError("ReadableByteStreamController.prototype.".concat(name, " can only be used on a ReadableByteStreamController")); +} + +function convertReaderOptions(options, context) { + assertDictionary(options, context); + var mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, "".concat(context, " has member 'mode' that")) + }; +} +function convertReadableStreamReaderMode(mode, context) { + mode = "".concat(mode); + if (mode !== 'byob') { + throw new TypeError("".concat(context, " '").concat(mode, "' is not a valid enumeration value for ReadableStreamReaderMode")); + } + return mode; +} +function convertByobReadOptions(options, context) { + var _a; + assertDictionary(options, context); + var min = (_a = options === null || options === void 0 ? void 0 : options.min) !== null && _a !== void 0 ? _a : 1; + return { + min: convertUnsignedLongLongWithEnforceRange(min, "".concat(context, " has member 'min' that")) + }; +} + +// Abstract operations for the ReadableStream. +function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); +} +// ReadableStream API exposed for controllers. +function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); +} +function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + var reader = stream._reader; + var readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } + else { + readIntoRequest._chunkSteps(chunk); + } +} +function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; +} +function ReadableStreamHasBYOBReader(stream) { + var reader = stream._reader; + if (reader === undefined) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +var ReadableStreamBYOBReader = /** @class */ (function () { + function ReadableStreamBYOBReader(stream) { + assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader'); + assertReadableStream(stream, 'First parameter'); + if (IsReadableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive reading by another reader'); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' + + 'source'); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + Object.defineProperty(ReadableStreamBYOBReader.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get: function () { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + ReadableStreamBYOBReader.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('cancel')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('cancel')); + } + return ReadableStreamReaderGenericCancel(this, reason); + }; + ReadableStreamBYOBReader.prototype.read = function (view, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException('read')); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError('view must be an array buffer view')); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError('view must have non-zero byteLength')); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError("view's buffer must have non-zero byteLength")); + } + if (IsDetachedBuffer(view.buffer)) { + return promiseRejectedWith(new TypeError('view\'s buffer has been detached')); + } + var options; + try { + options = convertByobReadOptions(rawOptions, 'options'); + } + catch (e) { + return promiseRejectedWith(e); + } + var min = options.min; + if (min === 0) { + return promiseRejectedWith(new TypeError('options.min must be greater than 0')); + } + if (!isDataView(view)) { + if (min > view.length) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s length')); + } + } + else if (min > view.byteLength) { + return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\'s byteLength')); + } + if (this._ownerReadableStream === undefined) { + return promiseRejectedWith(readerLockException('read from')); + } + var resolvePromise; + var rejectPromise; + var promise = newPromise(function (resolve, reject) { + resolvePromise = resolve; + rejectPromise = reject; + }); + var readIntoRequest = { + _chunkSteps: function (chunk) { return resolvePromise({ value: chunk, done: false }); }, + _closeSteps: function (chunk) { return resolvePromise({ value: chunk, done: true }); }, + _errorSteps: function (e) { return rejectPromise(e); } + }; + ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest); + return promise; + }; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + ReadableStreamBYOBReader.prototype.releaseLock = function () { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException('releaseLock'); + } + if (this._ownerReadableStream === undefined) { + return; + } + ReadableStreamBYOBReaderRelease(this); + }; + return ReadableStreamBYOBReader; +}()); +Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } +}); +setFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel'); +setFunctionName(ReadableStreamBYOBReader.prototype.read, 'read'); +setFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamBYOBReader', + configurable: true + }); +} +// Abstract operations for the readers. +function IsReadableStreamBYOBReader(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) { + return false; + } + return x instanceof ReadableStreamBYOBReader; +} +function ReadableStreamBYOBReaderRead(reader, view, min, readIntoRequest) { + var stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === 'errored') { + readIntoRequest._errorSteps(stream._storedError); + } + else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, min, readIntoRequest); + } +} +function ReadableStreamBYOBReaderRelease(reader) { + ReadableStreamReaderGenericRelease(reader); + var e = new TypeError('Reader was released'); + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); +} +function ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._errorSteps(e); + }); +} +// Helper functions for the ReadableStreamBYOBReader. +function byobReaderBrandCheckException(name) { + return new TypeError("ReadableStreamBYOBReader.prototype.".concat(name, " can only be used on a ReadableStreamBYOBReader")); +} + +function ExtractHighWaterMark(strategy, defaultHWM) { + var highWaterMark = strategy.highWaterMark; + if (highWaterMark === undefined) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError('Invalid highWaterMark'); + } + return highWaterMark; +} +function ExtractSizeAlgorithm(strategy) { + var size = strategy.size; + if (!size) { + return function () { return 1; }; + } + return size; +} + +function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + var size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark), + size: size === undefined ? undefined : convertQueuingStrategySize(size, "".concat(context, " has member 'size' that")) + }; +} +function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return function (chunk) { return convertUnrestrictedDouble(fn(chunk)); }; +} + +function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + var abort = original === null || original === void 0 ? void 0 : original.abort; + var close = original === null || original === void 0 ? void 0 : original.close; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + var write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === undefined ? + undefined : + convertUnderlyingSinkAbortCallback(abort, original, "".concat(context, " has member 'abort' that")), + close: close === undefined ? + undefined : + convertUnderlyingSinkCloseCallback(close, original, "".concat(context, " has member 'close' that")), + start: start === undefined ? + undefined : + convertUnderlyingSinkStartCallback(start, original, "".concat(context, " has member 'start' that")), + write: write === undefined ? + undefined : + convertUnderlyingSinkWriteCallback(write, original, "".concat(context, " has member 'write' that")), + type: type + }; +} +function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return function () { return promiseCall(fn, original, []); }; +} +function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} + +function assertWritableStream(x, context) { + if (!IsWritableStream(x)) { + throw new TypeError("".concat(context, " is not a WritableStream.")); + } +} + +function isAbortSignal(value) { + if (typeof value !== 'object' || value === null) { + return false; + } + try { + return typeof value.aborted === 'boolean'; + } + catch (_a) { + // AbortSignal.prototype.aborted throws if its brand check fails + return false; + } +} +var supportsAbortController = typeof AbortController === 'function'; +/** + * Construct a new AbortController, if supported by the platform. + * + * @internal + */ +function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return undefined; +} + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +var WritableStream = /** @class */ (function () { + function WritableStream(rawUnderlyingSink, rawStrategy) { + if (rawUnderlyingSink === void 0) { rawUnderlyingSink = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSink === undefined) { + rawUnderlyingSink = null; + } + else { + assertObject(rawUnderlyingSink, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter'); + InitializeWritableStream(this); + var type = underlyingSink.type; + if (type !== undefined) { + throw new RangeError('Invalid type is specified'); + } + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + Object.defineProperty(WritableStream.prototype, "locked", { + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get: function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('locked'); + } + return IsWritableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + WritableStream.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('abort')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer')); + } + return WritableStreamAbort(this, reason); + }; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + WritableStream.prototype.close = function () { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2('close')); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer')); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamClose(this); + }; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + WritableStream.prototype.getWriter = function () { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2('getWriter'); + } + return AcquireWritableStreamDefaultWriter(this); + }; + return WritableStream; +}()); +Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(WritableStream.prototype.abort, 'abort'); +setFunctionName(WritableStream.prototype.close, 'close'); +setFunctionName(WritableStream.prototype.getWriter, 'getWriter'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStream', + configurable: true + }); +} +// Abstract operations for the WritableStream. +function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); +} +// Throws if and only if startAlgorithm throws. +function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + var controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +function InitializeWritableStream(stream) { + stream._state = 'writable'; + // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is + // 'erroring' or 'errored'. May be set to an undefined value. + stream._storedError = undefined; + stream._writer = undefined; + // Initialize to undefined first because the constructor of the controller checks this + // variable to validate the caller. + stream._writableStreamController = undefined; + // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data + // producer without waiting for the queued writes to finish. + stream._writeRequests = new SimpleQueue(); + // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents + // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here. + stream._inFlightWriteRequest = undefined; + // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer + // has been detached. + stream._closeRequest = undefined; + // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it + // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here. + stream._inFlightCloseRequest = undefined; + // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached. + stream._pendingAbortRequest = undefined; + // The backpressure signal set by the controller. + stream._backpressure = false; +} +function IsWritableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) { + return false; + } + return x instanceof WritableStream; +} +function IsWritableStreamLocked(stream) { + if (stream._writer === undefined) { + return false; + } + return true; +} +function WritableStreamAbort(stream, reason) { + var _a; + if (stream._state === 'closed' || stream._state === 'errored') { + return promiseResolvedWith(undefined); + } + stream._writableStreamController._abortReason = reason; + (_a = stream._writableStreamController._abortController) === null || _a === void 0 ? void 0 : _a.abort(reason); + // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring', + // but it doesn't know that signaling abort runs author code that might have changed the state. + // Widen the type again by casting to WritableStreamState. + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseResolvedWith(undefined); + } + if (stream._pendingAbortRequest !== undefined) { + return stream._pendingAbortRequest._promise; + } + var wasAlreadyErroring = false; + if (state === 'erroring') { + wasAlreadyErroring = true; + // reason will not be used, so don't keep a reference to it. + reason = undefined; + } + var promise = newPromise(function (resolve, reject) { + stream._pendingAbortRequest = { + _promise: undefined, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; +} +function WritableStreamClose(stream) { + var state = stream._state; + if (state === 'closed' || state === 'errored') { + return promiseRejectedWith(new TypeError("The stream (in ".concat(state, " state) is not in the writable state and cannot be closed"))); + } + var promise = newPromise(function (resolve, reject) { + var closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + var writer = stream._writer; + if (writer !== undefined && stream._backpressure && state === 'writable') { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; +} +// WritableStream API exposed for controllers. +function WritableStreamAddWriteRequest(stream) { + var promise = newPromise(function (resolve, reject) { + var writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; +} +function WritableStreamDealWithRejection(stream, error) { + var state = stream._state; + if (state === 'writable') { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); +} +function WritableStreamStartErroring(stream, reason) { + var controller = stream._writableStreamController; + stream._state = 'erroring'; + stream._storedError = reason; + var writer = stream._writer; + if (writer !== undefined) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } +} +function WritableStreamFinishErroring(stream) { + stream._state = 'errored'; + stream._writableStreamController[ErrorSteps](); + var storedError = stream._storedError; + stream._writeRequests.forEach(function (writeRequest) { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === undefined) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = undefined; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + var promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, function () { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }, function (reason) { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return null; + }); +} +function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(undefined); + stream._inFlightWriteRequest = undefined; +} +function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = undefined; + WritableStreamDealWithRejection(stream, error); +} +function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(undefined); + stream._inFlightCloseRequest = undefined; + var state = stream._state; + if (state === 'erroring') { + // The error was too late to do anything, so it is ignored. + stream._storedError = undefined; + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = undefined; + } + } + stream._state = 'closed'; + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseResolve(writer); + } +} +function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = undefined; + // Never execute sink abort() after sink close(). + if (stream._pendingAbortRequest !== undefined) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = undefined; + } + WritableStreamDealWithRejection(stream, error); +} +// TODO(ricea): Fix alphabetical order. +function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) { + return false; + } + return true; +} +function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = undefined; +} +function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); +} +function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== undefined) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = undefined; + } + var writer = stream._writer; + if (writer !== undefined) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } +} +function WritableStreamUpdateBackpressure(stream, backpressure) { + var writer = stream._writer; + if (writer !== undefined && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } + else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +var WritableStreamDefaultWriter = /** @class */ (function () { + function WritableStreamDefaultWriter(stream) { + assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter'); + assertWritableStream(stream, 'First parameter'); + if (IsWritableStreamLocked(stream)) { + throw new TypeError('This stream has already been locked for exclusive writing by another writer'); + } + this._ownerWritableStream = stream; + stream._writer = this; + var state = stream._state; + if (state === 'writable') { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } + else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'erroring') { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } + else if (state === 'closed') { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } + else { + var storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + Object.defineProperty(WritableStreamDefaultWriter.prototype, "closed", { + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('closed')); + } + return this._closedPromise; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "desiredSize", { + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('desiredSize'); + } + if (this._ownerWritableStream === undefined) { + throw defaultWriterLockException('desiredSize'); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultWriter.prototype, "ready", { + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get: function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('ready')); + } + return this._readyPromise; + }, + enumerable: false, + configurable: true + }); + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + WritableStreamDefaultWriter.prototype.abort = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('abort')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('abort')); + } + return WritableStreamDefaultWriterAbort(this, reason); + }; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + WritableStreamDefaultWriter.prototype.close = function () { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('close')); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return promiseRejectedWith(defaultWriterLockException('close')); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError('Cannot close an already-closing stream')); + } + return WritableStreamDefaultWriterClose(this); + }; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + WritableStreamDefaultWriter.prototype.releaseLock = function () { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException('releaseLock'); + } + var stream = this._ownerWritableStream; + if (stream === undefined) { + return; + } + WritableStreamDefaultWriterRelease(this); + }; + WritableStreamDefaultWriter.prototype.write = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException('write')); + } + if (this._ownerWritableStream === undefined) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + return WritableStreamDefaultWriterWrite(this, chunk); + }; + return WritableStreamDefaultWriter; +}()); +Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } +}); +setFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort'); +setFunctionName(WritableStreamDefaultWriter.prototype.close, 'close'); +setFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock'); +setFunctionName(WritableStreamDefaultWriter.prototype.write, 'write'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultWriter', + configurable: true + }); +} +// Abstract operations for the WritableStreamDefaultWriter. +function IsWritableStreamDefaultWriter(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultWriter; +} +// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check. +function WritableStreamDefaultWriterAbort(writer, reason) { + var stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); +} +function WritableStreamDefaultWriterClose(writer) { + var stream = writer._ownerWritableStream; + return WritableStreamClose(stream); +} +function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseResolvedWith(undefined); + } + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); +} +function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === 'pending') { + defaultWriterClosedPromiseReject(writer, error); + } + else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === 'pending') { + defaultWriterReadyPromiseReject(writer, error); + } + else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } +} +function WritableStreamDefaultWriterGetDesiredSize(writer) { + var stream = writer._ownerWritableStream; + var state = stream._state; + if (state === 'errored' || state === 'erroring') { + return null; + } + if (state === 'closed') { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); +} +function WritableStreamDefaultWriterRelease(writer) { + var stream = writer._ownerWritableStream; + var releasedError = new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + // The state transitions to "errored" before the sink abort() method runs, but the writer.closed promise is not + // rejected until afterwards. This means that simply testing state will not work. + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = undefined; + writer._ownerWritableStream = undefined; +} +function WritableStreamDefaultWriterWrite(writer, chunk) { + var stream = writer._ownerWritableStream; + var controller = stream._writableStreamController; + var chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException('write to')); + } + var state = stream._state; + if (state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') { + return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to')); + } + if (state === 'erroring') { + return promiseRejectedWith(stream._storedError); + } + var promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; +} +var closeSentinel = {}; +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +var WritableStreamDefaultController = /** @class */ (function () { + function WritableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(WritableStreamDefaultController.prototype, "abortReason", { + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('abortReason'); + } + return this._abortReason; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(WritableStreamDefaultController.prototype, "signal", { + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get: function () { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('signal'); + } + if (this._abortController === undefined) { + // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`. + // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill, + // so instead we only implement support for `signal` if we find a global `AbortController` constructor. + throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported'); + } + return this._abortController.signal; + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + WritableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2('error'); + } + var state = this._controlledWritableStream._state; + if (state !== 'writable') { + // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so + // just treat it as a no-op. + return; + } + WritableStreamDefaultControllerError(this, e); + }; + /** @internal */ + WritableStreamDefaultController.prototype[AbortSteps] = function (reason) { + var result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + WritableStreamDefaultController.prototype[ErrorSteps] = function () { + ResetQueue(this); + }; + return WritableStreamDefaultController; +}()); +Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'WritableStreamDefaultController', + configurable: true + }); +} +// Abstract operations implementing interface required by the WritableStream. +function IsWritableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) { + return false; + } + return x instanceof WritableStreamDefaultController; +} +function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly. + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._abortReason = undefined; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + var startResult = startAlgorithm(); + var startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, function () { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (r) { + controller._started = true; + WritableStreamDealWithRejection(stream, r); + return null; + }); +} +function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + var controller = Object.create(WritableStreamDefaultController.prototype); + var startAlgorithm; + var writeAlgorithm; + var closeAlgorithm; + var abortAlgorithm; + if (underlyingSink.start !== undefined) { + startAlgorithm = function () { return underlyingSink.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSink.write !== undefined) { + writeAlgorithm = function (chunk) { return underlyingSink.write(chunk, controller); }; + } + else { + writeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.close !== undefined) { + closeAlgorithm = function () { return underlyingSink.close(); }; + } + else { + closeAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSink.abort !== undefined) { + abortAlgorithm = function (reason) { return underlyingSink.abort(reason); }; + } + else { + abortAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); +} +// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls. +function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = undefined; + controller._closeAlgorithm = undefined; + controller._abortAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } +} +function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; +} +function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + var stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); +} +// Abstract operations for the WritableStreamDefaultController. +function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + var stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== undefined) { + return; + } + var state = stream._state; + if (state === 'erroring') { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + var value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } + else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } +} +function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === 'writable') { + WritableStreamDefaultControllerError(controller, error); + } +} +function WritableStreamDefaultControllerProcessClose(controller) { + var stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + var sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, function () { + WritableStreamFinishInFlightClose(stream); + return null; + }, function (reason) { + WritableStreamFinishInFlightCloseWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + var stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + var sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, function () { + WritableStreamFinishInFlightWrite(stream); + var state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') { + var backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + return null; + }, function (reason) { + if (stream._state === 'writable') { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + return null; + }); +} +function WritableStreamDefaultControllerGetBackpressure(controller) { + var desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; +} +// A client of WritableStreamDefaultController may use these functions directly to bypass state check. +function WritableStreamDefaultControllerError(controller, error) { + var stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); +} +// Helper functions for the WritableStream. +function streamBrandCheckException$2(name) { + return new TypeError("WritableStream.prototype.".concat(name, " can only be used on a WritableStream")); +} +// Helper functions for the WritableStreamDefaultController. +function defaultControllerBrandCheckException$2(name) { + return new TypeError("WritableStreamDefaultController.prototype.".concat(name, " can only be used on a WritableStreamDefaultController")); +} +// Helper functions for the WritableStreamDefaultWriter. +function defaultWriterBrandCheckException(name) { + return new TypeError("WritableStreamDefaultWriter.prototype.".concat(name, " can only be used on a WritableStreamDefaultWriter")); +} +function defaultWriterLockException(name) { + return new TypeError('Cannot ' + name + ' a stream using a released writer'); +} +function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise(function (resolve, reject) { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = 'pending'; + }); +} +function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); +} +function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); +} +function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'rejected'; +} +function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === undefined) { + return; + } + writer._closedPromise_resolve(undefined); + writer._closedPromise_resolve = undefined; + writer._closedPromise_reject = undefined; + writer._closedPromiseState = 'resolved'; +} +function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise(function (resolve, reject) { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = 'pending'; +} +function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); +} +function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); +} +function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'rejected'; +} +function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); +} +function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); +} +function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === undefined) { + return; + } + writer._readyPromise_resolve(undefined); + writer._readyPromise_resolve = undefined; + writer._readyPromise_reject = undefined; + writer._readyPromiseState = 'fulfilled'; +} + +/// +function getGlobals() { + if (typeof globalThis !== 'undefined') { + return globalThis; + } + else if (typeof self !== 'undefined') { + return self; + } + else if (typeof global !== 'undefined') { + return global; + } + return undefined; +} +var globals = getGlobals(); + +/// +function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === 'function' || typeof ctor === 'object')) { + return false; + } + if (ctor.name !== 'DOMException') { + return false; + } + try { + new ctor(); + return true; + } + catch (_a) { + return false; + } +} +/** + * Support: + * - Web browsers + * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87) + */ +function getFromGlobal() { + var ctor = globals === null || globals === void 0 ? void 0 : globals.DOMException; + return isDOMExceptionConstructor(ctor) ? ctor : undefined; +} +/** + * Support: + * - All platforms + */ +function createPolyfill() { + // eslint-disable-next-line @typescript-eslint/no-shadow + var ctor = function DOMException(message, name) { + this.message = message || ''; + this.name = name || 'Error'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + setFunctionName(ctor, 'DOMException'); + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true }); + return ctor; +} +// eslint-disable-next-line @typescript-eslint/no-redeclare +var DOMException = getFromGlobal() || createPolyfill(); + +function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + var reader = AcquireReadableStreamDefaultReader(source); + var writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + var shuttingDown = false; + // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown. + var currentWrite = promiseResolvedWith(undefined); + return newPromise(function (resolve, reject) { + var abortAlgorithm; + if (signal !== undefined) { + abortAlgorithm = function () { + var error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError'); + var actions = []; + if (!preventAbort) { + actions.push(function () { + if (dest._state === 'writable') { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(undefined); + }); + } + if (!preventCancel) { + actions.push(function () { + if (source._state === 'readable') { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(undefined); + }); + } + shutdownWithAction(function () { return Promise.all(actions.map(function (action) { return action(); })); }, true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener('abort', abortAlgorithm); + } + // Using reader and writer, read all chunks from this and write them to dest + // - Backpressure must be enforced + // - Shutdown must stop all activity + function pipeLoop() { + return newPromise(function (resolveLoop, rejectLoop) { + function next(done) { + if (done) { + resolveLoop(); + } + else { + // Use `PerformPromiseThen` instead of `uponPromise` to avoid + // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, function () { + return newPromise(function (resolveRead, rejectRead) { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: function (chunk) { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop); + resolveRead(false); + }, + _closeSteps: function () { return resolveRead(true); }, + _errorSteps: rejectRead + }); + }); + }); + } + // Errors must be propagated forward + isOrBecomesErrored(source, reader._closedPromise, function (storedError) { + if (!preventAbort) { + shutdownWithAction(function () { return WritableStreamAbort(dest, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Errors must be propagated backward + isOrBecomesErrored(dest, writer._closedPromise, function (storedError) { + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, storedError); }, true, storedError); + } + else { + shutdown(true, storedError); + } + return null; + }); + // Closing must be propagated forward + isOrBecomesClosed(source, reader._closedPromise, function () { + if (!preventClose) { + shutdownWithAction(function () { return WritableStreamDefaultWriterCloseWithErrorPropagation(writer); }); + } + else { + shutdown(); + } + return null; + }); + // Closing must be propagated backward + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') { + var destClosed_1 = new TypeError('the destination writable stream closed before all data could be piped to it'); + if (!preventCancel) { + shutdownWithAction(function () { return ReadableStreamCancel(source, destClosed_1); }, true, destClosed_1); + } + else { + shutdown(true, destClosed_1); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait + // for that too. + var oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, function () { return oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined; }); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === 'errored') { + action(stream._storedError); + } + else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === 'closed') { + action(); + } + else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } + else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), function () { return finalize(originalIsError, originalError); }, function (newError) { return finalize(true, newError); }); + return null; + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), function () { return finalize(isError, error); }); + } + else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== undefined) { + signal.removeEventListener('abort', abortAlgorithm); + } + if (isError) { + reject(error); + } + else { + resolve(undefined); + } + return null; + } + }); +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +var ReadableStreamDefaultController = /** @class */ (function () { + function ReadableStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(ReadableStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get: function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('desiredSize'); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + }, + enumerable: false, + configurable: true + }); + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + ReadableStreamDefaultController.prototype.close = function () { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('close'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits close'); + } + ReadableStreamDefaultControllerClose(this); + }; + ReadableStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('enqueue'); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError('The stream is not in a state that permits enqueue'); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + ReadableStreamDefaultController.prototype.error = function (e) { + if (e === void 0) { e = undefined; } + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1('error'); + } + ReadableStreamDefaultControllerError(this, e); + }; + /** @internal */ + ReadableStreamDefaultController.prototype[CancelSteps] = function (reason) { + ResetQueue(this); + var result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + }; + /** @internal */ + ReadableStreamDefaultController.prototype[PullSteps] = function (readRequest) { + var stream = this._controlledReadableStream; + if (this._queue.length > 0) { + var chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } + else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } + else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + }; + /** @internal */ + ReadableStreamDefaultController.prototype[ReleaseSteps] = function () { + // Do nothing. + }; + return ReadableStreamDefaultController; +}()); +Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(ReadableStreamDefaultController.prototype.close, 'close'); +setFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(ReadableStreamDefaultController.prototype.error, 'error'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStreamDefaultController', + configurable: true + }); +} +// Abstract operations for the ReadableStreamDefaultController. +function IsReadableStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) { + return false; + } + return x instanceof ReadableStreamDefaultController; +} +function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + var shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + var pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, function () { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + return null; + }, function (e) { + ReadableStreamDefaultControllerError(controller, e); + return null; + }); +} +function ReadableStreamDefaultControllerShouldCallPull(controller) { + var stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + var desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; +} +function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = undefined; + controller._cancelAlgorithm = undefined; + controller._strategySizeAlgorithm = undefined; +} +// A client of ReadableStreamDefaultController may use these functions directly to bypass state check. +function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } +} +function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + var stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } + else { + var chunkSize = void 0; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } + catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } + catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); +} +function ReadableStreamDefaultControllerError(controller, e) { + var stream = controller._controlledReadableStream; + if (stream._state !== 'readable') { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e); +} +function ReadableStreamDefaultControllerGetDesiredSize(controller) { + var state = controller._controlledReadableStream._state; + if (state === 'errored') { + return null; + } + if (state === 'closed') { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; +} +// This is used in the implementation of TransformStream. +function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; +} +function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + var state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === 'readable') { + return true; + } + return false; +} +function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = undefined; + controller._queueTotalSize = undefined; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + var startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), function () { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + return null; + }, function (r) { + ReadableStreamDefaultControllerError(controller, r); + return null; + }); +} +function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + var controller = Object.create(ReadableStreamDefaultController.prototype); + var startAlgorithm; + var pullAlgorithm; + var cancelAlgorithm; + if (underlyingSource.start !== undefined) { + startAlgorithm = function () { return underlyingSource.start(controller); }; + } + else { + startAlgorithm = function () { return undefined; }; + } + if (underlyingSource.pull !== undefined) { + pullAlgorithm = function () { return underlyingSource.pull(controller); }; + } + else { + pullAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (underlyingSource.cancel !== undefined) { + cancelAlgorithm = function (reason) { return underlyingSource.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); +} +// Helper functions for the ReadableStreamDefaultController. +function defaultControllerBrandCheckException$1(name) { + return new TypeError("ReadableStreamDefaultController.prototype.".concat(name, " can only be used on a ReadableStreamDefaultController")); +} + +function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); +} +function ReadableStreamDefaultTee(stream, cloneForBranch2) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgain = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(undefined); + } + reading = true; + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgain = false; + var chunk1 = chunk; + var chunk2 = chunk; + // There is no way to access the cloning code right now in the reference implementation. + // If we add one then we'll need an implementation for serializable objects. + // if (!canceled2 && cloneForBranch2) { + // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2)); + // } + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + // do nothing + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, function (r) { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + return [branch1, branch2]; +} +function ReadableByteStreamTee(stream) { + var reader = AcquireReadableStreamDefaultReader(stream); + var reading = false; + var readAgainForBranch1 = false; + var readAgainForBranch2 = false; + var canceled1 = false; + var canceled2 = false; + var reason1; + var reason2; + var branch1; + var branch2; + var resolveCancelPromise; + var cancelPromise = newPromise(function (resolve) { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, function (r) { + if (thisReader !== reader) { + return null; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r); + ReadableByteStreamControllerError(branch2._readableStreamController, r); + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + return null; + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + var readRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var chunk1 = chunk; + var chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function () { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + var byobBranch = forBranch2 ? branch2 : branch1; + var otherBranch = forBranch2 ? branch1 : branch2; + var readIntoRequest = { + _chunkSteps: function (chunk) { + // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using + // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let + // successful synchronously-available reads get ahead of asynchronously-available errors. + _queueMicrotask(function () { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + var clonedChunk = void 0; + try { + clonedChunk = CloneAsUint8Array(chunk); + } + catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } + else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } + else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: function (chunk) { + reading = false; + var byobCanceled = forBranch2 ? canceled2 : canceled1; + var otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== undefined) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(undefined); + } + }, + _errorSteps: function () { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(undefined); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(undefined); + } + reading = true; + var byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } + else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(undefined); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + var compositeReason = CreateArrayFromList([reason1, reason2]); + var cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; +} + +function isReadableStreamLike(stream) { + return typeIsObject(stream) && typeof stream.getReader !== 'undefined'; +} + +function ReadableStreamFrom(source) { + if (isReadableStreamLike(source)) { + return ReadableStreamFromDefaultReader(source.getReader()); + } + return ReadableStreamFromIterable(source); +} +function ReadableStreamFromIterable(asyncIterable) { + var stream; + var iteratorRecord = GetIterator(asyncIterable, 'async'); + var startAlgorithm = noop; + function pullAlgorithm() { + var nextResult; + try { + nextResult = IteratorNext(iteratorRecord); + } + catch (e) { + return promiseRejectedWith(e); + } + var nextPromise = promiseResolvedWith(nextResult); + return transformPromiseWith(nextPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object'); + } + var done = IteratorComplete(iterResult); + if (done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = IteratorValue(iterResult); + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + var iterator = iteratorRecord.iterator; + var returnMethod; + try { + returnMethod = GetMethod(iterator, 'return'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (returnMethod === undefined) { + return promiseResolvedWith(undefined); + } + var returnResult; + try { + returnResult = reflectCall(returnMethod, iterator, [reason]); + } + catch (e) { + return promiseRejectedWith(e); + } + var returnPromise = promiseResolvedWith(returnResult); + return transformPromiseWith(returnPromise, function (iterResult) { + if (!typeIsObject(iterResult)) { + throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object'); + } + return undefined; + }); + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} +function ReadableStreamFromDefaultReader(reader) { + var stream; + var startAlgorithm = noop; + function pullAlgorithm() { + var readPromise; + try { + readPromise = reader.read(); + } + catch (e) { + return promiseRejectedWith(e); + } + return transformPromiseWith(readPromise, function (readResult) { + if (!typeIsObject(readResult)) { + throw new TypeError('The promise returned by the reader.read() method must fulfill with an object'); + } + if (readResult.done) { + ReadableStreamDefaultControllerClose(stream._readableStreamController); + } + else { + var value = readResult.value; + ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value); + } + }); + } + function cancelAlgorithm(reason) { + try { + return promiseResolvedWith(reader.cancel(reason)); + } + catch (e) { + return promiseRejectedWith(e); + } + } + stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0); + return stream; +} + +function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + var original = source; + var autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var pull = original === null || original === void 0 ? void 0 : original.pull; + var start = original === null || original === void 0 ? void 0 : original.start; + var type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === undefined ? + undefined : + convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, "".concat(context, " has member 'autoAllocateChunkSize' that")), + cancel: cancel === undefined ? + undefined : + convertUnderlyingSourceCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + pull: pull === undefined ? + undefined : + convertUnderlyingSourcePullCallback(pull, original, "".concat(context, " has member 'pull' that")), + start: start === undefined ? + undefined : + convertUnderlyingSourceStartCallback(start, original, "".concat(context, " has member 'start' that")), + type: type === undefined ? undefined : convertReadableStreamType(type, "".concat(context, " has member 'type' that")) + }; +} +function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} +function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertReadableStreamType(type, context) { + type = "".concat(type); + if (type !== 'bytes') { + throw new TypeError("".concat(context, " '").concat(type, "' is not a valid enumeration value for ReadableStreamType")); + } + return type; +} + +function convertIteratorOptions(options, context) { + assertDictionary(options, context); + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; +} + +function convertPipeOptions(options, context) { + assertDictionary(options, context); + var preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + var preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + var preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + var signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== undefined) { + assertAbortSignal(signal, "".concat(context, " has member 'signal' that")); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal: signal + }; +} +function assertAbortSignal(signal, context) { + if (!isAbortSignal(signal)) { + throw new TypeError("".concat(context, " is not an AbortSignal.")); + } +} + +function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + var readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, 'readable', 'ReadableWritablePair'); + assertReadableStream(readable, "".concat(context, " has member 'readable' that")); + var writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, 'writable', 'ReadableWritablePair'); + assertWritableStream(writable, "".concat(context, " has member 'writable' that")); + return { readable: readable, writable: writable }; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +var ReadableStream = /** @class */ (function () { + function ReadableStream(rawUnderlyingSource, rawStrategy) { + if (rawUnderlyingSource === void 0) { rawUnderlyingSource = {}; } + if (rawStrategy === void 0) { rawStrategy = {}; } + if (rawUnderlyingSource === undefined) { + rawUnderlyingSource = null; + } + else { + assertObject(rawUnderlyingSource, 'First parameter'); + } + var strategy = convertQueuingStrategy(rawStrategy, 'Second parameter'); + var underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter'); + InitializeReadableStream(this); + if (underlyingSource.type === 'bytes') { + if (strategy.size !== undefined) { + throw new RangeError('The strategy for a byte stream cannot have a size function'); + } + var highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } + else { + var sizeAlgorithm = ExtractSizeAlgorithm(strategy); + var highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + Object.defineProperty(ReadableStream.prototype, "locked", { + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get: function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('locked'); + } + return IsReadableStreamLocked(this); + }, + enumerable: false, + configurable: true + }); + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + ReadableStream.prototype.cancel = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('cancel')); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader')); + } + return ReadableStreamCancel(this, reason); + }; + ReadableStream.prototype.getReader = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('getReader'); + } + var options = convertReaderOptions(rawOptions, 'First parameter'); + if (options.mode === undefined) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + }; + ReadableStream.prototype.pipeThrough = function (rawTransform, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('pipeThrough'); + } + assertRequiredArgument(rawTransform, 1, 'pipeThrough'); + var transform = convertReadableWritablePair(rawTransform, 'First parameter'); + var options = convertPipeOptions(rawOptions, 'Second parameter'); + if (IsReadableStreamLocked(this)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream'); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream'); + } + var promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + }; + ReadableStream.prototype.pipeTo = function (destination, rawOptions) { + if (rawOptions === void 0) { rawOptions = {}; } + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1('pipeTo')); + } + if (destination === undefined) { + return promiseRejectedWith("Parameter 1 is required in 'pipeTo'."); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream")); + } + var options; + try { + options = convertPipeOptions(rawOptions, 'Second parameter'); + } + catch (e) { + return promiseRejectedWith(e); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + }; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + ReadableStream.prototype.tee = function () { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('tee'); + } + var branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + }; + ReadableStream.prototype.values = function (rawOptions) { + if (rawOptions === void 0) { rawOptions = undefined; } + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1('values'); + } + var options = convertIteratorOptions(rawOptions, 'First parameter'); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + }; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + ReadableStream.from = function (asyncIterable) { + return ReadableStreamFrom(asyncIterable); + }; + return ReadableStream; +}()); +Object.defineProperties(ReadableStream, { + from: { enumerable: true } +}); +Object.defineProperties(ReadableStream.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } +}); +setFunctionName(ReadableStream.from, 'from'); +setFunctionName(ReadableStream.prototype.cancel, 'cancel'); +setFunctionName(ReadableStream.prototype.getReader, 'getReader'); +setFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough'); +setFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo'); +setFunctionName(ReadableStream.prototype.tee, 'tee'); +setFunctionName(ReadableStream.prototype.values, 'values'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.toStringTag, { + value: 'ReadableStream', + configurable: true + }); +} +if (typeof SymbolPolyfill.asyncIterator === 'symbol') { + Object.defineProperty(ReadableStream.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream.prototype.values, + writable: true, + configurable: true + }); +} +// Abstract operations for the ReadableStream. +// Throws if and only if startAlgorithm throws. +function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + if (highWaterMark === void 0) { highWaterMark = 1; } + if (sizeAlgorithm === void 0) { sizeAlgorithm = function () { return 1; }; } + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; +} +// Throws if and only if startAlgorithm throws. +function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + var stream = Object.create(ReadableStream.prototype); + InitializeReadableStream(stream); + var controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined); + return stream; +} +function InitializeReadableStream(stream) { + stream._state = 'readable'; + stream._reader = undefined; + stream._storedError = undefined; + stream._disturbed = false; +} +function IsReadableStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) { + return false; + } + return x instanceof ReadableStream; +} +function IsReadableStreamLocked(stream) { + if (stream._reader === undefined) { + return false; + } + return true; +} +// ReadableStream API exposed for controllers. +function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === 'closed') { + return promiseResolvedWith(undefined); + } + if (stream._state === 'errored') { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + var reader = stream._reader; + if (reader !== undefined && IsReadableStreamBYOBReader(reader)) { + var readIntoRequests = reader._readIntoRequests; + reader._readIntoRequests = new SimpleQueue(); + readIntoRequests.forEach(function (readIntoRequest) { + readIntoRequest._closeSteps(undefined); + }); + } + var sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop); +} +function ReadableStreamClose(stream) { + stream._state = 'closed'; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + var readRequests = reader._readRequests; + reader._readRequests = new SimpleQueue(); + readRequests.forEach(function (readRequest) { + readRequest._closeSteps(); + }); + } +} +function ReadableStreamError(stream, e) { + stream._state = 'errored'; + stream._storedError = e; + var reader = stream._reader; + if (reader === undefined) { + return; + } + defaultReaderClosedPromiseReject(reader, e); + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamDefaultReaderErrorReadRequests(reader, e); + } + else { + ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e); + } +} +// Helper functions for the ReadableStream. +function streamBrandCheckException$1(name) { + return new TypeError("ReadableStream.prototype.".concat(name, " can only be used on a ReadableStream")); +} + +function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + var highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit'); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; +} + +// The size function must not have a prototype property nor be a constructor +var byteLengthSizeFunction = function (chunk) { + return chunk.byteLength; +}; +setFunctionName(byteLengthSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +var ByteLengthQueuingStrategy = /** @class */ (function () { + function ByteLengthQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('highWaterMark'); + } + return this._byteLengthQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ByteLengthQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get: function () { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException('size'); + } + return byteLengthSizeFunction; + }, + enumerable: false, + configurable: true + }); + return ByteLengthQueuingStrategy; +}()); +Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'ByteLengthQueuingStrategy', + configurable: true + }); +} +// Helper functions for the ByteLengthQueuingStrategy. +function byteLengthBrandCheckException(name) { + return new TypeError("ByteLengthQueuingStrategy.prototype.".concat(name, " can only be used on a ByteLengthQueuingStrategy")); +} +function IsByteLengthQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof ByteLengthQueuingStrategy; +} + +// The size function must not have a prototype property nor be a constructor +var countSizeFunction = function () { + return 1; +}; +setFunctionName(countSizeFunction, 'size'); +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +var CountQueuingStrategy = /** @class */ (function () { + function CountQueuingStrategy(options) { + assertRequiredArgument(options, 1, 'CountQueuingStrategy'); + options = convertQueuingStrategyInit(options, 'First parameter'); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + Object.defineProperty(CountQueuingStrategy.prototype, "highWaterMark", { + /** + * Returns the high water mark provided to the constructor. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('highWaterMark'); + } + return this._countQueuingStrategyHighWaterMark; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CountQueuingStrategy.prototype, "size", { + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get: function () { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException('size'); + } + return countSizeFunction; + }, + enumerable: false, + configurable: true + }); + return CountQueuingStrategy; +}()); +Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: 'CountQueuingStrategy', + configurable: true + }); +} +// Helper functions for the CountQueuingStrategy. +function countBrandCheckException(name) { + return new TypeError("CountQueuingStrategy.prototype.".concat(name, " can only be used on a CountQueuingStrategy")); +} +function IsCountQueuingStrategy(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) { + return false; + } + return x instanceof CountQueuingStrategy; +} + +function convertTransformer(original, context) { + assertDictionary(original, context); + var cancel = original === null || original === void 0 ? void 0 : original.cancel; + var flush = original === null || original === void 0 ? void 0 : original.flush; + var readableType = original === null || original === void 0 ? void 0 : original.readableType; + var start = original === null || original === void 0 ? void 0 : original.start; + var transform = original === null || original === void 0 ? void 0 : original.transform; + var writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + cancel: cancel === undefined ? + undefined : + convertTransformerCancelCallback(cancel, original, "".concat(context, " has member 'cancel' that")), + flush: flush === undefined ? + undefined : + convertTransformerFlushCallback(flush, original, "".concat(context, " has member 'flush' that")), + readableType: readableType, + start: start === undefined ? + undefined : + convertTransformerStartCallback(start, original, "".concat(context, " has member 'start' that")), + transform: transform === undefined ? + undefined : + convertTransformerTransformCallback(transform, original, "".concat(context, " has member 'transform' that")), + writableType: writableType + }; +} +function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return promiseCall(fn, original, [controller]); }; +} +function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return function (controller) { return reflectCall(fn, original, [controller]); }; +} +function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return function (chunk, controller) { return promiseCall(fn, original, [chunk, controller]); }; +} +function convertTransformerCancelCallback(fn, original, context) { + assertFunction(fn, context); + return function (reason) { return promiseCall(fn, original, [reason]); }; +} + +// Class TransformStream +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +var TransformStream = /** @class */ (function () { + function TransformStream(rawTransformer, rawWritableStrategy, rawReadableStrategy) { + if (rawTransformer === void 0) { rawTransformer = {}; } + if (rawWritableStrategy === void 0) { rawWritableStrategy = {}; } + if (rawReadableStrategy === void 0) { rawReadableStrategy = {}; } + if (rawTransformer === undefined) { + rawTransformer = null; + } + var writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter'); + var readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter'); + var transformer = convertTransformer(rawTransformer, 'First parameter'); + if (transformer.readableType !== undefined) { + throw new RangeError('Invalid readableType specified'); + } + if (transformer.writableType !== undefined) { + throw new RangeError('Invalid writableType specified'); + } + var readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + var readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + var writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + var writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + var startPromise_resolve; + var startPromise = newPromise(function (resolve) { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== undefined) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } + else { + startPromise_resolve(undefined); + } + } + Object.defineProperty(TransformStream.prototype, "readable", { + /** + * The readable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('readable'); + } + return this._readable; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TransformStream.prototype, "writable", { + /** + * The writable side of the transform stream. + */ + get: function () { + if (!IsTransformStream(this)) { + throw streamBrandCheckException('writable'); + } + return this._writable; + }, + enumerable: false, + configurable: true + }); + return TransformStream; +}()); +Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } +}); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStream', + configurable: true + }); +} +function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + return TransformStreamDefaultSourceCancelAlgorithm(stream, reason); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure. + stream._backpressure = undefined; + stream._backpressureChangePromise = undefined; + stream._backpressureChangePromise_resolve = undefined; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = undefined; +} +function IsTransformStream(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) { + return false; + } + return x instanceof TransformStream; +} +// This is a no-op if both sides are already errored. +function TransformStreamError(stream, e) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e); + TransformStreamErrorWritableAndUnblockWrite(stream, e); +} +function TransformStreamErrorWritableAndUnblockWrite(stream, e) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e); + TransformStreamUnblockWrite(stream); +} +function TransformStreamUnblockWrite(stream) { + if (stream._backpressure) { + // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure() + // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time + // _backpressure is set. + TransformStreamSetBackpressure(stream, false); + } +} +function TransformStreamSetBackpressure(stream, backpressure) { + // Passes also when called during construction. + if (stream._backpressureChangePromise !== undefined) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise(function (resolve) { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; +} +// Class TransformStreamDefaultController +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +var TransformStreamDefaultController = /** @class */ (function () { + function TransformStreamDefaultController() { + throw new TypeError('Illegal constructor'); + } + Object.defineProperty(TransformStreamDefaultController.prototype, "desiredSize", { + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get: function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('desiredSize'); + } + var readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + }, + enumerable: false, + configurable: true + }); + TransformStreamDefaultController.prototype.enqueue = function (chunk) { + if (chunk === void 0) { chunk = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('enqueue'); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + }; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + TransformStreamDefaultController.prototype.error = function (reason) { + if (reason === void 0) { reason = undefined; } + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('error'); + } + TransformStreamDefaultControllerError(this, reason); + }; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + TransformStreamDefaultController.prototype.terminate = function () { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException('terminate'); + } + TransformStreamDefaultControllerTerminate(this); + }; + return TransformStreamDefaultController; +}()); +Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } +}); +setFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue'); +setFunctionName(TransformStreamDefaultController.prototype.error, 'error'); +setFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate'); +if (typeof SymbolPolyfill.toStringTag === 'symbol') { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: 'TransformStreamDefaultController', + configurable: true + }); +} +// Transform Stream Default Controller Abstract Operations +function IsTransformStreamDefaultController(x) { + if (!typeIsObject(x)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) { + return false; + } + return x instanceof TransformStreamDefaultController; +} +function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._finishPromise = undefined; + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + var controller = Object.create(TransformStreamDefaultController.prototype); + var transformAlgorithm; + var flushAlgorithm; + var cancelAlgorithm; + if (transformer.transform !== undefined) { + transformAlgorithm = function (chunk) { return transformer.transform(chunk, controller); }; + } + else { + transformAlgorithm = function (chunk) { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(undefined); + } + catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + } + if (transformer.flush !== undefined) { + flushAlgorithm = function () { return transformer.flush(controller); }; + } + else { + flushAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + if (transformer.cancel !== undefined) { + cancelAlgorithm = function (reason) { return transformer.cancel(reason); }; + } + else { + cancelAlgorithm = function () { return promiseResolvedWith(undefined); }; + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm); +} +function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = undefined; + controller._flushAlgorithm = undefined; + controller._cancelAlgorithm = undefined; +} +function TransformStreamDefaultControllerEnqueue(controller, chunk) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError('Readable side is not in a state that permits enqueue'); + } + // We throttle transform invocations based on the backpressure of the ReadableStream, but we still + // accept TransformStreamDefaultControllerEnqueue() calls. + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } + catch (e) { + // This happens when readableStrategy.size() throws. + TransformStreamErrorWritableAndUnblockWrite(stream, e); + throw stream._readable._storedError; + } + var backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } +} +function TransformStreamDefaultControllerError(controller, e) { + TransformStreamError(controller._controlledTransformStream, e); +} +function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + var transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, undefined, function (r) { + TransformStreamError(controller._controlledTransformStream, r); + throw r; + }); +} +function TransformStreamDefaultControllerTerminate(controller) { + var stream = controller._controlledTransformStream; + var readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + var error = new TypeError('TransformStream terminated'); + TransformStreamErrorWritableAndUnblockWrite(stream, error); +} +// TransformStreamDefaultSink Algorithms +function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + var controller = stream._transformStreamController; + if (stream._backpressure) { + var backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, function () { + var writable = stream._writable; + var state = writable._state; + if (state === 'erroring') { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); +} +function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally, + // we don't run the _cancelAlgorithm again. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerError(readable._readableStreamController, reason); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +function TransformStreamDefaultSinkCloseAlgorithm(stream) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._readable cannot change after construction, so caching it across a call to user code is safe. + var readable = stream._readable; + // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally, + // we don't also run the _cancelAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(flushPromise, function () { + if (readable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, readable._storedError); + } + else { + ReadableStreamDefaultControllerClose(readable._readableStreamController); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + ReadableStreamDefaultControllerError(readable._readableStreamController, r); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// TransformStreamDefaultSource Algorithms +function TransformStreamDefaultSourcePullAlgorithm(stream) { + // Invariant. Enforced by the promises returned by start() and pull(). + TransformStreamSetBackpressure(stream, false); + // Prevent the next pull() call until there is backpressure. + return stream._backpressureChangePromise; +} +function TransformStreamDefaultSourceCancelAlgorithm(stream, reason) { + var controller = stream._transformStreamController; + if (controller._finishPromise !== undefined) { + return controller._finishPromise; + } + // stream._writable cannot change after construction, so caching it across a call to user code is safe. + var writable = stream._writable; + // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or + // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the + // _flushAlgorithm. + controller._finishPromise = newPromise(function (resolve, reject) { + controller._finishPromise_resolve = resolve; + controller._finishPromise_reject = reject; + }); + var cancelPromise = controller._cancelAlgorithm(reason); + TransformStreamDefaultControllerClearAlgorithms(controller); + uponPromise(cancelPromise, function () { + if (writable._state === 'errored') { + defaultControllerFinishPromiseReject(controller, writable._storedError); + } + else { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseResolve(controller); + } + return null; + }, function (r) { + WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r); + TransformStreamUnblockWrite(stream); + defaultControllerFinishPromiseReject(controller, r); + return null; + }); + return controller._finishPromise; +} +// Helper functions for the TransformStreamDefaultController. +function defaultControllerBrandCheckException(name) { + return new TypeError("TransformStreamDefaultController.prototype.".concat(name, " can only be used on a TransformStreamDefaultController")); +} +function defaultControllerFinishPromiseResolve(controller) { + if (controller._finishPromise_resolve === undefined) { + return; + } + controller._finishPromise_resolve(); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +function defaultControllerFinishPromiseReject(controller, reason) { + if (controller._finishPromise_reject === undefined) { + return; + } + setPromiseIsHandledToTrue(controller._finishPromise); + controller._finishPromise_reject(reason); + controller._finishPromise_resolve = undefined; + controller._finishPromise_reject = undefined; +} +// Helper functions for the TransformStream. +function streamBrandCheckException(name) { + return new TypeError("TransformStream.prototype.".concat(name, " can only be used on a TransformStream")); +} + +export { ByteLengthQueuingStrategy, CountQueuingStrategy, ReadableByteStreamController, ReadableStream, ReadableStreamBYOBReader, ReadableStreamBYOBRequest, ReadableStreamDefaultController, ReadableStreamDefaultReader, TransformStream, TransformStreamDefaultController, WritableStream, WritableStreamDefaultController, WritableStreamDefaultWriter }; +//# sourceMappingURL=ponyfill.mjs.map diff --git a/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map b/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map new file mode 100644 index 0000000..3cc0740 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/ponyfill.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"ponyfill.mjs","sources":["../src/stub/symbol.ts","../node_modules/tslib/tslib.es6.js","../src/utils.ts","../src/lib/helpers/miscellaneous.ts","../src/lib/helpers/webidl.ts","../src/lib/simple-queue.ts","../src/lib/abstract-ops/internal-methods.ts","../src/lib/readable-stream/generic-reader.ts","../src/stub/number-isfinite.ts","../src/stub/math-trunc.ts","../src/lib/validators/basic.ts","../src/lib/validators/readable-stream.ts","../src/lib/readable-stream/default-reader.ts","../src/target/es5/stub/async-iterator-prototype.ts","../src/lib/readable-stream/async-iterator.ts","../src/stub/number-isnan.ts","../src/lib/abstract-ops/ecmascript.ts","../src/lib/abstract-ops/miscellaneous.ts","../src/lib/abstract-ops/queue-with-sizes.ts","../src/lib/helpers/array-buffer-view.ts","../src/lib/readable-stream/byte-stream-controller.ts","../src/lib/validators/reader-options.ts","../src/lib/readable-stream/byob-reader.ts","../src/lib/abstract-ops/queuing-strategy.ts","../src/lib/validators/queuing-strategy.ts","../src/lib/validators/underlying-sink.ts","../src/lib/validators/writable-stream.ts","../src/lib/abort-signal.ts","../src/lib/writable-stream.ts","../src/globals.ts","../src/stub/dom-exception.ts","../src/lib/readable-stream/pipe.ts","../src/lib/readable-stream/default-controller.ts","../src/lib/readable-stream/tee.ts","../src/lib/readable-stream/readable-stream-like.ts","../src/lib/readable-stream/from.ts","../src/lib/validators/underlying-source.ts","../src/lib/validators/iterator-options.ts","../src/lib/validators/pipe-options.ts","../src/lib/validators/readable-writable-pair.ts","../src/lib/readable-stream.ts","../src/lib/validators/queuing-strategy-init.ts","../src/lib/byte-length-queuing-strategy.ts","../src/lib/count-queuing-strategy.ts","../src/lib/validators/transformer.ts","../src/lib/transform-stream.ts"],"sourcesContent":["/// \n\nconst SymbolPolyfill: (description?: string) => symbol =\n typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ?\n Symbol :\n description => `Symbol(${description})` as any as symbol;\n\nexport default SymbolPolyfill;\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n 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);\r\n 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); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","export function noop(): undefined {\n return undefined;\n}\n","import { noop } from '../../utils';\nimport { AssertionError } from '../../stub/assert';\n\nexport function typeIsObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport const rethrowAssertionErrorRejection: (e: any) => void =\n DEBUG ? e => {\n // Used throughout the reference implementation, as `.catch(rethrowAssertionErrorRejection)`, to ensure any errors\n // get shown. There are places in the spec where we do promise transformations and purposefully ignore or don't\n // expect any errors, but assertion errors are always problematic.\n if (e && e instanceof AssertionError) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n } : noop;\n\nexport function setFunctionName(fn: Function, name: string): void {\n try {\n Object.defineProperty(fn, 'name', {\n value: name,\n configurable: true\n });\n } catch {\n // This property is non-configurable in older browsers, so ignore if this throws.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name#browser_compatibility\n }\n}\n","import { rethrowAssertionErrorRejection } from './miscellaneous';\nimport assert from '../../stub/assert';\n\nconst originalPromise = Promise;\nconst originalPromiseThen = Promise.prototype.then;\nconst originalPromiseReject = Promise.reject.bind(originalPromise);\n\n// https://webidl.spec.whatwg.org/#a-new-promise\nexport function newPromise(executor: (\n resolve: (value: T | PromiseLike) => void,\n reject: (reason?: any) => void\n) => void): Promise {\n return new originalPromise(executor);\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-resolved-with\nexport function promiseResolvedWith(value: T | PromiseLike): Promise {\n return newPromise(resolve => resolve(value));\n}\n\n// https://webidl.spec.whatwg.org/#a-promise-rejected-with\nexport function promiseRejectedWith(reason: any): Promise {\n return originalPromiseReject(reason);\n}\n\nexport function PerformPromiseThen(\n promise: Promise,\n onFulfilled?: (value: T) => TResult1 | PromiseLike,\n onRejected?: (reason: any) => TResult2 | PromiseLike): Promise {\n // There doesn't appear to be any way to correctly emulate the behaviour from JavaScript, so this is just an\n // approximation.\n return originalPromiseThen.call(promise, onFulfilled, onRejected) as Promise;\n}\n\n// Bluebird logs a warning when a promise is created within a fulfillment handler, but then isn't returned\n// from that handler. To prevent this, return null instead of void from all handlers.\n// http://bluebirdjs.com/docs/warning-explanations.html#warning-a-promise-was-created-in-a-handler-but-was-not-returned-from-it\nexport function uponPromise(\n promise: Promise,\n onFulfilled?: (value: T) => null | PromiseLike,\n onRejected?: (reason: any) => null | PromiseLike): void {\n PerformPromiseThen(\n PerformPromiseThen(promise, onFulfilled, onRejected),\n undefined,\n rethrowAssertionErrorRejection\n );\n}\n\nexport function uponFulfillment(promise: Promise, onFulfilled: (value: T) => null | PromiseLike): void {\n uponPromise(promise, onFulfilled);\n}\n\nexport function uponRejection(promise: Promise, onRejected: (reason: any) => null | PromiseLike): void {\n uponPromise(promise, undefined, onRejected);\n}\n\nexport function transformPromiseWith(\n promise: Promise,\n fulfillmentHandler?: (value: T) => TResult1 | PromiseLike,\n rejectionHandler?: (reason: any) => TResult2 | PromiseLike): Promise {\n return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler);\n}\n\nexport function setPromiseIsHandledToTrue(promise: Promise): void {\n PerformPromiseThen(promise, undefined, rethrowAssertionErrorRejection);\n}\n\nlet _queueMicrotask: (callback: () => void) => void = callback => {\n if (typeof queueMicrotask === 'function') {\n _queueMicrotask = queueMicrotask;\n } else {\n const resolvedPromise = promiseResolvedWith(undefined);\n _queueMicrotask = cb => PerformPromiseThen(resolvedPromise, cb);\n }\n return _queueMicrotask(callback);\n};\n\nexport { _queueMicrotask as queueMicrotask };\n\nexport function reflectCall(F: (this: T, ...fnArgs: A) => R, V: T, args: A): R {\n if (typeof F !== 'function') {\n throw new TypeError('Argument is not a function');\n }\n return Function.prototype.apply.call(F, V, args);\n}\n\nexport function promiseCall(F: (this: T, ...fnArgs: A) => R | PromiseLike,\n V: T,\n args: A): Promise {\n assert(typeof F === 'function');\n assert(V !== undefined);\n assert(Array.isArray(args));\n try {\n return promiseResolvedWith(reflectCall(F, V, args));\n } catch (value) {\n return promiseRejectedWith(value);\n }\n}\n","import assert from '../stub/assert';\n\n// Original from Chromium\n// https://chromium.googlesource.com/chromium/src/+/0aee4434a4dba42a42abaea9bfbc0cd196a63bc1/third_party/blink/renderer/core/streams/SimpleQueue.js\n\nconst QUEUE_MAX_ARRAY_SIZE = 16384;\n\ninterface Node {\n _elements: T[];\n _next: Node | undefined;\n}\n\n/**\n * Simple queue structure.\n *\n * Avoids scalability issues with using a packed array directly by using\n * multiple arrays in a linked list and keeping the array size bounded.\n */\nexport class SimpleQueue {\n private _front: Node;\n private _back: Node;\n private _cursor = 0;\n private _size = 0;\n\n constructor() {\n // _front and _back are always defined.\n this._front = {\n _elements: [],\n _next: undefined\n };\n this._back = this._front;\n // The cursor is used to avoid calling Array.shift().\n // It contains the index of the front element of the array inside the\n // front-most node. It is always in the range [0, QUEUE_MAX_ARRAY_SIZE).\n this._cursor = 0;\n // When there is only one node, size === elements.length - cursor.\n this._size = 0;\n }\n\n get length(): number {\n return this._size;\n }\n\n // For exception safety, this method is structured in order:\n // 1. Read state\n // 2. Calculate required state mutations\n // 3. Perform state mutations\n push(element: T): void {\n const oldBack = this._back;\n let newBack = oldBack;\n assert(oldBack._next === undefined);\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }\n\n // Like push(), shift() follows the read -> calculate -> mutate pattern for\n // exception safety.\n shift(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n assert(elements.length === QUEUE_MAX_ARRAY_SIZE);\n assert(oldFront._next !== undefined);\n newFront = oldFront._next!;\n newCursor = 0;\n }\n\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined!;\n\n return element;\n }\n\n // The tricky thing about forEach() is that it can be called\n // re-entrantly. The queue may be mutated inside the callback. It is easy to\n // see that push() within the callback has no negative effects since the end\n // of the queue is checked for on every iteration. If shift() is called\n // repeatedly within the callback then the next iteration may return an\n // element that has been removed. In this case the callback will be called\n // with undefined values until we either \"catch up\" with elements that still\n // exist or reach the back of the queue.\n forEach(callback: (element: T) => void): void {\n let i = this._cursor;\n let node = this._front;\n let elements = node._elements;\n while (i !== elements.length || node._next !== undefined) {\n if (i === elements.length) {\n assert(node._next !== undefined);\n assert(i === QUEUE_MAX_ARRAY_SIZE);\n node = node._next!;\n elements = node._elements;\n i = 0;\n if (elements.length === 0) {\n break;\n }\n }\n callback(elements[i]);\n ++i;\n }\n }\n\n // Return the element that would be returned if shift() was called now,\n // without modifying the queue.\n peek(): T {\n assert(this._size > 0); // must not be called on an empty queue\n\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }\n}\n","export const AbortSteps = Symbol('[[AbortSteps]]');\nexport const ErrorSteps = Symbol('[[ErrorSteps]]');\nexport const CancelSteps = Symbol('[[CancelSteps]]');\nexport const PullSteps = Symbol('[[PullSteps]]');\nexport const ReleaseSteps = Symbol('[[ReleaseSteps]]');\n","import assert from '../../stub/assert';\nimport { ReadableStream, ReadableStreamCancel, type ReadableStreamReader } from '../readable-stream';\nimport { newPromise, setPromiseIsHandledToTrue } from '../helpers/webidl';\nimport { ReleaseSteps } from '../abstract-ops/internal-methods';\n\nexport function ReadableStreamReaderGenericInitialize(reader: ReadableStreamReader, stream: ReadableStream) {\n reader._ownerReadableStream = stream;\n stream._reader = reader;\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseInitialize(reader);\n } else if (stream._state === 'closed') {\n defaultReaderClosedPromiseInitializeAsResolved(reader);\n } else {\n assert(stream._state === 'errored');\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError);\n }\n}\n\n// A client of ReadableStreamDefaultReader and ReadableStreamBYOBReader may use these functions directly to bypass state\n// check.\n\nexport function ReadableStreamReaderGenericCancel(reader: ReadableStreamReader, reason: any): Promise {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n return ReadableStreamCancel(stream, reason);\n}\n\nexport function ReadableStreamReaderGenericRelease(reader: ReadableStreamReader) {\n const stream = reader._ownerReadableStream;\n assert(stream !== undefined);\n assert(stream._reader === reader);\n\n if (stream._state === 'readable') {\n defaultReaderClosedPromiseReject(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n } else {\n defaultReaderClosedPromiseResetToRejected(\n reader,\n new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`));\n }\n\n stream._readableStreamController[ReleaseSteps]();\n\n stream._reader = undefined;\n reader._ownerReadableStream = undefined!;\n}\n\n// Helper functions for the readers.\n\nexport function readerLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released reader');\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nexport function defaultReaderClosedPromiseInitialize(reader: ReadableStreamReader) {\n reader._closedPromise = newPromise((resolve, reject) => {\n reader._closedPromise_resolve = resolve;\n reader._closedPromise_reject = reject;\n });\n}\n\nexport function defaultReaderClosedPromiseInitializeAsRejected(reader: ReadableStreamReader, reason: any) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseReject(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseInitializeAsResolved(reader: ReadableStreamReader) {\n defaultReaderClosedPromiseInitialize(reader);\n defaultReaderClosedPromiseResolve(reader);\n}\n\nexport function defaultReaderClosedPromiseReject(reader: ReadableStreamReader, reason: any) {\n if (reader._closedPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(reader._closedPromise);\n reader._closedPromise_reject(reason);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n\nexport function defaultReaderClosedPromiseResetToRejected(reader: ReadableStreamReader, reason: any) {\n assert(reader._closedPromise_resolve === undefined);\n assert(reader._closedPromise_reject === undefined);\n\n defaultReaderClosedPromiseInitializeAsRejected(reader, reason);\n}\n\nexport function defaultReaderClosedPromiseResolve(reader: ReadableStreamReader) {\n if (reader._closedPromise_resolve === undefined) {\n return;\n }\n\n reader._closedPromise_resolve(undefined);\n reader._closedPromise_resolve = undefined;\n reader._closedPromise_reject = undefined;\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite#Polyfill\nconst NumberIsFinite: typeof Number.isFinite = Number.isFinite || function (x) {\n return typeof x === 'number' && isFinite(x);\n};\n\nexport default NumberIsFinite;\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc#Polyfill\nconst MathTrunc: typeof Math.trunc = Math.trunc || function (v) {\n return v < 0 ? Math.ceil(v) : Math.floor(v);\n};\n\nexport default MathTrunc;\n","import NumberIsFinite from '../../stub/number-isfinite';\nimport MathTrunc from '../../stub/math-trunc';\n\n// https://heycam.github.io/webidl/#idl-dictionaries\nexport function isDictionary(x: any): x is object | null {\n return typeof x === 'object' || typeof x === 'function';\n}\n\nexport function assertDictionary(obj: unknown,\n context: string): asserts obj is object | null | undefined {\n if (obj !== undefined && !isDictionary(obj)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport type AnyFunction = (...args: any[]) => any;\n\n// https://heycam.github.io/webidl/#idl-callback-functions\nexport function assertFunction(x: unknown, context: string): asserts x is AnyFunction {\n if (typeof x !== 'function') {\n throw new TypeError(`${context} is not a function.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-object\nexport function isObject(x: any): x is object {\n return (typeof x === 'object' && x !== null) || typeof x === 'function';\n}\n\nexport function assertObject(x: unknown,\n context: string): asserts x is object {\n if (!isObject(x)) {\n throw new TypeError(`${context} is not an object.`);\n }\n}\n\nexport function assertRequiredArgument(x: T | undefined,\n position: number,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`Parameter ${position} is required in '${context}'.`);\n }\n}\n\nexport function assertRequiredField(x: T | undefined,\n field: string,\n context: string): asserts x is T {\n if (x === undefined) {\n throw new TypeError(`${field} is required in '${context}'.`);\n }\n}\n\n// https://heycam.github.io/webidl/#idl-unrestricted-double\nexport function convertUnrestrictedDouble(value: unknown): number {\n return Number(value);\n}\n\nfunction censorNegativeZero(x: number): number {\n return x === 0 ? 0 : x;\n}\n\nfunction integerPart(x: number): number {\n return censorNegativeZero(MathTrunc(x));\n}\n\n// https://heycam.github.io/webidl/#idl-unsigned-long-long\nexport function convertUnsignedLongLongWithEnforceRange(value: unknown, context: string): number {\n const lowerBound = 0;\n const upperBound = Number.MAX_SAFE_INTEGER;\n\n let x = Number(value);\n x = censorNegativeZero(x);\n\n if (!NumberIsFinite(x)) {\n throw new TypeError(`${context} is not a finite number`);\n }\n\n x = integerPart(x);\n\n if (x < lowerBound || x > upperBound) {\n throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`);\n }\n\n if (!NumberIsFinite(x) || x === 0) {\n return 0;\n }\n\n // TODO Use BigInt if supported?\n // let xBigInt = BigInt(integerPart(x));\n // xBigInt = BigInt.asUintN(64, xBigInt);\n // return Number(xBigInt);\n\n return x;\n}\n","import { IsReadableStream, ReadableStream } from '../readable-stream';\n\nexport function assertReadableStream(x: unknown, context: string): asserts x is ReadableStream {\n if (!IsReadableStream(x)) {\n throw new TypeError(`${context} is not a ReadableStream.`);\n }\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, ReadableStream } from '../readable-stream';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { PullSteps } from '../abstract-ops/internal-methods';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\n\n/**\n * A result returned by {@link ReadableStreamDefaultReader.read}.\n *\n * @public\n */\nexport type ReadableStreamDefaultReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value?: undefined;\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamDefaultReader(stream: ReadableStream): ReadableStreamDefaultReader {\n return new ReadableStreamDefaultReader(stream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadRequest(stream: ReadableStream,\n readRequest: ReadRequest): void {\n assert(IsReadableStreamDefaultReader(stream._reader));\n assert(stream._state === 'readable');\n\n (stream._reader! as ReadableStreamDefaultReader)._readRequests.push(readRequest);\n}\n\nexport function ReadableStreamFulfillReadRequest(stream: ReadableStream, chunk: R | undefined, done: boolean) {\n const reader = stream._reader as ReadableStreamDefaultReader;\n\n assert(reader._readRequests.length > 0);\n\n const readRequest = reader._readRequests.shift()!;\n if (done) {\n readRequest._closeSteps();\n } else {\n readRequest._chunkSteps(chunk!);\n }\n}\n\nexport function ReadableStreamGetNumReadRequests(stream: ReadableStream): number {\n return (stream._reader as ReadableStreamDefaultReader)._readRequests.length;\n}\n\nexport function ReadableStreamHasDefaultReader(stream: ReadableStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamDefaultReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadRequest {\n _chunkSteps(chunk: R): void;\n\n _closeSteps(): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A default reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamDefaultReader {\n /** @internal */\n _ownerReadableStream!: ReadableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamDefaultReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed,\n * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Returns a promise that allows access to the next chunk from the stream's internal queue, if available.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(): Promise> {\n if (!IsReadableStreamDefaultReader(this)) {\n return promiseRejectedWith(defaultReaderBrandCheckException('read'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: () => resolvePromise({ value: undefined, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamDefaultReaderRead(this, readRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamDefaultReader(this)) {\n throw defaultReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamDefaultReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamDefaultReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamDefaultReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamDefaultReader(x: any): x is ReadableStreamDefaultReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultReader;\n}\n\nexport function ReadableStreamDefaultReaderRead(reader: ReadableStreamDefaultReader,\n readRequest: ReadRequest): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n readRequest._closeSteps();\n } else if (stream._state === 'errored') {\n readRequest._errorSteps(stream._storedError);\n } else {\n assert(stream._state === 'readable');\n stream._readableStreamController[PullSteps](readRequest as ReadRequest);\n }\n}\n\nexport function ReadableStreamDefaultReaderRelease(reader: ReadableStreamDefaultReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n}\n\nexport function ReadableStreamDefaultReaderErrorReadRequests(reader: ReadableStreamDefaultReader, e: any) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamDefaultReader.\n\nfunction defaultReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`);\n}\n","/// \n\nexport let AsyncIteratorPrototype: AsyncIterable | undefined;\n\nif (typeof Symbol.asyncIterator === 'symbol') {\n // We're running inside a ES2018+ environment, but we're compiling to an older syntax.\n // We cannot access %AsyncIteratorPrototype% without non-ES2018 syntax, but we can re-create it.\n AsyncIteratorPrototype = {\n // 25.1.3.1 %AsyncIteratorPrototype% [ @@asyncIterator ] ( )\n // https://tc39.github.io/ecma262/#sec-asynciteratorprototype-asynciterator\n [Symbol.asyncIterator](this: AsyncIterator) {\n return this;\n }\n };\n Object.defineProperty(AsyncIteratorPrototype, Symbol.asyncIterator, { enumerable: false });\n}\n","/// \n\nimport { ReadableStream } from '../readable-stream';\nimport {\n AcquireReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadableStreamDefaultReadResult,\n type ReadRequest\n} from './default-reader';\nimport { ReadableStreamReaderGenericCancel, ReadableStreamReaderGenericRelease } from './generic-reader';\nimport assert from '../../stub/assert';\nimport { AsyncIteratorPrototype } from '@@target/stub/async-iterator-prototype';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n queueMicrotask,\n transformPromiseWith\n} from '../helpers/webidl';\n\n/**\n * An async iterator returned by {@link ReadableStream.values}.\n *\n * @public\n */\nexport interface ReadableStreamAsyncIterator extends AsyncIterator {\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nexport class ReadableStreamAsyncIteratorImpl {\n private readonly _reader: ReadableStreamDefaultReader;\n private readonly _preventCancel: boolean;\n private _ongoingPromise: Promise> | undefined = undefined;\n private _isFinished = false;\n\n constructor(reader: ReadableStreamDefaultReader, preventCancel: boolean) {\n this._reader = reader;\n this._preventCancel = preventCancel;\n }\n\n next(): Promise> {\n const nextSteps = () => this._nextSteps();\n this._ongoingPromise = this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) :\n nextSteps();\n return this._ongoingPromise;\n }\n\n return(value: any): Promise> {\n const returnSteps = () => this._returnSteps(value);\n return this._ongoingPromise ?\n transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) :\n returnSteps();\n }\n\n private _nextSteps(): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value: undefined, done: true });\n }\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n\n let resolvePromise!: (result: ReadableStreamDefaultReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n this._ongoingPromise = undefined;\n // This needs to be delayed by one microtask, otherwise we stop pulling too early which breaks a test.\n // FIXME Is this a bug in the specification, or in the test?\n queueMicrotask(() => resolvePromise({ value: chunk, done: false }));\n },\n _closeSteps: () => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n resolvePromise({ value: undefined, done: true });\n },\n _errorSteps: reason => {\n this._ongoingPromise = undefined;\n this._isFinished = true;\n ReadableStreamReaderGenericRelease(reader);\n rejectPromise(reason);\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n return promise;\n }\n\n private _returnSteps(value: any): Promise> {\n if (this._isFinished) {\n return Promise.resolve({ value, done: true });\n }\n this._isFinished = true;\n\n const reader = this._reader;\n assert(reader._ownerReadableStream !== undefined);\n assert(reader._readRequests.length === 0);\n\n if (!this._preventCancel) {\n const result = ReadableStreamReaderGenericCancel(reader, value);\n ReadableStreamReaderGenericRelease(reader);\n return transformPromiseWith(result, () => ({ value, done: true }));\n }\n\n ReadableStreamReaderGenericRelease(reader);\n return promiseResolvedWith({ value, done: true });\n }\n}\n\ninterface ReadableStreamAsyncIteratorInstance extends ReadableStreamAsyncIterator {\n /** @interal */\n _asyncIteratorImpl: ReadableStreamAsyncIteratorImpl;\n\n next(): Promise>;\n\n return(value?: any): Promise>;\n}\n\nconst ReadableStreamAsyncIteratorPrototype: ReadableStreamAsyncIteratorInstance = {\n next(this: ReadableStreamAsyncIteratorInstance): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('next'));\n }\n return this._asyncIteratorImpl.next();\n },\n\n return(this: ReadableStreamAsyncIteratorInstance, value: any): Promise> {\n if (!IsReadableStreamAsyncIterator(this)) {\n return promiseRejectedWith(streamAsyncIteratorBrandCheckException('return'));\n }\n return this._asyncIteratorImpl.return(value);\n }\n} as any;\nif (AsyncIteratorPrototype !== undefined) {\n Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype);\n}\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamAsyncIterator(stream: ReadableStream,\n preventCancel: boolean): ReadableStreamAsyncIterator {\n const reader = AcquireReadableStreamDefaultReader(stream);\n const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel);\n const iterator: ReadableStreamAsyncIteratorInstance = Object.create(ReadableStreamAsyncIteratorPrototype);\n iterator._asyncIteratorImpl = impl;\n return iterator;\n}\n\nfunction IsReadableStreamAsyncIterator(x: any): x is ReadableStreamAsyncIterator {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_asyncIteratorImpl')) {\n return false;\n }\n\n try {\n // noinspection SuspiciousTypeOfGuard\n return (x as ReadableStreamAsyncIteratorInstance)._asyncIteratorImpl instanceof\n ReadableStreamAsyncIteratorImpl;\n } catch {\n return false;\n }\n}\n\n// Helper functions for the ReadableStream.\n\nfunction streamAsyncIteratorBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`);\n}\n","/// \n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN#Polyfill\nconst NumberIsNaN: typeof Number.isNaN = Number.isNaN || function (x) {\n // eslint-disable-next-line no-self-compare\n return x !== x;\n};\n\nexport default NumberIsNaN;\n","import { reflectCall } from 'lib/helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport assert from '../../stub/assert';\n\ndeclare global {\n interface ArrayBuffer {\n readonly detached: boolean;\n\n transfer(): ArrayBuffer;\n }\n\n function structuredClone(value: T, options: { transfer: ArrayBuffer[] }): T;\n}\n\nexport function CreateArrayFromList(elements: T): T {\n // We use arrays to represent lists, so this is basically a no-op.\n // Do a slice though just in case we happen to depend on the unique-ness.\n return elements.slice() as T;\n}\n\nexport function CopyDataBlockBytes(dest: ArrayBuffer,\n destOffset: number,\n src: ArrayBuffer,\n srcOffset: number,\n n: number) {\n new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset);\n}\n\nexport let TransferArrayBuffer = (O: ArrayBuffer): ArrayBuffer => {\n if (typeof O.transfer === 'function') {\n TransferArrayBuffer = buffer => buffer.transfer();\n } else if (typeof structuredClone === 'function') {\n TransferArrayBuffer = buffer => structuredClone(buffer, { transfer: [buffer] });\n } else {\n // Not implemented correctly\n TransferArrayBuffer = buffer => buffer;\n }\n return TransferArrayBuffer(O);\n};\n\nexport function CanTransferArrayBuffer(O: ArrayBuffer): boolean {\n return !IsDetachedBuffer(O);\n}\n\nexport let IsDetachedBuffer = (O: ArrayBuffer): boolean => {\n if (typeof O.detached === 'boolean') {\n IsDetachedBuffer = buffer => buffer.detached;\n } else {\n // Not implemented correctly\n IsDetachedBuffer = buffer => buffer.byteLength === 0;\n }\n return IsDetachedBuffer(O);\n};\n\nexport function ArrayBufferSlice(buffer: ArrayBuffer, begin: number, end: number): ArrayBuffer {\n // ArrayBuffer.prototype.slice is not available on IE10\n // https://www.caniuse.com/mdn-javascript_builtins_arraybuffer_slice\n if (buffer.slice) {\n return buffer.slice(begin, end);\n }\n const length = end - begin;\n const slice = new ArrayBuffer(length);\n CopyDataBlockBytes(slice, 0, buffer, begin, length);\n return slice;\n}\n\nexport type MethodName = {\n [P in keyof T]: T[P] extends Function | undefined ? P : never;\n}[keyof T];\n\nexport function GetMethod>(receiver: T, prop: K): T[K] | undefined {\n const func = receiver[prop];\n if (func === undefined || func === null) {\n return undefined;\n }\n if (typeof func !== 'function') {\n throw new TypeError(`${String(prop)} is not a function`);\n }\n return func;\n}\n\nexport interface SyncIteratorRecord {\n iterator: Iterator,\n nextMethod: Iterator['next'],\n done: boolean;\n}\n\nexport interface AsyncIteratorRecord {\n iterator: AsyncIterator,\n nextMethod: AsyncIterator['next'],\n done: boolean;\n}\n\nexport type SyncOrAsyncIteratorRecord = SyncIteratorRecord | AsyncIteratorRecord;\n\nexport function CreateAsyncFromSyncIterator(syncIteratorRecord: SyncIteratorRecord): AsyncIteratorRecord {\n // Instead of re-implementing CreateAsyncFromSyncIterator and %AsyncFromSyncIteratorPrototype%,\n // we use yield* inside an async generator function to achieve the same result.\n\n // Wrap the sync iterator inside a sync iterable, so we can use it with yield*.\n const syncIterable = {\n [Symbol.iterator]: () => syncIteratorRecord.iterator\n };\n // Create an async generator function and immediately invoke it.\n const asyncIterator = (async function* () {\n return yield* syncIterable;\n }());\n // Return as an async iterator record.\n const nextMethod = asyncIterator.next;\n return { iterator: asyncIterator, nextMethod, done: false };\n}\n\nexport type SyncOrAsyncIterable = Iterable | AsyncIterable;\nexport type SyncOrAsyncIteratorMethod = () => (Iterator | AsyncIterator);\n\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint: 'async',\n method?: SyncOrAsyncIteratorMethod\n): AsyncIteratorRecord;\nfunction GetIterator(\n obj: Iterable,\n hint: 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncIteratorRecord;\nfunction GetIterator(\n obj: SyncOrAsyncIterable,\n hint = 'sync',\n method?: SyncOrAsyncIteratorMethod\n): SyncOrAsyncIteratorRecord {\n assert(hint === 'sync' || hint === 'async');\n if (method === undefined) {\n if (hint === 'async') {\n method = GetMethod(obj as AsyncIterable, Symbol.asyncIterator);\n if (method === undefined) {\n const syncMethod = GetMethod(obj as Iterable, Symbol.iterator);\n const syncIteratorRecord = GetIterator(obj as Iterable, 'sync', syncMethod);\n return CreateAsyncFromSyncIterator(syncIteratorRecord);\n }\n } else {\n method = GetMethod(obj as Iterable, Symbol.iterator);\n }\n }\n if (method === undefined) {\n throw new TypeError('The object is not iterable');\n }\n const iterator = reflectCall(method, obj, []);\n if (!typeIsObject(iterator)) {\n throw new TypeError('The iterator method must return an object');\n }\n const nextMethod = iterator.next;\n return { iterator, nextMethod, done: false } as SyncOrAsyncIteratorRecord;\n}\n\nexport { GetIterator };\n\nexport function IteratorNext(iteratorRecord: AsyncIteratorRecord): Promise> {\n const result = reflectCall(iteratorRecord.nextMethod, iteratorRecord.iterator, []);\n if (!typeIsObject(result)) {\n throw new TypeError('The iterator.next() method must return an object');\n }\n return result;\n}\n\nexport function IteratorComplete(\n iterResult: IteratorResult\n): iterResult is IteratorReturnResult {\n assert(typeIsObject(iterResult));\n return Boolean(iterResult.done);\n}\n\nexport function IteratorValue(iterResult: IteratorYieldResult): T {\n assert(typeIsObject(iterResult));\n return iterResult.value;\n}\n","import NumberIsNaN from '../../stub/number-isnan';\nimport { ArrayBufferSlice } from './ecmascript';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function IsNonNegativeNumber(v: number): boolean {\n if (typeof v !== 'number') {\n return false;\n }\n\n if (NumberIsNaN(v)) {\n return false;\n }\n\n if (v < 0) {\n return false;\n }\n\n return true;\n}\n\nexport function CloneAsUint8Array(O: NonShared): NonShared {\n const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength);\n return new Uint8Array(buffer) as NonShared;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsNonNegativeNumber } from './miscellaneous';\n\nexport interface QueueContainer {\n _queue: SimpleQueue;\n _queueTotalSize: number;\n}\n\nexport interface QueuePair {\n value: T;\n size: number;\n}\n\nexport function DequeueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.shift()!;\n container._queueTotalSize -= pair.size;\n if (container._queueTotalSize < 0) {\n container._queueTotalSize = 0;\n }\n\n return pair.value;\n}\n\nexport function EnqueueValueWithSize(container: QueueContainer>, value: T, size: number) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n if (!IsNonNegativeNumber(size) || size === Infinity) {\n throw new RangeError('Size must be a finite, non-NaN, non-negative number.');\n }\n\n container._queue.push({ value, size });\n container._queueTotalSize += size;\n}\n\nexport function PeekQueueValue(container: QueueContainer>): T {\n assert('_queue' in container && '_queueTotalSize' in container);\n assert(container._queue.length > 0);\n\n const pair = container._queue.peek();\n return pair.value;\n}\n\nexport function ResetQueue(container: QueueContainer) {\n assert('_queue' in container && '_queueTotalSize' in container);\n\n container._queue = new SimpleQueue();\n container._queueTotalSize = 0;\n}\n","export type TypedArray =\n | Int8Array\n | Uint8Array\n | Uint8ClampedArray\n | Int16Array\n | Uint16Array\n | Int32Array\n | Uint32Array\n | Float32Array\n | Float64Array;\n\nexport type NonShared = T & {\n buffer: ArrayBuffer;\n}\n\nexport interface ArrayBufferViewConstructor {\n new(buffer: ArrayBuffer, byteOffset: number, length?: number): T;\n\n readonly prototype: T;\n}\n\nexport interface TypedArrayConstructor extends ArrayBufferViewConstructor {\n readonly BYTES_PER_ELEMENT: number;\n}\n\nexport type DataViewConstructor = ArrayBufferViewConstructor;\n\nfunction isDataViewConstructor(ctor: Function): ctor is DataViewConstructor {\n return ctor === DataView;\n}\n\nexport function isDataView(view: ArrayBufferView): view is DataView {\n return isDataViewConstructor(view.constructor);\n}\n\nexport function arrayBufferViewElementSize(ctor: ArrayBufferViewConstructor): number {\n if (isDataViewConstructor(ctor)) {\n return 1;\n }\n return (ctor as unknown as TypedArrayConstructor).BYTES_PER_ELEMENT;\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport { ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n IsReadableStreamDefaultReader,\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n ReadableStreamHasDefaultReader,\n type ReadRequest\n} from './default-reader';\nimport {\n ReadableStreamAddReadIntoRequest,\n ReadableStreamFulfillReadIntoRequest,\n ReadableStreamGetNumReadIntoRequests,\n ReadableStreamHasBYOBReader,\n type ReadIntoRequest\n} from './byob-reader';\nimport NumberIsInteger from '../../stub/number-isinteger';\nimport {\n IsReadableStreamLocked,\n type ReadableByteStream,\n ReadableStreamClose,\n ReadableStreamError\n} from '../readable-stream';\nimport type { ValidatedUnderlyingByteSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport {\n ArrayBufferSlice,\n CanTransferArrayBuffer,\n CopyDataBlockBytes,\n IsDetachedBuffer,\n TransferArrayBuffer\n} from '../abstract-ops/ecmascript';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\nimport { assertRequiredArgument, convertUnsignedLongLongWithEnforceRange } from '../validators/basic';\nimport {\n type ArrayBufferViewConstructor,\n arrayBufferViewElementSize,\n type NonShared,\n type TypedArrayConstructor\n} from '../helpers/array-buffer-view';\n\n/**\n * A pull-into request in a {@link ReadableByteStreamController}.\n *\n * @public\n */\nexport class ReadableStreamBYOBRequest {\n /** @internal */\n _associatedReadableByteStreamController!: ReadableByteStreamController;\n /** @internal */\n _view!: NonShared | null;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the view for writing in to, or `null` if the BYOB request has already been responded to.\n */\n get view(): ArrayBufferView | null {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('view');\n }\n\n return this._view;\n }\n\n /**\n * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into\n * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.\n *\n * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer\n * modifiable.\n */\n respond(bytesWritten: number): void;\n respond(bytesWritten: number | undefined): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respond');\n }\n assertRequiredArgument(bytesWritten, 1, 'respond');\n bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, 'First parameter');\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(this._view!.buffer)) {\n throw new TypeError(`The BYOB request's buffer has been detached and so cannot be used as a response`);\n }\n\n assert(this._view!.byteLength > 0);\n assert(this._view!.buffer.byteLength > 0);\n\n ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten);\n }\n\n /**\n * Indicates to the associated readable byte stream that instead of writing into\n * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,\n * which will be given to the consumer of the readable byte stream.\n *\n * After this method is called, `view` will be transferred and no longer modifiable.\n */\n respondWithNewView(view: ArrayBufferView): void;\n respondWithNewView(view: NonShared): void {\n if (!IsReadableStreamBYOBRequest(this)) {\n throw byobRequestBrandCheckException('respondWithNewView');\n }\n assertRequiredArgument(view, 1, 'respondWithNewView');\n\n if (!ArrayBuffer.isView(view)) {\n throw new TypeError('You can only respond with array buffer views');\n }\n\n if (this._associatedReadableByteStreamController === undefined) {\n throw new TypeError('This BYOB request has been invalidated');\n }\n\n if (IsDetachedBuffer(view.buffer)) {\n throw new TypeError('The given view\\'s buffer has been detached and so cannot be used as a response');\n }\n\n ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBRequest.prototype, {\n respond: { enumerable: true },\n respondWithNewView: { enumerable: true },\n view: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respond, 'respond');\nsetFunctionName(ReadableStreamBYOBRequest.prototype.respondWithNewView, 'respondWithNewView');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBRequest.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBRequest',\n configurable: true\n });\n}\n\ninterface ByteQueueElement {\n buffer: ArrayBuffer;\n byteOffset: number;\n byteLength: number;\n}\n\ntype PullIntoDescriptor = NonShared> =\n DefaultPullIntoDescriptor\n | BYOBPullIntoDescriptor;\n\ninterface DefaultPullIntoDescriptor {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: TypedArrayConstructor;\n readerType: 'default' | 'none';\n}\n\ninterface BYOBPullIntoDescriptor = NonShared> {\n buffer: ArrayBuffer;\n bufferByteLength: number;\n byteOffset: number;\n byteLength: number;\n bytesFilled: number;\n minimumFill: number;\n elementSize: number;\n viewConstructor: ArrayBufferViewConstructor;\n readerType: 'byob' | 'none';\n}\n\n/**\n * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableByteStreamController {\n /** @internal */\n _controlledReadableByteStream!: ReadableByteStream;\n /** @internal */\n _queue!: SimpleQueue;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n /** @internal */\n _autoAllocateChunkSize: number | undefined;\n /** @internal */\n _byobRequest: ReadableStreamBYOBRequest | null;\n /** @internal */\n _pendingPullIntos!: SimpleQueue;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the current BYOB pull request, or `null` if there isn't one.\n */\n get byobRequest(): ReadableStreamBYOBRequest | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('byobRequest');\n }\n\n return ReadableByteStreamControllerGetBYOBRequest(this);\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('desiredSize');\n }\n\n return ReadableByteStreamControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('close');\n }\n\n if (this._closeRequested) {\n throw new TypeError('The stream has already been closed; do not close it again!');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`);\n }\n\n ReadableByteStreamControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk chunk in the controlled readable stream.\n * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.\n */\n enqueue(chunk: ArrayBufferView): void;\n enqueue(chunk: NonShared): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('enqueue');\n }\n\n assertRequiredArgument(chunk, 1, 'enqueue');\n if (!ArrayBuffer.isView(chunk)) {\n throw new TypeError('chunk must be an array buffer view');\n }\n if (chunk.byteLength === 0) {\n throw new TypeError('chunk must have non-zero byteLength');\n }\n if (chunk.buffer.byteLength === 0) {\n throw new TypeError(`chunk's buffer must have non-zero byteLength`);\n }\n\n if (this._closeRequested) {\n throw new TypeError('stream is closed or draining');\n }\n\n const state = this._controlledReadableByteStream._state;\n if (state !== 'readable') {\n throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`);\n }\n\n ReadableByteStreamControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableByteStreamController(this)) {\n throw byteStreamControllerBrandCheckException('error');\n }\n\n ReadableByteStreamControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ReadableByteStreamControllerClearPendingPullIntos(this);\n\n ResetQueue(this);\n\n const result = this._cancelAlgorithm(reason);\n ReadableByteStreamControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest>): void {\n const stream = this._controlledReadableByteStream;\n assert(ReadableStreamHasDefaultReader(stream));\n\n if (this._queueTotalSize > 0) {\n assert(ReadableStreamGetNumReadRequests(stream) === 0);\n\n ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest);\n return;\n }\n\n const autoAllocateChunkSize = this._autoAllocateChunkSize;\n if (autoAllocateChunkSize !== undefined) {\n let buffer: ArrayBuffer;\n try {\n buffer = new ArrayBuffer(autoAllocateChunkSize);\n } catch (bufferE) {\n readRequest._errorSteps(bufferE);\n return;\n }\n\n const pullIntoDescriptor: DefaultPullIntoDescriptor = {\n buffer,\n bufferByteLength: autoAllocateChunkSize,\n byteOffset: 0,\n byteLength: autoAllocateChunkSize,\n bytesFilled: 0,\n minimumFill: 1,\n elementSize: 1,\n viewConstructor: Uint8Array,\n readerType: 'default'\n };\n\n this._pendingPullIntos.push(pullIntoDescriptor);\n }\n\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableByteStreamControllerCallPullIfNeeded(this);\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n if (this._pendingPullIntos.length > 0) {\n const firstPullInto = this._pendingPullIntos.peek();\n firstPullInto.readerType = 'none';\n\n this._pendingPullIntos = new SimpleQueue();\n this._pendingPullIntos.push(firstPullInto);\n }\n }\n}\n\nObject.defineProperties(ReadableByteStreamController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n byobRequest: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableByteStreamController.prototype.close, 'close');\nsetFunctionName(ReadableByteStreamController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableByteStreamController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableByteStreamController.prototype, Symbol.toStringTag, {\n value: 'ReadableByteStreamController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableByteStreamController.\n\nexport function IsReadableByteStreamController(x: any): x is ReadableByteStreamController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableByteStream')) {\n return false;\n }\n\n return x instanceof ReadableByteStreamController;\n}\n\nfunction IsReadableStreamBYOBRequest(x: any): x is ReadableStreamBYOBRequest {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_associatedReadableByteStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBRequest;\n}\n\nfunction ReadableByteStreamControllerCallPullIfNeeded(controller: ReadableByteStreamController): void {\n const shouldPull = ReadableByteStreamControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n // TODO: Test controller argument\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableByteStreamControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableByteStreamControllerClearPendingPullIntos(controller: ReadableByteStreamController) {\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n controller._pendingPullIntos = new SimpleQueue();\n}\n\nfunction ReadableByteStreamControllerCommitPullIntoDescriptor>(\n stream: ReadableByteStream,\n pullIntoDescriptor: PullIntoDescriptor\n) {\n assert(stream._state !== 'errored');\n assert(pullIntoDescriptor.readerType !== 'none');\n\n let done = false;\n if (stream._state === 'closed') {\n assert(pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize === 0);\n done = true;\n }\n\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n if (pullIntoDescriptor.readerType === 'default') {\n ReadableStreamFulfillReadRequest(stream, filledView as unknown as NonShared, done);\n } else {\n assert(pullIntoDescriptor.readerType === 'byob');\n ReadableStreamFulfillReadIntoRequest(stream, filledView, done);\n }\n}\n\nfunction ReadableByteStreamControllerConvertPullIntoDescriptor>(\n pullIntoDescriptor: PullIntoDescriptor\n): T {\n const bytesFilled = pullIntoDescriptor.bytesFilled;\n const elementSize = pullIntoDescriptor.elementSize;\n\n assert(bytesFilled <= pullIntoDescriptor.byteLength);\n assert(bytesFilled % elementSize === 0);\n\n return new pullIntoDescriptor.viewConstructor(\n pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize) as T;\n}\n\nfunction ReadableByteStreamControllerEnqueueChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n controller._queue.push({ buffer, byteOffset, byteLength });\n controller._queueTotalSize += byteLength;\n}\n\nfunction ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller: ReadableByteStreamController,\n buffer: ArrayBuffer,\n byteOffset: number,\n byteLength: number) {\n let clonedChunk;\n try {\n clonedChunk = ArrayBufferSlice(buffer, byteOffset, byteOffset + byteLength);\n } catch (cloneE) {\n ReadableByteStreamControllerError(controller, cloneE);\n throw cloneE;\n }\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, clonedChunk, 0, byteLength);\n}\n\nfunction ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.readerType === 'none');\n if (firstDescriptor.bytesFilled > 0) {\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n firstDescriptor.buffer,\n firstDescriptor.byteOffset,\n firstDescriptor.bytesFilled\n );\n }\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n}\n\nfunction ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller: ReadableByteStreamController,\n pullIntoDescriptor: PullIntoDescriptor) {\n const maxBytesToCopy = Math.min(controller._queueTotalSize,\n pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled);\n const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy;\n\n let totalBytesToCopyRemaining = maxBytesToCopy;\n let ready = false;\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n const remainderBytes = maxBytesFilled % pullIntoDescriptor.elementSize;\n const maxAlignedBytes = maxBytesFilled - remainderBytes;\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n if (maxAlignedBytes >= pullIntoDescriptor.minimumFill) {\n totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled;\n ready = true;\n }\n\n const queue = controller._queue;\n\n while (totalBytesToCopyRemaining > 0) {\n const headOfQueue = queue.peek();\n\n const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength);\n\n const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy);\n\n if (headOfQueue.byteLength === bytesToCopy) {\n queue.shift();\n } else {\n headOfQueue.byteOffset += bytesToCopy;\n headOfQueue.byteLength -= bytesToCopy;\n }\n controller._queueTotalSize -= bytesToCopy;\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor);\n\n totalBytesToCopyRemaining -= bytesToCopy;\n }\n\n if (!ready) {\n assert(controller._queueTotalSize === 0);\n assert(pullIntoDescriptor.bytesFilled > 0);\n assert(pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill);\n }\n\n return ready;\n}\n\nfunction ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller: ReadableByteStreamController,\n size: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(controller._pendingPullIntos.length === 0 || controller._pendingPullIntos.peek() === pullIntoDescriptor);\n assert(controller._byobRequest === null);\n pullIntoDescriptor.bytesFilled += size;\n}\n\nfunction ReadableByteStreamControllerHandleQueueDrain(controller: ReadableByteStreamController) {\n assert(controller._controlledReadableByteStream._state === 'readable');\n\n if (controller._queueTotalSize === 0 && controller._closeRequested) {\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(controller._controlledReadableByteStream);\n } else {\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n }\n}\n\nfunction ReadableByteStreamControllerInvalidateBYOBRequest(controller: ReadableByteStreamController) {\n if (controller._byobRequest === null) {\n return;\n }\n\n controller._byobRequest._associatedReadableByteStreamController = undefined!;\n controller._byobRequest._view = null!;\n controller._byobRequest = null;\n}\n\nfunction ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller: ReadableByteStreamController) {\n assert(!controller._closeRequested);\n\n while (controller._pendingPullIntos.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n\n const pullIntoDescriptor = controller._pendingPullIntos.peek();\n assert(pullIntoDescriptor.readerType !== 'none');\n\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n ReadableByteStreamControllerCommitPullIntoDescriptor(\n controller._controlledReadableByteStream,\n pullIntoDescriptor\n );\n }\n }\n}\n\nfunction ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller: ReadableByteStreamController) {\n const reader = controller._controlledReadableByteStream._reader;\n assert(IsReadableStreamDefaultReader(reader));\n while (reader._readRequests.length > 0) {\n if (controller._queueTotalSize === 0) {\n return;\n }\n const readRequest = reader._readRequests.shift();\n ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest);\n }\n}\n\nexport function ReadableByteStreamControllerPullInto>(\n controller: ReadableByteStreamController,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = controller._controlledReadableByteStream;\n\n const ctor = view.constructor as ArrayBufferViewConstructor;\n const elementSize = arrayBufferViewElementSize(ctor);\n\n const { byteOffset, byteLength } = view;\n\n const minimumFill = min * elementSize;\n assert(minimumFill >= elementSize && minimumFill <= byteLength);\n assert(minimumFill % elementSize === 0);\n\n let buffer: ArrayBuffer;\n try {\n buffer = TransferArrayBuffer(view.buffer);\n } catch (e) {\n readIntoRequest._errorSteps(e);\n return;\n }\n\n const pullIntoDescriptor: BYOBPullIntoDescriptor = {\n buffer,\n bufferByteLength: buffer.byteLength,\n byteOffset,\n byteLength,\n bytesFilled: 0,\n minimumFill,\n elementSize,\n viewConstructor: ctor,\n readerType: 'byob'\n };\n\n if (controller._pendingPullIntos.length > 0) {\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n // No ReadableByteStreamControllerCallPullIfNeeded() call since:\n // - No change happens on desiredSize\n // - The source has already been notified of that there's at least 1 pending read(view)\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n return;\n }\n\n if (stream._state === 'closed') {\n const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0);\n readIntoRequest._closeSteps(emptyView);\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) {\n const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor);\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n readIntoRequest._chunkSteps(filledView);\n return;\n }\n\n if (controller._closeRequested) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n readIntoRequest._errorSteps(e);\n return;\n }\n }\n\n controller._pendingPullIntos.push(pullIntoDescriptor);\n\n ReadableStreamAddReadIntoRequest(stream, readIntoRequest);\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInClosedState(controller: ReadableByteStreamController,\n firstDescriptor: PullIntoDescriptor) {\n assert(firstDescriptor.bytesFilled % firstDescriptor.elementSize === 0);\n\n if (firstDescriptor.readerType === 'none') {\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n\n const stream = controller._controlledReadableByteStream;\n if (ReadableStreamHasBYOBReader(stream)) {\n while (ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller);\n ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor);\n }\n }\n}\n\nfunction ReadableByteStreamControllerRespondInReadableState(controller: ReadableByteStreamController,\n bytesWritten: number,\n pullIntoDescriptor: PullIntoDescriptor) {\n assert(pullIntoDescriptor.bytesFilled + bytesWritten <= pullIntoDescriptor.byteLength);\n\n ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor);\n\n if (pullIntoDescriptor.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n return;\n }\n\n if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.minimumFill) {\n // A descriptor for a read() request that is not yet filled up to its minimum length will stay at the head\n // of the queue, so the underlying source can keep filling it.\n return;\n }\n\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n\n const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize;\n if (remainderSize > 0) {\n const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled;\n ReadableByteStreamControllerEnqueueClonedChunkToQueue(\n controller,\n pullIntoDescriptor.buffer,\n end - remainderSize,\n remainderSize\n );\n }\n\n pullIntoDescriptor.bytesFilled -= remainderSize;\n ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor);\n\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n}\n\nfunction ReadableByteStreamControllerRespondInternal(controller: ReadableByteStreamController, bytesWritten: number) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n assert(CanTransferArrayBuffer(firstDescriptor.buffer));\n\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n\n const state = controller._controlledReadableByteStream._state;\n if (state === 'closed') {\n assert(bytesWritten === 0);\n ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor);\n } else {\n assert(state === 'readable');\n assert(bytesWritten > 0);\n ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nfunction ReadableByteStreamControllerShiftPendingPullInto(\n controller: ReadableByteStreamController\n): PullIntoDescriptor {\n assert(controller._byobRequest === null);\n const descriptor = controller._pendingPullIntos.shift()!;\n return descriptor;\n}\n\nfunction ReadableByteStreamControllerShouldCallPull(controller: ReadableByteStreamController): boolean {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return false;\n }\n\n if (controller._closeRequested) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableByteStreamControllerClearAlgorithms(controller: ReadableByteStreamController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\n// A client of ReadableByteStreamController may use these functions directly to bypass state check.\n\nexport function ReadableByteStreamControllerClose(controller: ReadableByteStreamController) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n if (controller._queueTotalSize > 0) {\n controller._closeRequested = true;\n\n return;\n }\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (firstPendingPullInto.bytesFilled % firstPendingPullInto.elementSize !== 0) {\n const e = new TypeError('Insufficient bytes to fill elements in the given buffer');\n ReadableByteStreamControllerError(controller, e);\n\n throw e;\n }\n }\n\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n}\n\nexport function ReadableByteStreamControllerEnqueue(\n controller: ReadableByteStreamController,\n chunk: NonShared\n) {\n const stream = controller._controlledReadableByteStream;\n\n if (controller._closeRequested || stream._state !== 'readable') {\n return;\n }\n\n const { buffer, byteOffset, byteLength } = chunk;\n if (IsDetachedBuffer(buffer)) {\n throw new TypeError('chunk\\'s buffer is detached and so cannot be enqueued');\n }\n const transferredBuffer = TransferArrayBuffer(buffer);\n\n if (controller._pendingPullIntos.length > 0) {\n const firstPendingPullInto = controller._pendingPullIntos.peek();\n if (IsDetachedBuffer(firstPendingPullInto.buffer)) {\n throw new TypeError(\n 'The BYOB request\\'s buffer has been detached and so cannot be filled with an enqueued chunk'\n );\n }\n ReadableByteStreamControllerInvalidateBYOBRequest(controller);\n firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer);\n if (firstPendingPullInto.readerType === 'none') {\n ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto);\n }\n }\n\n if (ReadableStreamHasDefaultReader(stream)) {\n ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller);\n if (ReadableStreamGetNumReadRequests(stream) === 0) {\n assert(controller._pendingPullIntos.length === 0);\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n } else {\n assert(controller._queue.length === 0);\n if (controller._pendingPullIntos.length > 0) {\n assert(controller._pendingPullIntos.peek().readerType === 'default');\n ReadableByteStreamControllerShiftPendingPullInto(controller);\n }\n const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength);\n ReadableStreamFulfillReadRequest(stream, transferredView as NonShared, false);\n }\n } else if (ReadableStreamHasBYOBReader(stream)) {\n // TODO: Ideally in this branch detaching should happen only if the buffer is not consumed fully.\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller);\n } else {\n assert(!IsReadableStreamLocked(stream));\n ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength);\n }\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableByteStreamControllerError(controller: ReadableByteStreamController, e: any) {\n const stream = controller._controlledReadableByteStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ReadableByteStreamControllerClearPendingPullIntos(controller);\n\n ResetQueue(controller);\n ReadableByteStreamControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableByteStreamControllerFillReadRequestFromQueue(\n controller: ReadableByteStreamController,\n readRequest: ReadRequest>\n) {\n assert(controller._queueTotalSize > 0);\n\n const entry = controller._queue.shift();\n controller._queueTotalSize -= entry.byteLength;\n\n ReadableByteStreamControllerHandleQueueDrain(controller);\n\n const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength);\n readRequest._chunkSteps(view as NonShared);\n}\n\nexport function ReadableByteStreamControllerGetBYOBRequest(\n controller: ReadableByteStreamController\n): ReadableStreamBYOBRequest | null {\n if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) {\n const firstDescriptor = controller._pendingPullIntos.peek();\n const view = new Uint8Array(firstDescriptor.buffer,\n firstDescriptor.byteOffset + firstDescriptor.bytesFilled,\n firstDescriptor.byteLength - firstDescriptor.bytesFilled);\n\n const byobRequest: ReadableStreamBYOBRequest = Object.create(ReadableStreamBYOBRequest.prototype);\n SetUpReadableStreamBYOBRequest(byobRequest, controller, view as NonShared);\n controller._byobRequest = byobRequest;\n }\n return controller._byobRequest;\n}\n\nfunction ReadableByteStreamControllerGetDesiredSize(controller: ReadableByteStreamController): number | null {\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nexport function ReadableByteStreamControllerRespond(controller: ReadableByteStreamController, bytesWritten: number) {\n assert(controller._pendingPullIntos.length > 0);\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (bytesWritten !== 0) {\n throw new TypeError('bytesWritten must be 0 when calling respond() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (bytesWritten === 0) {\n throw new TypeError('bytesWritten must be greater than 0 when calling respond() on a readable stream');\n }\n if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) {\n throw new RangeError('bytesWritten out of range');\n }\n }\n\n firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer);\n\n ReadableByteStreamControllerRespondInternal(controller, bytesWritten);\n}\n\nexport function ReadableByteStreamControllerRespondWithNewView(controller: ReadableByteStreamController,\n view: NonShared) {\n assert(controller._pendingPullIntos.length > 0);\n assert(!IsDetachedBuffer(view.buffer));\n\n const firstDescriptor = controller._pendingPullIntos.peek();\n const state = controller._controlledReadableByteStream._state;\n\n if (state === 'closed') {\n if (view.byteLength !== 0) {\n throw new TypeError('The view\\'s length must be 0 when calling respondWithNewView() on a closed stream');\n }\n } else {\n assert(state === 'readable');\n if (view.byteLength === 0) {\n throw new TypeError(\n 'The view\\'s length must be greater than 0 when calling respondWithNewView() on a readable stream'\n );\n }\n }\n\n if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) {\n throw new RangeError('The region specified by view does not match byobRequest');\n }\n if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) {\n throw new RangeError('The buffer of view has different capacity than byobRequest');\n }\n if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) {\n throw new RangeError('The region specified by view is larger than byobRequest');\n }\n\n const viewByteLength = view.byteLength;\n firstDescriptor.buffer = TransferArrayBuffer(view.buffer);\n ReadableByteStreamControllerRespondInternal(controller, viewByteLength);\n}\n\nexport function SetUpReadableByteStreamController(stream: ReadableByteStream,\n controller: ReadableByteStreamController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n autoAllocateChunkSize: number | undefined) {\n assert(stream._readableStreamController === undefined);\n if (autoAllocateChunkSize !== undefined) {\n assert(NumberIsInteger(autoAllocateChunkSize));\n assert(autoAllocateChunkSize > 0);\n }\n\n controller._controlledReadableByteStream = stream;\n\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._byobRequest = null;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._closeRequested = false;\n controller._started = false;\n\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._autoAllocateChunkSize = autoAllocateChunkSize;\n\n controller._pendingPullIntos = new SimpleQueue();\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableByteStreamControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableByteStreamControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableByteStreamControllerFromUnderlyingSource(\n stream: ReadableByteStream,\n underlyingByteSource: ValidatedUnderlyingByteSource,\n highWaterMark: number\n) {\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingByteSource.start !== undefined) {\n startAlgorithm = () => underlyingByteSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingByteSource.pull !== undefined) {\n pullAlgorithm = () => underlyingByteSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingByteSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingByteSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize;\n if (autoAllocateChunkSize === 0) {\n throw new TypeError('autoAllocateChunkSize must be greater than 0');\n }\n\n SetUpReadableByteStreamController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize\n );\n}\n\nfunction SetUpReadableStreamBYOBRequest(request: ReadableStreamBYOBRequest,\n controller: ReadableByteStreamController,\n view: NonShared) {\n assert(IsReadableByteStreamController(controller));\n assert(typeof view === 'object');\n assert(ArrayBuffer.isView(view));\n assert(!IsDetachedBuffer(view.buffer));\n request._associatedReadableByteStreamController = controller;\n request._view = view;\n}\n\n// Helper functions for the ReadableStreamBYOBRequest.\n\nfunction byobRequestBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`);\n}\n\n// Helper functions for the ReadableByteStreamController.\n\nfunction byteStreamControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`);\n}\n","import { assertDictionary, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from '../readable-stream/reader-options';\n\nexport function convertReaderOptions(options: ReadableStreamGetReaderOptions | null | undefined,\n context: string): ReadableStreamGetReaderOptions {\n assertDictionary(options, context);\n const mode = options?.mode;\n return {\n mode: mode === undefined ? undefined : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`)\n };\n}\n\nfunction convertReadableStreamReaderMode(mode: string, context: string): 'byob' {\n mode = `${mode}`;\n if (mode !== 'byob') {\n throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`);\n }\n return mode;\n}\n\nexport function convertByobReadOptions(\n options: ReadableStreamBYOBReaderReadOptions | null | undefined,\n context: string\n): ValidatedReadableStreamBYOBReaderReadOptions {\n assertDictionary(options, context);\n const min = options?.min ?? 1;\n return {\n min: convertUnsignedLongLongWithEnforceRange(\n min,\n `${context} has member 'min' that`\n )\n };\n}\n","import assert from '../../stub/assert';\nimport { SimpleQueue } from '../simple-queue';\nimport {\n ReadableStreamReaderGenericCancel,\n ReadableStreamReaderGenericInitialize,\n ReadableStreamReaderGenericRelease,\n readerLockException\n} from './generic-reader';\nimport { IsReadableStreamLocked, type ReadableByteStream, type ReadableStream } from '../readable-stream';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamController,\n ReadableByteStreamControllerPullInto\n} from './byte-stream-controller';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { newPromise, promiseRejectedWith } from '../helpers/webidl';\nimport { assertRequiredArgument } from '../validators/basic';\nimport { assertReadableStream } from '../validators/readable-stream';\nimport { IsDetachedBuffer } from '../abstract-ops/ecmascript';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ValidatedReadableStreamBYOBReaderReadOptions\n} from './reader-options';\nimport { convertByobReadOptions } from '../validators/reader-options';\nimport { isDataView, type NonShared, type TypedArray } from '../helpers/array-buffer-view';\n\n/**\n * A result returned by {@link ReadableStreamBYOBReader.read}.\n *\n * @public\n */\nexport type ReadableStreamBYOBReadResult = {\n done: false;\n value: T;\n} | {\n done: true;\n value: T | undefined;\n};\n\n// Abstract operations for the ReadableStream.\n\nexport function AcquireReadableStreamBYOBReader(stream: ReadableByteStream): ReadableStreamBYOBReader {\n return new ReadableStreamBYOBReader(stream as ReadableStream);\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamAddReadIntoRequest>(\n stream: ReadableByteStream,\n readIntoRequest: ReadIntoRequest\n): void {\n assert(IsReadableStreamBYOBReader(stream._reader));\n assert(stream._state === 'readable' || stream._state === 'closed');\n\n (stream._reader! as ReadableStreamBYOBReader)._readIntoRequests.push(readIntoRequest);\n}\n\nexport function ReadableStreamFulfillReadIntoRequest(stream: ReadableByteStream,\n chunk: ArrayBufferView,\n done: boolean) {\n const reader = stream._reader as ReadableStreamBYOBReader;\n\n assert(reader._readIntoRequests.length > 0);\n\n const readIntoRequest = reader._readIntoRequests.shift()!;\n if (done) {\n readIntoRequest._closeSteps(chunk);\n } else {\n readIntoRequest._chunkSteps(chunk);\n }\n}\n\nexport function ReadableStreamGetNumReadIntoRequests(stream: ReadableByteStream): number {\n return (stream._reader as ReadableStreamBYOBReader)._readIntoRequests.length;\n}\n\nexport function ReadableStreamHasBYOBReader(stream: ReadableByteStream): boolean {\n const reader = stream._reader;\n\n if (reader === undefined) {\n return false;\n }\n\n if (!IsReadableStreamBYOBReader(reader)) {\n return false;\n }\n\n return true;\n}\n\n// Readers\n\nexport interface ReadIntoRequest> {\n _chunkSteps(chunk: T): void;\n\n _closeSteps(chunk: T | undefined): void;\n\n _errorSteps(e: any): void;\n}\n\n/**\n * A BYOB reader vended by a {@link ReadableStream}.\n *\n * @public\n */\nexport class ReadableStreamBYOBReader {\n /** @internal */\n _ownerReadableStream!: ReadableByteStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _readIntoRequests: SimpleQueue>;\n\n constructor(stream: ReadableStream) {\n assertRequiredArgument(stream, 1, 'ReadableStreamBYOBReader');\n assertReadableStream(stream, 'First parameter');\n\n if (IsReadableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive reading by another reader');\n }\n\n if (!IsReadableByteStreamController(stream._readableStreamController)) {\n throw new TypeError('Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte ' +\n 'source');\n }\n\n ReadableStreamReaderGenericInitialize(this, stream);\n\n this._readIntoRequests = new SimpleQueue();\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the reader's lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('cancel'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('cancel'));\n }\n\n return ReadableStreamReaderGenericCancel(this, reason);\n }\n\n /**\n * Attempts to reads bytes into view, and returns a promise resolved with the result.\n *\n * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.\n */\n read(\n view: T,\n options?: ReadableStreamBYOBReaderReadOptions\n ): Promise>;\n read>(\n view: T,\n rawOptions: ReadableStreamBYOBReaderReadOptions | null | undefined = {}\n ): Promise> {\n if (!IsReadableStreamBYOBReader(this)) {\n return promiseRejectedWith(byobReaderBrandCheckException('read'));\n }\n\n if (!ArrayBuffer.isView(view)) {\n return promiseRejectedWith(new TypeError('view must be an array buffer view'));\n }\n if (view.byteLength === 0) {\n return promiseRejectedWith(new TypeError('view must have non-zero byteLength'));\n }\n if (view.buffer.byteLength === 0) {\n return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`));\n }\n if (IsDetachedBuffer(view.buffer)) {\n return promiseRejectedWith(new TypeError('view\\'s buffer has been detached'));\n }\n\n let options: ValidatedReadableStreamBYOBReaderReadOptions;\n try {\n options = convertByobReadOptions(rawOptions, 'options');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const min = options.min;\n if (min === 0) {\n return promiseRejectedWith(new TypeError('options.min must be greater than 0'));\n }\n if (!isDataView(view)) {\n if (min > (view as unknown as TypedArray).length) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s length'));\n }\n } else if (min > view.byteLength) {\n return promiseRejectedWith(new RangeError('options.min must be less than or equal to view\\'s byteLength'));\n }\n\n if (this._ownerReadableStream === undefined) {\n return promiseRejectedWith(readerLockException('read from'));\n }\n\n let resolvePromise!: (result: ReadableStreamBYOBReadResult) => void;\n let rejectPromise!: (reason: any) => void;\n const promise = newPromise>((resolve, reject) => {\n resolvePromise = resolve;\n rejectPromise = reject;\n });\n const readIntoRequest: ReadIntoRequest = {\n _chunkSteps: chunk => resolvePromise({ value: chunk, done: false }),\n _closeSteps: chunk => resolvePromise({ value: chunk, done: true }),\n _errorSteps: e => rejectPromise(e)\n };\n ReadableStreamBYOBReaderRead(this, view, min, readIntoRequest);\n return promise;\n }\n\n /**\n * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.\n * If the associated stream is errored when the lock is released, the reader will appear errored in the same way\n * from now on; otherwise, the reader will appear closed.\n *\n * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by\n * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to\n * do so will throw a `TypeError` and leave the reader locked to the stream.\n */\n releaseLock(): void {\n if (!IsReadableStreamBYOBReader(this)) {\n throw byobReaderBrandCheckException('releaseLock');\n }\n\n if (this._ownerReadableStream === undefined) {\n return;\n }\n\n ReadableStreamBYOBReaderRelease(this);\n }\n}\n\nObject.defineProperties(ReadableStreamBYOBReader.prototype, {\n cancel: { enumerable: true },\n read: { enumerable: true },\n releaseLock: { enumerable: true },\n closed: { enumerable: true }\n});\nsetFunctionName(ReadableStreamBYOBReader.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStreamBYOBReader.prototype.read, 'read');\nsetFunctionName(ReadableStreamBYOBReader.prototype.releaseLock, 'releaseLock');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamBYOBReader.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamBYOBReader',\n configurable: true\n });\n}\n\n// Abstract operations for the readers.\n\nexport function IsReadableStreamBYOBReader(x: any): x is ReadableStreamBYOBReader {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readIntoRequests')) {\n return false;\n }\n\n return x instanceof ReadableStreamBYOBReader;\n}\n\nexport function ReadableStreamBYOBReaderRead>(\n reader: ReadableStreamBYOBReader,\n view: T,\n min: number,\n readIntoRequest: ReadIntoRequest\n): void {\n const stream = reader._ownerReadableStream;\n\n assert(stream !== undefined);\n\n stream._disturbed = true;\n\n if (stream._state === 'errored') {\n readIntoRequest._errorSteps(stream._storedError);\n } else {\n ReadableByteStreamControllerPullInto(\n stream._readableStreamController as ReadableByteStreamController,\n view,\n min,\n readIntoRequest\n );\n }\n}\n\nexport function ReadableStreamBYOBReaderRelease(reader: ReadableStreamBYOBReader) {\n ReadableStreamReaderGenericRelease(reader);\n const e = new TypeError('Reader was released');\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n}\n\nexport function ReadableStreamBYOBReaderErrorReadIntoRequests(reader: ReadableStreamBYOBReader, e: any) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._errorSteps(e);\n });\n}\n\n// Helper functions for the ReadableStreamBYOBReader.\n\nfunction byobReaderBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`);\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport NumberIsNaN from '../../stub/number-isnan';\n\nexport function ExtractHighWaterMark(strategy: QueuingStrategy, defaultHWM: number): number {\n const { highWaterMark } = strategy;\n\n if (highWaterMark === undefined) {\n return defaultHWM;\n }\n\n if (NumberIsNaN(highWaterMark) || highWaterMark < 0) {\n throw new RangeError('Invalid highWaterMark');\n }\n\n return highWaterMark;\n}\n\nexport function ExtractSizeAlgorithm(strategy: QueuingStrategy): QueuingStrategySizeCallback {\n const { size } = strategy;\n\n if (!size) {\n return () => 1;\n }\n\n return size;\n}\n","import type { QueuingStrategy, QueuingStrategySizeCallback } from '../queuing-strategy';\nimport { assertDictionary, assertFunction, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategy(init: QueuingStrategy | null | undefined,\n context: string): QueuingStrategy {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n const size = init?.size;\n return {\n highWaterMark: highWaterMark === undefined ? undefined : convertUnrestrictedDouble(highWaterMark),\n size: size === undefined ? undefined : convertQueuingStrategySize(size, `${context} has member 'size' that`)\n };\n}\n\nfunction convertQueuingStrategySize(fn: QueuingStrategySizeCallback,\n context: string): QueuingStrategySizeCallback {\n assertFunction(fn, context);\n return chunk => convertUnrestrictedDouble(fn(chunk));\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from '../writable-stream/underlying-sink';\nimport { WritableStreamDefaultController } from '../writable-stream';\n\nexport function convertUnderlyingSink(original: UnderlyingSink | null,\n context: string): ValidatedUnderlyingSink {\n assertDictionary(original, context);\n const abort = original?.abort;\n const close = original?.close;\n const start = original?.start;\n const type = original?.type;\n const write = original?.write;\n return {\n abort: abort === undefined ?\n undefined :\n convertUnderlyingSinkAbortCallback(abort, original!, `${context} has member 'abort' that`),\n close: close === undefined ?\n undefined :\n convertUnderlyingSinkCloseCallback(close, original!, `${context} has member 'close' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSinkStartCallback(start, original!, `${context} has member 'start' that`),\n write: write === undefined ?\n undefined :\n convertUnderlyingSinkWriteCallback(write, original!, `${context} has member 'write' that`),\n type\n };\n}\n\nfunction convertUnderlyingSinkAbortCallback(\n fn: UnderlyingSinkAbortCallback,\n original: UnderlyingSink,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSinkCloseCallback(\n fn: UnderlyingSinkCloseCallback,\n original: UnderlyingSink,\n context: string\n): () => Promise {\n assertFunction(fn, context);\n return () => promiseCall(fn, original, []);\n}\n\nfunction convertUnderlyingSinkStartCallback(\n fn: UnderlyingSinkStartCallback,\n original: UnderlyingSink,\n context: string\n): UnderlyingSinkStartCallback {\n assertFunction(fn, context);\n return (controller: WritableStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSinkWriteCallback(\n fn: UnderlyingSinkWriteCallback,\n original: UnderlyingSink,\n context: string\n): (chunk: W, controller: WritableStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: W, controller: WritableStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n","import { IsWritableStream, WritableStream } from '../writable-stream';\n\nexport function assertWritableStream(x: unknown, context: string): asserts x is WritableStream {\n if (!IsWritableStream(x)) {\n throw new TypeError(`${context} is not a WritableStream.`);\n }\n}\n","/**\n * A signal object that allows you to communicate with a request and abort it if required\n * via its associated `AbortController` object.\n *\n * @remarks\n * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @public\n */\nexport interface AbortSignal {\n /**\n * Whether the request is aborted.\n */\n readonly aborted: boolean;\n\n /**\n * If aborted, returns the reason for aborting.\n */\n readonly reason?: any;\n\n /**\n * Add an event listener to be triggered when this signal becomes aborted.\n */\n addEventListener(type: 'abort', listener: () => void): void;\n\n /**\n * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.\n */\n removeEventListener(type: 'abort', listener: () => void): void;\n}\n\nexport function isAbortSignal(value: unknown): value is AbortSignal {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof (value as AbortSignal).aborted === 'boolean';\n } catch {\n // AbortSignal.prototype.aborted throws if its brand check fails\n return false;\n }\n}\n\n/**\n * A controller object that allows you to abort an `AbortSignal` when desired.\n *\n * @remarks\n * This interface is compatible with the `AbortController` interface defined in TypeScript's DOM types.\n * It is redefined here, so it can be polyfilled without a DOM, for example with\n * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.\n *\n * @internal\n */\nexport interface AbortController {\n readonly signal: AbortSignal;\n\n abort(reason?: any): void;\n}\n\ninterface AbortControllerConstructor {\n new(): AbortController;\n}\n\nconst supportsAbortController = typeof (AbortController as any) === 'function';\n\n/**\n * Construct a new AbortController, if supported by the platform.\n *\n * @internal\n */\nexport function createAbortController(): AbortController | undefined {\n if (supportsAbortController) {\n return new (AbortController as AbortControllerConstructor)();\n }\n return undefined;\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponPromise\n} from './helpers/webidl';\nimport {\n DequeueValue,\n EnqueueValueWithSize,\n PeekQueueValue,\n type QueuePair,\n ResetQueue\n} from './abstract-ops/queue-with-sizes';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { SimpleQueue } from './simple-queue';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { AbortSteps, ErrorSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport type {\n UnderlyingSink,\n UnderlyingSinkAbortCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n ValidatedUnderlyingSink\n} from './writable-stream/underlying-sink';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertUnderlyingSink } from './validators/underlying-sink';\nimport { assertWritableStream } from './validators/writable-stream';\nimport { type AbortController, type AbortSignal, createAbortController } from './abort-signal';\n\ntype WritableStreamState = 'writable' | 'closed' | 'erroring' | 'errored';\n\ninterface WriteOrCloseRequest {\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n}\n\ntype WriteRequest = WriteOrCloseRequest;\ntype CloseRequest = WriteOrCloseRequest;\n\ninterface PendingAbortRequest {\n _promise: Promise;\n _resolve: (value?: undefined) => void;\n _reject: (reason: any) => void;\n _reason: any;\n _wasAlreadyErroring: boolean;\n}\n\n/**\n * A writable stream represents a destination for data, into which you can write.\n *\n * @public\n */\nclass WritableStream {\n /** @internal */\n _state!: WritableStreamState;\n /** @internal */\n _storedError: any;\n /** @internal */\n _writer: WritableStreamDefaultWriter | undefined;\n /** @internal */\n _writableStreamController!: WritableStreamDefaultController;\n /** @internal */\n _writeRequests!: SimpleQueue;\n /** @internal */\n _inFlightWriteRequest: WriteRequest | undefined;\n /** @internal */\n _closeRequest: CloseRequest | undefined;\n /** @internal */\n _inFlightCloseRequest: CloseRequest | undefined;\n /** @internal */\n _pendingAbortRequest: PendingAbortRequest | undefined;\n /** @internal */\n _backpressure!: boolean;\n\n constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSink: UnderlyingSink | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSink === undefined) {\n rawUnderlyingSink = null;\n } else {\n assertObject(rawUnderlyingSink, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, 'First parameter');\n\n InitializeWritableStream(this);\n\n const type = underlyingSink.type;\n if (type !== undefined) {\n throw new RangeError('Invalid type is specified');\n }\n\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n\n SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm);\n }\n\n /**\n * Returns whether or not the writable stream is locked to a writer.\n */\n get locked(): boolean {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsWritableStreamLocked(this);\n }\n\n /**\n * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be\n * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort\n * mechanism of the underlying sink.\n *\n * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled\n * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel\n * the stream) if the stream is currently locked.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('abort'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot abort a stream that already has a writer'));\n }\n\n return WritableStreamAbort(this, reason);\n }\n\n /**\n * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its\n * close behavior. During this time any further attempts to write will fail (without erroring the stream).\n *\n * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream\n * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with\n * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.\n */\n close() {\n if (!IsWritableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('close'));\n }\n\n if (IsWritableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot close a stream that already has a writer'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(this)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamClose(this);\n }\n\n /**\n * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream\n * is locked, no other writer can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to write to a stream\n * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at\n * the same time, which would cause the resulting written data to be unpredictable and probably useless.\n */\n getWriter(): WritableStreamDefaultWriter {\n if (!IsWritableStream(this)) {\n throw streamBrandCheckException('getWriter');\n }\n\n return AcquireWritableStreamDefaultWriter(this);\n }\n}\n\nObject.defineProperties(WritableStream.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n getWriter: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(WritableStream.prototype.abort, 'abort');\nsetFunctionName(WritableStream.prototype.close, 'close');\nsetFunctionName(WritableStream.prototype.getWriter, 'getWriter');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStream.prototype, Symbol.toStringTag, {\n value: 'WritableStream',\n configurable: true\n });\n}\n\nexport {\n AcquireWritableStreamDefaultWriter,\n CreateWritableStream,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamDefaultControllerErrorIfNeeded,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite,\n WritableStreamCloseQueuedOrInFlight\n};\n\nexport type {\n UnderlyingSink,\n UnderlyingSinkStartCallback,\n UnderlyingSinkWriteCallback,\n UnderlyingSinkCloseCallback,\n UnderlyingSinkAbortCallback\n};\n\n// Abstract operations for the WritableStream.\n\nfunction AcquireWritableStreamDefaultWriter(stream: WritableStream): WritableStreamDefaultWriter {\n return new WritableStreamDefaultWriter(stream);\n}\n\n// Throws if and only if startAlgorithm throws.\nfunction CreateWritableStream(startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: WritableStream = Object.create(WritableStream.prototype);\n InitializeWritableStream(stream);\n\n const controller: WritableStreamDefaultController = Object.create(WritableStreamDefaultController.prototype);\n\n SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm,\n abortAlgorithm, highWaterMark, sizeAlgorithm);\n return stream;\n}\n\nfunction InitializeWritableStream(stream: WritableStream) {\n stream._state = 'writable';\n\n // The error that will be reported by new method calls once the state becomes errored. Only set when [[state]] is\n // 'erroring' or 'errored'. May be set to an undefined value.\n stream._storedError = undefined;\n\n stream._writer = undefined;\n\n // Initialize to undefined first because the constructor of the controller checks this\n // variable to validate the caller.\n stream._writableStreamController = undefined!;\n\n // This queue is placed here instead of the writer class in order to allow for passing a writer to the next data\n // producer without waiting for the queued writes to finish.\n stream._writeRequests = new SimpleQueue();\n\n // Write requests are removed from _writeRequests when write() is called on the underlying sink. This prevents\n // them from being erroneously rejected on error. If a write() call is in-flight, the request is stored here.\n stream._inFlightWriteRequest = undefined;\n\n // The promise that was returned from writer.close(). Stored here because it may be fulfilled after the writer\n // has been detached.\n stream._closeRequest = undefined;\n\n // Close request is removed from _closeRequest when close() is called on the underlying sink. This prevents it\n // from being erroneously rejected on error. If a close() call is in-flight, the request is stored here.\n stream._inFlightCloseRequest = undefined;\n\n // The promise that was returned from writer.abort(). This may also be fulfilled after the writer has detached.\n stream._pendingAbortRequest = undefined;\n\n // The backpressure signal set by the controller.\n stream._backpressure = false;\n}\n\nfunction IsWritableStream(x: unknown): x is WritableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_writableStreamController')) {\n return false;\n }\n\n return x instanceof WritableStream;\n}\n\nfunction IsWritableStreamLocked(stream: WritableStream): boolean {\n assert(IsWritableStream(stream));\n\n if (stream._writer === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamAbort(stream: WritableStream, reason: any): Promise {\n if (stream._state === 'closed' || stream._state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n stream._writableStreamController._abortReason = reason;\n stream._writableStreamController._abortController?.abort(reason);\n\n // TypeScript narrows the type of `stream._state` down to 'writable' | 'erroring',\n // but it doesn't know that signaling abort runs author code that might have changed the state.\n // Widen the type again by casting to WritableStreamState.\n const state = stream._state as WritableStreamState;\n\n if (state === 'closed' || state === 'errored') {\n return promiseResolvedWith(undefined);\n }\n if (stream._pendingAbortRequest !== undefined) {\n return stream._pendingAbortRequest._promise;\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n let wasAlreadyErroring = false;\n if (state === 'erroring') {\n wasAlreadyErroring = true;\n // reason will not be used, so don't keep a reference to it.\n reason = undefined;\n }\n\n const promise = newPromise((resolve, reject) => {\n stream._pendingAbortRequest = {\n _promise: undefined!,\n _resolve: resolve,\n _reject: reject,\n _reason: reason,\n _wasAlreadyErroring: wasAlreadyErroring\n };\n });\n stream._pendingAbortRequest!._promise = promise;\n\n if (!wasAlreadyErroring) {\n WritableStreamStartErroring(stream, reason);\n }\n\n return promise;\n}\n\nfunction WritableStreamClose(stream: WritableStream): Promise {\n const state = stream._state;\n if (state === 'closed' || state === 'errored') {\n return promiseRejectedWith(new TypeError(\n `The stream (in ${state} state) is not in the writable state and cannot be closed`));\n }\n\n assert(state === 'writable' || state === 'erroring');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const promise = newPromise((resolve, reject) => {\n const closeRequest: CloseRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._closeRequest = closeRequest;\n });\n\n const writer = stream._writer;\n if (writer !== undefined && stream._backpressure && state === 'writable') {\n defaultWriterReadyPromiseResolve(writer);\n }\n\n WritableStreamDefaultControllerClose(stream._writableStreamController);\n\n return promise;\n}\n\n// WritableStream API exposed for controllers.\n\nfunction WritableStreamAddWriteRequest(stream: WritableStream): Promise {\n assert(IsWritableStreamLocked(stream));\n assert(stream._state === 'writable');\n\n const promise = newPromise((resolve, reject) => {\n const writeRequest: WriteRequest = {\n _resolve: resolve,\n _reject: reject\n };\n\n stream._writeRequests.push(writeRequest);\n });\n\n return promise;\n}\n\nfunction WritableStreamDealWithRejection(stream: WritableStream, error: any) {\n const state = stream._state;\n\n if (state === 'writable') {\n WritableStreamStartErroring(stream, error);\n return;\n }\n\n assert(state === 'erroring');\n WritableStreamFinishErroring(stream);\n}\n\nfunction WritableStreamStartErroring(stream: WritableStream, reason: any) {\n assert(stream._storedError === undefined);\n assert(stream._state === 'writable');\n\n const controller = stream._writableStreamController;\n assert(controller !== undefined);\n\n stream._state = 'erroring';\n stream._storedError = reason;\n const writer = stream._writer;\n if (writer !== undefined) {\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason);\n }\n\n if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) {\n WritableStreamFinishErroring(stream);\n }\n}\n\nfunction WritableStreamFinishErroring(stream: WritableStream) {\n assert(stream._state === 'erroring');\n assert(!WritableStreamHasOperationMarkedInFlight(stream));\n stream._state = 'errored';\n stream._writableStreamController[ErrorSteps]();\n\n const storedError = stream._storedError;\n stream._writeRequests.forEach(writeRequest => {\n writeRequest._reject(storedError);\n });\n stream._writeRequests = new SimpleQueue();\n\n if (stream._pendingAbortRequest === undefined) {\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const abortRequest = stream._pendingAbortRequest;\n stream._pendingAbortRequest = undefined;\n\n if (abortRequest._wasAlreadyErroring) {\n abortRequest._reject(storedError);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return;\n }\n\n const promise = stream._writableStreamController[AbortSteps](abortRequest._reason);\n uponPromise(\n promise,\n () => {\n abortRequest._resolve();\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n },\n (reason: any) => {\n abortRequest._reject(reason);\n WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream);\n return null;\n });\n}\n\nfunction WritableStreamFinishInFlightWrite(stream: WritableStream) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._resolve(undefined);\n stream._inFlightWriteRequest = undefined;\n}\n\nfunction WritableStreamFinishInFlightWriteWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightWriteRequest !== undefined);\n stream._inFlightWriteRequest!._reject(error);\n stream._inFlightWriteRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n WritableStreamDealWithRejection(stream, error);\n}\n\nfunction WritableStreamFinishInFlightClose(stream: WritableStream) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._resolve(undefined);\n stream._inFlightCloseRequest = undefined;\n\n const state = stream._state;\n\n assert(state === 'writable' || state === 'erroring');\n\n if (state === 'erroring') {\n // The error was too late to do anything, so it is ignored.\n stream._storedError = undefined;\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._resolve();\n stream._pendingAbortRequest = undefined;\n }\n }\n\n stream._state = 'closed';\n\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseResolve(writer);\n }\n\n assert(stream._pendingAbortRequest === undefined);\n assert(stream._storedError === undefined);\n}\n\nfunction WritableStreamFinishInFlightCloseWithError(stream: WritableStream, error: any) {\n assert(stream._inFlightCloseRequest !== undefined);\n stream._inFlightCloseRequest!._reject(error);\n stream._inFlightCloseRequest = undefined;\n\n assert(stream._state === 'writable' || stream._state === 'erroring');\n\n // Never execute sink abort() after sink close().\n if (stream._pendingAbortRequest !== undefined) {\n stream._pendingAbortRequest._reject(error);\n stream._pendingAbortRequest = undefined;\n }\n WritableStreamDealWithRejection(stream, error);\n}\n\n// TODO(ricea): Fix alphabetical order.\nfunction WritableStreamCloseQueuedOrInFlight(stream: WritableStream): boolean {\n if (stream._closeRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamHasOperationMarkedInFlight(stream: WritableStream): boolean {\n if (stream._inFlightWriteRequest === undefined && stream._inFlightCloseRequest === undefined) {\n return false;\n }\n\n return true;\n}\n\nfunction WritableStreamMarkCloseRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightCloseRequest === undefined);\n assert(stream._closeRequest !== undefined);\n stream._inFlightCloseRequest = stream._closeRequest;\n stream._closeRequest = undefined;\n}\n\nfunction WritableStreamMarkFirstWriteRequestInFlight(stream: WritableStream) {\n assert(stream._inFlightWriteRequest === undefined);\n assert(stream._writeRequests.length !== 0);\n stream._inFlightWriteRequest = stream._writeRequests.shift();\n}\n\nfunction WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream: WritableStream) {\n assert(stream._state === 'errored');\n if (stream._closeRequest !== undefined) {\n assert(stream._inFlightCloseRequest === undefined);\n\n stream._closeRequest._reject(stream._storedError);\n stream._closeRequest = undefined;\n }\n const writer = stream._writer;\n if (writer !== undefined) {\n defaultWriterClosedPromiseReject(writer, stream._storedError);\n }\n}\n\nfunction WritableStreamUpdateBackpressure(stream: WritableStream, backpressure: boolean) {\n assert(stream._state === 'writable');\n assert(!WritableStreamCloseQueuedOrInFlight(stream));\n\n const writer = stream._writer;\n if (writer !== undefined && backpressure !== stream._backpressure) {\n if (backpressure) {\n defaultWriterReadyPromiseReset(writer);\n } else {\n assert(!backpressure);\n\n defaultWriterReadyPromiseResolve(writer);\n }\n }\n\n stream._backpressure = backpressure;\n}\n\n/**\n * A default writer vended by a {@link WritableStream}.\n *\n * @public\n */\nexport class WritableStreamDefaultWriter {\n /** @internal */\n _ownerWritableStream: WritableStream;\n /** @internal */\n _closedPromise!: Promise;\n /** @internal */\n _closedPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _closedPromise_reject?: (reason: any) => void;\n /** @internal */\n _closedPromiseState!: 'pending' | 'resolved' | 'rejected';\n /** @internal */\n _readyPromise!: Promise;\n /** @internal */\n _readyPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _readyPromise_reject?: (reason: any) => void;\n /** @internal */\n _readyPromiseState!: 'pending' | 'fulfilled' | 'rejected';\n\n constructor(stream: WritableStream) {\n assertRequiredArgument(stream, 1, 'WritableStreamDefaultWriter');\n assertWritableStream(stream, 'First parameter');\n\n if (IsWritableStreamLocked(stream)) {\n throw new TypeError('This stream has already been locked for exclusive writing by another writer');\n }\n\n this._ownerWritableStream = stream;\n stream._writer = this;\n\n const state = stream._state;\n\n if (state === 'writable') {\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) {\n defaultWriterReadyPromiseInitialize(this);\n } else {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n }\n\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'erroring') {\n defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError);\n defaultWriterClosedPromiseInitialize(this);\n } else if (state === 'closed') {\n defaultWriterReadyPromiseInitializeAsResolved(this);\n defaultWriterClosedPromiseInitializeAsResolved(this);\n } else {\n assert(state === 'errored');\n\n const storedError = stream._storedError;\n defaultWriterReadyPromiseInitializeAsRejected(this, storedError);\n defaultWriterClosedPromiseInitializeAsRejected(this, storedError);\n }\n }\n\n /**\n * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or\n * the writer’s lock is released before the stream finishes closing.\n */\n get closed(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('closed'));\n }\n\n return this._closedPromise;\n }\n\n /**\n * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full.\n * A producer can use this information to determine the right amount of data to write.\n *\n * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort\n * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when\n * the writer’s lock is released.\n */\n get desiredSize(): number | null {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('desiredSize');\n }\n\n if (this._ownerWritableStream === undefined) {\n throw defaultWriterLockException('desiredSize');\n }\n\n return WritableStreamDefaultWriterGetDesiredSize(this);\n }\n\n /**\n * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions\n * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips\n * back to zero or below, the getter will return a new promise that stays pending until the next transition.\n *\n * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become\n * rejected.\n */\n get ready(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('ready'));\n }\n\n return this._readyPromise;\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.\n */\n abort(reason: any = undefined): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('abort'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('abort'));\n }\n\n return WritableStreamDefaultWriterAbort(this, reason);\n }\n\n /**\n * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.\n */\n close(): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('close'));\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('close'));\n }\n\n if (WritableStreamCloseQueuedOrInFlight(stream)) {\n return promiseRejectedWith(new TypeError('Cannot close an already-closing stream'));\n }\n\n return WritableStreamDefaultWriterClose(this);\n }\n\n /**\n * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active.\n * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from\n * now on; otherwise, the writer will appear closed.\n *\n * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the\n * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).\n * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents\n * other producers from writing in an interleaved manner.\n */\n releaseLock(): void {\n if (!IsWritableStreamDefaultWriter(this)) {\n throw defaultWriterBrandCheckException('releaseLock');\n }\n\n const stream = this._ownerWritableStream;\n\n if (stream === undefined) {\n return;\n }\n\n assert(stream._writer !== undefined);\n\n WritableStreamDefaultWriterRelease(this);\n }\n\n /**\n * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,\n * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return\n * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes\n * errored before the writing process is initiated.\n *\n * Note that what \"success\" means is up to the underlying sink; it might indicate simply that the chunk has been\n * accepted, and not necessarily that it is safely saved to its ultimate destination.\n */\n write(chunk: W): Promise;\n write(chunk: W = undefined!): Promise {\n if (!IsWritableStreamDefaultWriter(this)) {\n return promiseRejectedWith(defaultWriterBrandCheckException('write'));\n }\n\n if (this._ownerWritableStream === undefined) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n return WritableStreamDefaultWriterWrite(this, chunk);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultWriter.prototype, {\n abort: { enumerable: true },\n close: { enumerable: true },\n releaseLock: { enumerable: true },\n write: { enumerable: true },\n closed: { enumerable: true },\n desiredSize: { enumerable: true },\n ready: { enumerable: true }\n});\nsetFunctionName(WritableStreamDefaultWriter.prototype.abort, 'abort');\nsetFunctionName(WritableStreamDefaultWriter.prototype.close, 'close');\nsetFunctionName(WritableStreamDefaultWriter.prototype.releaseLock, 'releaseLock');\nsetFunctionName(WritableStreamDefaultWriter.prototype.write, 'write');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultWriter.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultWriter',\n configurable: true\n });\n}\n\n// Abstract operations for the WritableStreamDefaultWriter.\n\nfunction IsWritableStreamDefaultWriter(x: any): x is WritableStreamDefaultWriter {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_ownerWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultWriter;\n}\n\n// A client of WritableStreamDefaultWriter may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultWriterAbort(writer: WritableStreamDefaultWriter, reason: any) {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamAbort(stream, reason);\n}\n\nfunction WritableStreamDefaultWriterClose(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n return WritableStreamClose(stream);\n}\n\nfunction WritableStreamDefaultWriterCloseWithErrorPropagation(writer: WritableStreamDefaultWriter): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const state = stream._state;\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable' || state === 'erroring');\n\n return WritableStreamDefaultWriterClose(writer);\n}\n\nfunction WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._closedPromiseState === 'pending') {\n defaultWriterClosedPromiseReject(writer, error);\n } else {\n defaultWriterClosedPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer: WritableStreamDefaultWriter, error: any) {\n if (writer._readyPromiseState === 'pending') {\n defaultWriterReadyPromiseReject(writer, error);\n } else {\n defaultWriterReadyPromiseResetToRejected(writer, error);\n }\n}\n\nfunction WritableStreamDefaultWriterGetDesiredSize(writer: WritableStreamDefaultWriter): number | null {\n const stream = writer._ownerWritableStream;\n const state = stream._state;\n\n if (state === 'errored' || state === 'erroring') {\n return null;\n }\n\n if (state === 'closed') {\n return 0;\n }\n\n return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController);\n}\n\nfunction WritableStreamDefaultWriterRelease(writer: WritableStreamDefaultWriter) {\n const stream = writer._ownerWritableStream;\n assert(stream !== undefined);\n assert(stream._writer === writer);\n\n const releasedError = new TypeError(\n `Writer was released and can no longer be used to monitor the stream's closedness`);\n\n WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError);\n\n // The state transitions to \"errored\" before the sink abort() method runs, but the writer.closed promise is not\n // rejected until afterwards. This means that simply testing state will not work.\n WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError);\n\n stream._writer = undefined;\n writer._ownerWritableStream = undefined!;\n}\n\nfunction WritableStreamDefaultWriterWrite(writer: WritableStreamDefaultWriter, chunk: W): Promise {\n const stream = writer._ownerWritableStream;\n\n assert(stream !== undefined);\n\n const controller = stream._writableStreamController;\n\n const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk);\n\n if (stream !== writer._ownerWritableStream) {\n return promiseRejectedWith(defaultWriterLockException('write to'));\n }\n\n const state = stream._state;\n if (state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n if (WritableStreamCloseQueuedOrInFlight(stream) || state === 'closed') {\n return promiseRejectedWith(new TypeError('The stream is closing or closed and cannot be written to'));\n }\n if (state === 'erroring') {\n return promiseRejectedWith(stream._storedError);\n }\n\n assert(state === 'writable');\n\n const promise = WritableStreamAddWriteRequest(stream);\n\n WritableStreamDefaultControllerWrite(controller, chunk, chunkSize);\n\n return promise;\n}\n\nconst closeSentinel: unique symbol = {} as any;\n\ntype QueueRecord = W | typeof closeSentinel;\n\n/**\n * Allows control of a {@link WritableStream | writable stream}'s state and internal queue.\n *\n * @public\n */\nexport class WritableStreamDefaultController {\n /** @internal */\n _controlledWritableStream!: WritableStream;\n /** @internal */\n _queue!: SimpleQueue>>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _abortReason: any;\n /** @internal */\n _abortController: AbortController | undefined;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _writeAlgorithm!: (chunk: W) => Promise;\n /** @internal */\n _closeAlgorithm!: () => Promise;\n /** @internal */\n _abortAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.\n *\n * @deprecated\n * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.\n * Use {@link WritableStreamDefaultController.signal}'s `reason` instead.\n */\n get abortReason(): any {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('abortReason');\n }\n return this._abortReason;\n }\n\n /**\n * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.\n */\n get signal(): AbortSignal {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('signal');\n }\n if (this._abortController === undefined) {\n // Older browsers or older Node versions may not support `AbortController` or `AbortSignal`.\n // We don't want to bundle and ship an `AbortController` polyfill together with our polyfill,\n // so instead we only implement support for `signal` if we find a global `AbortController` constructor.\n throw new TypeError('WritableStreamDefaultController.prototype.signal is not supported');\n }\n return this._abortController.signal;\n }\n\n /**\n * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.\n *\n * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying\n * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the\n * normal lifecycle of interactions with the underlying sink.\n */\n error(e: any = undefined): void {\n if (!IsWritableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n const state = this._controlledWritableStream._state;\n if (state !== 'writable') {\n // The stream is closed, errored or will be soon. The sink can't do anything useful if it gets an error here, so\n // just treat it as a no-op.\n return;\n }\n\n WritableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [AbortSteps](reason: any): Promise {\n const result = this._abortAlgorithm(reason);\n WritableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [ErrorSteps]() {\n ResetQueue(this);\n }\n}\n\nObject.defineProperties(WritableStreamDefaultController.prototype, {\n abortReason: { enumerable: true },\n signal: { enumerable: true },\n error: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(WritableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'WritableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations implementing interface required by the WritableStream.\n\nfunction IsWritableStreamDefaultController(x: any): x is WritableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledWritableStream')) {\n return false;\n }\n\n return x instanceof WritableStreamDefaultController;\n}\n\nfunction SetUpWritableStreamDefaultController(stream: WritableStream,\n controller: WritableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n writeAlgorithm: (chunk: W) => Promise,\n closeAlgorithm: () => Promise,\n abortAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(IsWritableStream(stream));\n assert(stream._writableStreamController === undefined);\n\n controller._controlledWritableStream = stream;\n stream._writableStreamController = controller;\n\n // Need to set the slots so that the assert doesn't fire. In the spec the slots already exist implicitly.\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._abortReason = undefined;\n controller._abortController = createAbortController();\n controller._started = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._writeAlgorithm = writeAlgorithm;\n controller._closeAlgorithm = closeAlgorithm;\n controller._abortAlgorithm = abortAlgorithm;\n\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n\n const startResult = startAlgorithm();\n const startPromise = promiseResolvedWith(startResult);\n uponPromise(\n startPromise,\n () => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n r => {\n assert(stream._state === 'writable' || stream._state === 'erroring');\n controller._started = true;\n WritableStreamDealWithRejection(stream, r);\n return null;\n }\n );\n}\n\nfunction SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream: WritableStream,\n underlyingSink: ValidatedUnderlyingSink,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n const controller = Object.create(WritableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let writeAlgorithm: (chunk: W) => Promise;\n let closeAlgorithm: () => Promise;\n let abortAlgorithm: (reason: any) => Promise;\n\n if (underlyingSink.start !== undefined) {\n startAlgorithm = () => underlyingSink.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSink.write !== undefined) {\n writeAlgorithm = chunk => underlyingSink.write!(chunk, controller);\n } else {\n writeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.close !== undefined) {\n closeAlgorithm = () => underlyingSink.close!();\n } else {\n closeAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSink.abort !== undefined) {\n abortAlgorithm = reason => underlyingSink.abort!(reason);\n } else {\n abortAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpWritableStreamDefaultController(\n stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// ClearAlgorithms may be called twice. Erroring the same stream in multiple ways will often result in redundant calls.\nfunction WritableStreamDefaultControllerClearAlgorithms(controller: WritableStreamDefaultController) {\n controller._writeAlgorithm = undefined!;\n controller._closeAlgorithm = undefined!;\n controller._abortAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\nfunction WritableStreamDefaultControllerClose(controller: WritableStreamDefaultController) {\n EnqueueValueWithSize(controller, closeSentinel, 0);\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\nfunction WritableStreamDefaultControllerGetChunkSize(controller: WritableStreamDefaultController,\n chunk: W): number {\n try {\n return controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE);\n return 1;\n }\n}\n\nfunction WritableStreamDefaultControllerGetDesiredSize(controller: WritableStreamDefaultController): number {\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\nfunction WritableStreamDefaultControllerWrite(controller: WritableStreamDefaultController,\n chunk: W,\n chunkSize: number) {\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE);\n return;\n }\n\n const stream = controller._controlledWritableStream;\n if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n}\n\n// Abstract operations for the WritableStreamDefaultController.\n\nfunction WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n if (!controller._started) {\n return;\n }\n\n if (stream._inFlightWriteRequest !== undefined) {\n return;\n }\n\n const state = stream._state;\n assert(state !== 'closed' && state !== 'errored');\n if (state === 'erroring') {\n WritableStreamFinishErroring(stream);\n return;\n }\n\n if (controller._queue.length === 0) {\n return;\n }\n\n const value = PeekQueueValue(controller);\n if (value === closeSentinel) {\n WritableStreamDefaultControllerProcessClose(controller);\n } else {\n WritableStreamDefaultControllerProcessWrite(controller, value);\n }\n}\n\nfunction WritableStreamDefaultControllerErrorIfNeeded(controller: WritableStreamDefaultController, error: any) {\n if (controller._controlledWritableStream._state === 'writable') {\n WritableStreamDefaultControllerError(controller, error);\n }\n}\n\nfunction WritableStreamDefaultControllerProcessClose(controller: WritableStreamDefaultController) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkCloseRequestInFlight(stream);\n\n DequeueValue(controller);\n assert(controller._queue.length === 0);\n\n const sinkClosePromise = controller._closeAlgorithm();\n WritableStreamDefaultControllerClearAlgorithms(controller);\n uponPromise(\n sinkClosePromise,\n () => {\n WritableStreamFinishInFlightClose(stream);\n return null;\n },\n reason => {\n WritableStreamFinishInFlightCloseWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerProcessWrite(controller: WritableStreamDefaultController, chunk: W) {\n const stream = controller._controlledWritableStream;\n\n WritableStreamMarkFirstWriteRequestInFlight(stream);\n\n const sinkWritePromise = controller._writeAlgorithm(chunk);\n uponPromise(\n sinkWritePromise,\n () => {\n WritableStreamFinishInFlightWrite(stream);\n\n const state = stream._state;\n assert(state === 'writable' || state === 'erroring');\n\n DequeueValue(controller);\n\n if (!WritableStreamCloseQueuedOrInFlight(stream) && state === 'writable') {\n const backpressure = WritableStreamDefaultControllerGetBackpressure(controller);\n WritableStreamUpdateBackpressure(stream, backpressure);\n }\n\n WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller);\n return null;\n },\n reason => {\n if (stream._state === 'writable') {\n WritableStreamDefaultControllerClearAlgorithms(controller);\n }\n WritableStreamFinishInFlightWriteWithError(stream, reason);\n return null;\n }\n );\n}\n\nfunction WritableStreamDefaultControllerGetBackpressure(controller: WritableStreamDefaultController): boolean {\n const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller);\n return desiredSize <= 0;\n}\n\n// A client of WritableStreamDefaultController may use these functions directly to bypass state check.\n\nfunction WritableStreamDefaultControllerError(controller: WritableStreamDefaultController, error: any) {\n const stream = controller._controlledWritableStream;\n\n assert(stream._state === 'writable');\n\n WritableStreamDefaultControllerClearAlgorithms(controller);\n WritableStreamStartErroring(stream, error);\n}\n\n// Helper functions for the WritableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`);\n}\n\n// Helper functions for the WritableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`);\n}\n\n\n// Helper functions for the WritableStreamDefaultWriter.\n\nfunction defaultWriterBrandCheckException(name: string): TypeError {\n return new TypeError(\n `WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`);\n}\n\nfunction defaultWriterLockException(name: string): TypeError {\n return new TypeError('Cannot ' + name + ' a stream using a released writer');\n}\n\nfunction defaultWriterClosedPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._closedPromise = newPromise((resolve, reject) => {\n writer._closedPromise_resolve = resolve;\n writer._closedPromise_reject = reject;\n writer._closedPromiseState = 'pending';\n });\n}\n\nfunction defaultWriterClosedPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseReject(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterClosedPromiseInitialize(writer);\n defaultWriterClosedPromiseResolve(writer);\n}\n\nfunction defaultWriterClosedPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._closedPromise_reject === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n setPromiseIsHandledToTrue(writer._closedPromise);\n writer._closedPromise_reject(reason);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'rejected';\n}\n\nfunction defaultWriterClosedPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._closedPromise_resolve === undefined);\n assert(writer._closedPromise_reject === undefined);\n assert(writer._closedPromiseState !== 'pending');\n\n defaultWriterClosedPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterClosedPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._closedPromise_resolve === undefined) {\n return;\n }\n assert(writer._closedPromiseState === 'pending');\n\n writer._closedPromise_resolve(undefined);\n writer._closedPromise_resolve = undefined;\n writer._closedPromise_reject = undefined;\n writer._closedPromiseState = 'resolved';\n}\n\nfunction defaultWriterReadyPromiseInitialize(writer: WritableStreamDefaultWriter) {\n writer._readyPromise = newPromise((resolve, reject) => {\n writer._readyPromise_resolve = resolve;\n writer._readyPromise_reject = reject;\n });\n writer._readyPromiseState = 'pending';\n}\n\nfunction defaultWriterReadyPromiseInitializeAsRejected(writer: WritableStreamDefaultWriter, reason: any) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseReject(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseInitializeAsResolved(writer: WritableStreamDefaultWriter) {\n defaultWriterReadyPromiseInitialize(writer);\n defaultWriterReadyPromiseResolve(writer);\n}\n\nfunction defaultWriterReadyPromiseReject(writer: WritableStreamDefaultWriter, reason: any) {\n if (writer._readyPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(writer._readyPromise);\n writer._readyPromise_reject(reason);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'rejected';\n}\n\nfunction defaultWriterReadyPromiseReset(writer: WritableStreamDefaultWriter) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitialize(writer);\n}\n\nfunction defaultWriterReadyPromiseResetToRejected(writer: WritableStreamDefaultWriter, reason: any) {\n assert(writer._readyPromise_resolve === undefined);\n assert(writer._readyPromise_reject === undefined);\n\n defaultWriterReadyPromiseInitializeAsRejected(writer, reason);\n}\n\nfunction defaultWriterReadyPromiseResolve(writer: WritableStreamDefaultWriter) {\n if (writer._readyPromise_resolve === undefined) {\n return;\n }\n\n writer._readyPromise_resolve(undefined);\n writer._readyPromise_resolve = undefined;\n writer._readyPromise_reject = undefined;\n writer._readyPromiseState = 'fulfilled';\n}\n","/// \n\nfunction getGlobals(): typeof globalThis | undefined {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n } else if (typeof self !== 'undefined') {\n return self;\n } else if (typeof global !== 'undefined') {\n return global;\n }\n return undefined;\n}\n\nexport const globals = getGlobals();\n","/// \nimport { globals } from '../globals';\nimport { setFunctionName } from '../lib/helpers/miscellaneous';\n\ninterface DOMException extends Error {\n name: string;\n message: string;\n}\n\ntype DOMExceptionConstructor = new (message?: string, name?: string) => DOMException;\n\nfunction isDOMExceptionConstructor(ctor: unknown): ctor is DOMExceptionConstructor {\n if (!(typeof ctor === 'function' || typeof ctor === 'object')) {\n return false;\n }\n if ((ctor as DOMExceptionConstructor).name !== 'DOMException') {\n return false;\n }\n try {\n new (ctor as DOMExceptionConstructor)();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Support:\n * - Web browsers\n * - Node 18 and higher (https://github.com/nodejs/node/commit/e4b1fb5e6422c1ff151234bb9de792d45dd88d87)\n */\nfunction getFromGlobal(): DOMExceptionConstructor | undefined {\n const ctor = globals?.DOMException;\n return isDOMExceptionConstructor(ctor) ? ctor : undefined;\n}\n\n/**\n * Support:\n * - All platforms\n */\nfunction createPolyfill(): DOMExceptionConstructor {\n // eslint-disable-next-line @typescript-eslint/no-shadow\n const ctor = function DOMException(this: DOMException, message?: string, name?: string) {\n this.message = message || '';\n this.name = name || 'Error';\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n } as any;\n setFunctionName(ctor, 'DOMException');\n ctor.prototype = Object.create(Error.prototype);\n Object.defineProperty(ctor.prototype, 'constructor', { value: ctor, writable: true, configurable: true });\n return ctor;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-redeclare\nconst DOMException: DOMExceptionConstructor = getFromGlobal() || createPolyfill();\n\nexport { DOMException };\n","import { IsReadableStream, IsReadableStreamLocked, ReadableStream, ReadableStreamCancel } from '../readable-stream';\nimport { AcquireReadableStreamDefaultReader, ReadableStreamDefaultReaderRead } from './default-reader';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireWritableStreamDefaultWriter,\n IsWritableStream,\n IsWritableStreamLocked,\n WritableStream,\n WritableStreamAbort,\n WritableStreamCloseQueuedOrInFlight,\n WritableStreamDefaultWriterCloseWithErrorPropagation,\n WritableStreamDefaultWriterRelease,\n WritableStreamDefaultWriterWrite\n} from '../writable-stream';\nimport assert from '../../stub/assert';\nimport {\n newPromise,\n PerformPromiseThen,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n uponFulfillment,\n uponPromise,\n uponRejection\n} from '../helpers/webidl';\nimport { noop } from '../../utils';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\nimport { DOMException } from '../../stub/dom-exception';\n\nexport function ReadableStreamPipeTo(source: ReadableStream,\n dest: WritableStream,\n preventClose: boolean,\n preventAbort: boolean,\n preventCancel: boolean,\n signal: AbortSignal | undefined): Promise {\n assert(IsReadableStream(source));\n assert(IsWritableStream(dest));\n assert(typeof preventClose === 'boolean');\n assert(typeof preventAbort === 'boolean');\n assert(typeof preventCancel === 'boolean');\n assert(signal === undefined || isAbortSignal(signal));\n assert(!IsReadableStreamLocked(source));\n assert(!IsWritableStreamLocked(dest));\n\n const reader = AcquireReadableStreamDefaultReader(source);\n const writer = AcquireWritableStreamDefaultWriter(dest);\n\n source._disturbed = true;\n\n let shuttingDown = false;\n\n // This is used to keep track of the spec's requirement that we wait for ongoing writes during shutdown.\n let currentWrite = promiseResolvedWith(undefined);\n\n return newPromise((resolve, reject) => {\n let abortAlgorithm: () => void;\n if (signal !== undefined) {\n abortAlgorithm = () => {\n const error = signal.reason !== undefined ? signal.reason : new DOMException('Aborted', 'AbortError');\n const actions: Array<() => Promise> = [];\n if (!preventAbort) {\n actions.push(() => {\n if (dest._state === 'writable') {\n return WritableStreamAbort(dest, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n if (!preventCancel) {\n actions.push(() => {\n if (source._state === 'readable') {\n return ReadableStreamCancel(source, error);\n }\n return promiseResolvedWith(undefined);\n });\n }\n shutdownWithAction(() => Promise.all(actions.map(action => action())), true, error);\n };\n\n if (signal.aborted) {\n abortAlgorithm();\n return;\n }\n\n signal.addEventListener('abort', abortAlgorithm);\n }\n\n // Using reader and writer, read all chunks from this and write them to dest\n // - Backpressure must be enforced\n // - Shutdown must stop all activity\n function pipeLoop() {\n return newPromise((resolveLoop, rejectLoop) => {\n function next(done: boolean) {\n if (done) {\n resolveLoop();\n } else {\n // Use `PerformPromiseThen` instead of `uponPromise` to avoid\n // adding unnecessary `.catch(rethrowAssertionErrorRejection)` handlers\n PerformPromiseThen(pipeStep(), next, rejectLoop);\n }\n }\n\n next(false);\n });\n }\n\n function pipeStep(): Promise {\n if (shuttingDown) {\n return promiseResolvedWith(true);\n }\n\n return PerformPromiseThen(writer._readyPromise, () => {\n return newPromise((resolveRead, rejectRead) => {\n ReadableStreamDefaultReaderRead(\n reader,\n {\n _chunkSteps: chunk => {\n currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), undefined, noop);\n resolveRead(false);\n },\n _closeSteps: () => resolveRead(true),\n _errorSteps: rejectRead\n }\n );\n });\n });\n }\n\n // Errors must be propagated forward\n isOrBecomesErrored(source, reader._closedPromise, storedError => {\n if (!preventAbort) {\n shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Errors must be propagated backward\n isOrBecomesErrored(dest, writer._closedPromise, storedError => {\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError);\n } else {\n shutdown(true, storedError);\n }\n return null;\n });\n\n // Closing must be propagated forward\n isOrBecomesClosed(source, reader._closedPromise, () => {\n if (!preventClose) {\n shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer));\n } else {\n shutdown();\n }\n return null;\n });\n\n // Closing must be propagated backward\n if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === 'closed') {\n const destClosed = new TypeError('the destination writable stream closed before all data could be piped to it');\n\n if (!preventCancel) {\n shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed);\n } else {\n shutdown(true, destClosed);\n }\n }\n\n setPromiseIsHandledToTrue(pipeLoop());\n\n function waitForWritesToFinish(): Promise {\n // Another write may have started while we were waiting on this currentWrite, so we have to be sure to wait\n // for that too.\n const oldCurrentWrite = currentWrite;\n return PerformPromiseThen(\n currentWrite,\n () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : undefined\n );\n }\n\n function isOrBecomesErrored(stream: ReadableStream | WritableStream,\n promise: Promise,\n action: (reason: any) => null) {\n if (stream._state === 'errored') {\n action(stream._storedError);\n } else {\n uponRejection(promise, action);\n }\n }\n\n function isOrBecomesClosed(stream: ReadableStream | WritableStream, promise: Promise, action: () => null) {\n if (stream._state === 'closed') {\n action();\n } else {\n uponFulfillment(promise, action);\n }\n }\n\n function shutdownWithAction(action: () => Promise, originalIsError?: boolean, originalError?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), doTheRest);\n } else {\n doTheRest();\n }\n\n function doTheRest(): null {\n uponPromise(\n action(),\n () => finalize(originalIsError, originalError),\n newError => finalize(true, newError)\n );\n return null;\n }\n }\n\n function shutdown(isError?: boolean, error?: any) {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n\n if (dest._state === 'writable' && !WritableStreamCloseQueuedOrInFlight(dest)) {\n uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error));\n } else {\n finalize(isError, error);\n }\n }\n\n function finalize(isError?: boolean, error?: any): null {\n WritableStreamDefaultWriterRelease(writer);\n ReadableStreamReaderGenericRelease(reader);\n\n if (signal !== undefined) {\n signal.removeEventListener('abort', abortAlgorithm);\n }\n if (isError) {\n reject(error);\n } else {\n resolve(undefined);\n }\n\n return null;\n }\n });\n}\n","import type { QueuingStrategySizeCallback } from '../queuing-strategy';\nimport assert from '../../stub/assert';\nimport { DequeueValue, EnqueueValueWithSize, type QueuePair, ResetQueue } from '../abstract-ops/queue-with-sizes';\nimport {\n ReadableStreamAddReadRequest,\n ReadableStreamFulfillReadRequest,\n ReadableStreamGetNumReadRequests,\n type ReadRequest\n} from './default-reader';\nimport { SimpleQueue } from '../simple-queue';\nimport { IsReadableStreamLocked, ReadableStream, ReadableStreamClose, ReadableStreamError } from '../readable-stream';\nimport type { ValidatedUnderlyingSource } from './underlying-source';\nimport { setFunctionName, typeIsObject } from '../helpers/miscellaneous';\nimport { CancelSteps, PullSteps, ReleaseSteps } from '../abstract-ops/internal-methods';\nimport { promiseResolvedWith, uponPromise } from '../helpers/webidl';\n\n/**\n * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.\n *\n * @public\n */\nexport class ReadableStreamDefaultController {\n /** @internal */\n _controlledReadableStream!: ReadableStream;\n /** @internal */\n _queue!: SimpleQueue>;\n /** @internal */\n _queueTotalSize!: number;\n /** @internal */\n _started!: boolean;\n /** @internal */\n _closeRequested!: boolean;\n /** @internal */\n _pullAgain!: boolean;\n /** @internal */\n _pulling !: boolean;\n /** @internal */\n _strategySizeAlgorithm!: QueuingStrategySizeCallback;\n /** @internal */\n _strategyHWM!: number;\n /** @internal */\n _pullAlgorithm!: () => Promise;\n /** @internal */\n _cancelAlgorithm!: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is\n * over-full. An underlying source ought to use this information to determine when and how to apply backpressure.\n */\n get desiredSize(): number | null {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n return ReadableStreamDefaultControllerGetDesiredSize(this);\n }\n\n /**\n * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from\n * the stream, but once those are read, the stream will become closed.\n */\n close(): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('close');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits close');\n }\n\n ReadableStreamDefaultControllerClose(this);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the controlled readable stream.\n */\n enqueue(chunk: R): void;\n enqueue(chunk: R = undefined!): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) {\n throw new TypeError('The stream is not in a state that permits enqueue');\n }\n\n return ReadableStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.\n */\n error(e: any = undefined): void {\n if (!IsReadableStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n ReadableStreamDefaultControllerError(this, e);\n }\n\n /** @internal */\n [CancelSteps](reason: any): Promise {\n ResetQueue(this);\n const result = this._cancelAlgorithm(reason);\n ReadableStreamDefaultControllerClearAlgorithms(this);\n return result;\n }\n\n /** @internal */\n [PullSteps](readRequest: ReadRequest): void {\n const stream = this._controlledReadableStream;\n\n if (this._queue.length > 0) {\n const chunk = DequeueValue(this);\n\n if (this._closeRequested && this._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(this);\n ReadableStreamClose(stream);\n } else {\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n\n readRequest._chunkSteps(chunk);\n } else {\n ReadableStreamAddReadRequest(stream, readRequest);\n ReadableStreamDefaultControllerCallPullIfNeeded(this);\n }\n }\n\n /** @internal */\n [ReleaseSteps](): void {\n // Do nothing.\n }\n}\n\nObject.defineProperties(ReadableStreamDefaultController.prototype, {\n close: { enumerable: true },\n enqueue: { enumerable: true },\n error: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(ReadableStreamDefaultController.prototype.close, 'close');\nsetFunctionName(ReadableStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(ReadableStreamDefaultController.prototype.error, 'error');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'ReadableStreamDefaultController',\n configurable: true\n });\n}\n\n// Abstract operations for the ReadableStreamDefaultController.\n\nfunction IsReadableStreamDefaultController(x: any): x is ReadableStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledReadableStream')) {\n return false;\n }\n\n return x instanceof ReadableStreamDefaultController;\n}\n\nfunction ReadableStreamDefaultControllerCallPullIfNeeded(controller: ReadableStreamDefaultController): void {\n const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller);\n if (!shouldPull) {\n return;\n }\n\n if (controller._pulling) {\n controller._pullAgain = true;\n return;\n }\n\n assert(!controller._pullAgain);\n\n controller._pulling = true;\n\n const pullPromise = controller._pullAlgorithm();\n uponPromise(\n pullPromise,\n () => {\n controller._pulling = false;\n\n if (controller._pullAgain) {\n controller._pullAgain = false;\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n }\n\n return null;\n },\n e => {\n ReadableStreamDefaultControllerError(controller, e);\n return null;\n }\n );\n}\n\nfunction ReadableStreamDefaultControllerShouldCallPull(controller: ReadableStreamDefaultController): boolean {\n const stream = controller._controlledReadableStream;\n\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return false;\n }\n\n if (!controller._started) {\n return false;\n }\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n return true;\n }\n\n const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller);\n assert(desiredSize !== null);\n if (desiredSize! > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction ReadableStreamDefaultControllerClearAlgorithms(controller: ReadableStreamDefaultController) {\n controller._pullAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n controller._strategySizeAlgorithm = undefined!;\n}\n\n// A client of ReadableStreamDefaultController may use these functions directly to bypass state check.\n\nexport function ReadableStreamDefaultControllerClose(controller: ReadableStreamDefaultController) {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n controller._closeRequested = true;\n\n if (controller._queue.length === 0) {\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamClose(stream);\n }\n}\n\nexport function ReadableStreamDefaultControllerEnqueue(\n controller: ReadableStreamDefaultController,\n chunk: R\n): void {\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) {\n return;\n }\n\n const stream = controller._controlledReadableStream;\n\n if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) {\n ReadableStreamFulfillReadRequest(stream, chunk, false);\n } else {\n let chunkSize;\n try {\n chunkSize = controller._strategySizeAlgorithm(chunk);\n } catch (chunkSizeE) {\n ReadableStreamDefaultControllerError(controller, chunkSizeE);\n throw chunkSizeE;\n }\n\n try {\n EnqueueValueWithSize(controller, chunk, chunkSize);\n } catch (enqueueE) {\n ReadableStreamDefaultControllerError(controller, enqueueE);\n throw enqueueE;\n }\n }\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n}\n\nexport function ReadableStreamDefaultControllerError(controller: ReadableStreamDefaultController, e: any) {\n const stream = controller._controlledReadableStream;\n\n if (stream._state !== 'readable') {\n return;\n }\n\n ResetQueue(controller);\n\n ReadableStreamDefaultControllerClearAlgorithms(controller);\n ReadableStreamError(stream, e);\n}\n\nexport function ReadableStreamDefaultControllerGetDesiredSize(\n controller: ReadableStreamDefaultController\n): number | null {\n const state = controller._controlledReadableStream._state;\n\n if (state === 'errored') {\n return null;\n }\n if (state === 'closed') {\n return 0;\n }\n\n return controller._strategyHWM - controller._queueTotalSize;\n}\n\n// This is used in the implementation of TransformStream.\nexport function ReadableStreamDefaultControllerHasBackpressure(\n controller: ReadableStreamDefaultController\n): boolean {\n if (ReadableStreamDefaultControllerShouldCallPull(controller)) {\n return false;\n }\n\n return true;\n}\n\nexport function ReadableStreamDefaultControllerCanCloseOrEnqueue(\n controller: ReadableStreamDefaultController\n): boolean {\n const state = controller._controlledReadableStream._state;\n\n if (!controller._closeRequested && state === 'readable') {\n return true;\n }\n\n return false;\n}\n\nexport function SetUpReadableStreamDefaultController(stream: ReadableStream,\n controller: ReadableStreamDefaultController,\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback) {\n assert(stream._readableStreamController === undefined);\n\n controller._controlledReadableStream = stream;\n\n controller._queue = undefined!;\n controller._queueTotalSize = undefined!;\n ResetQueue(controller);\n\n controller._started = false;\n controller._closeRequested = false;\n controller._pullAgain = false;\n controller._pulling = false;\n\n controller._strategySizeAlgorithm = sizeAlgorithm;\n controller._strategyHWM = highWaterMark;\n\n controller._pullAlgorithm = pullAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n stream._readableStreamController = controller;\n\n const startResult = startAlgorithm();\n uponPromise(\n promiseResolvedWith(startResult),\n () => {\n controller._started = true;\n\n assert(!controller._pulling);\n assert(!controller._pullAgain);\n\n ReadableStreamDefaultControllerCallPullIfNeeded(controller);\n return null;\n },\n r => {\n ReadableStreamDefaultControllerError(controller, r);\n return null;\n }\n );\n}\n\nexport function SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n stream: ReadableStream,\n underlyingSource: ValidatedUnderlyingSource,\n highWaterMark: number,\n sizeAlgorithm: QueuingStrategySizeCallback\n) {\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n\n let startAlgorithm: () => void | PromiseLike;\n let pullAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (underlyingSource.start !== undefined) {\n startAlgorithm = () => underlyingSource.start!(controller);\n } else {\n startAlgorithm = () => undefined;\n }\n if (underlyingSource.pull !== undefined) {\n pullAlgorithm = () => underlyingSource.pull!(controller);\n } else {\n pullAlgorithm = () => promiseResolvedWith(undefined);\n }\n if (underlyingSource.cancel !== undefined) {\n cancelAlgorithm = reason => underlyingSource.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n}\n\n// Helper functions for the ReadableStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`);\n}\n","import {\n CreateReadableByteStream,\n CreateReadableStream,\n type DefaultReadableStream,\n IsReadableStream,\n type ReadableByteStream,\n ReadableStream,\n ReadableStreamCancel,\n type ReadableStreamReader\n} from '../readable-stream';\nimport { ReadableStreamReaderGenericRelease } from './generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReaderRead,\n type ReadRequest\n} from './default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReaderRead,\n type ReadIntoRequest\n} from './byob-reader';\nimport assert from '../../stub/assert';\nimport { newPromise, promiseResolvedWith, queueMicrotask, uponRejection } from '../helpers/webidl';\nimport {\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError\n} from './default-controller';\nimport {\n IsReadableByteStreamController,\n ReadableByteStreamControllerClose,\n ReadableByteStreamControllerEnqueue,\n ReadableByteStreamControllerError,\n ReadableByteStreamControllerGetBYOBRequest,\n ReadableByteStreamControllerRespond,\n ReadableByteStreamControllerRespondWithNewView\n} from './byte-stream-controller';\nimport { CreateArrayFromList } from '../abstract-ops/ecmascript';\nimport { CloneAsUint8Array } from '../abstract-ops/miscellaneous';\nimport type { NonShared } from '../helpers/array-buffer-view';\n\nexport function ReadableStreamTee(stream: ReadableStream,\n cloneForBranch2: boolean): [ReadableStream, ReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n if (IsReadableByteStreamController(stream._readableStreamController)) {\n return ReadableByteStreamTee(stream as unknown as ReadableByteStream) as\n unknown as [ReadableStream, ReadableStream];\n }\n return ReadableStreamDefaultTee(stream, cloneForBranch2);\n}\n\nexport function ReadableStreamDefaultTee(\n stream: ReadableStream,\n cloneForBranch2: boolean\n): [DefaultReadableStream, DefaultReadableStream] {\n assert(IsReadableStream(stream));\n assert(typeof cloneForBranch2 === 'boolean');\n\n const reader = AcquireReadableStreamDefaultReader(stream);\n\n let reading = false;\n let readAgain = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: DefaultReadableStream;\n let branch2: DefaultReadableStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function pullAlgorithm(): Promise {\n if (reading) {\n readAgain = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const readRequest: ReadRequest = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgain = false;\n const chunk1 = chunk;\n const chunk2 = chunk;\n\n // There is no way to access the cloning code right now in the reference implementation.\n // If we add one then we'll need an implementation for serializable objects.\n // if (!canceled2 && cloneForBranch2) {\n // chunk2 = StructuredDeserialize(StructuredSerialize(chunk2));\n // }\n\n if (!canceled1) {\n ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgain) {\n pullAlgorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableStreamDefaultControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableStreamDefaultControllerClose(branch2._readableStreamController);\n }\n\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm() {\n // do nothing\n }\n\n branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm);\n branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm);\n\n uponRejection(reader._closedPromise, (r: any) => {\n ReadableStreamDefaultControllerError(branch1._readableStreamController, r);\n ReadableStreamDefaultControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n\n return [branch1, branch2];\n}\n\nexport function ReadableByteStreamTee(stream: ReadableByteStream): [ReadableByteStream, ReadableByteStream] {\n assert(IsReadableStream(stream));\n assert(IsReadableByteStreamController(stream._readableStreamController));\n\n let reader: ReadableStreamReader> = AcquireReadableStreamDefaultReader(stream);\n let reading = false;\n let readAgainForBranch1 = false;\n let readAgainForBranch2 = false;\n let canceled1 = false;\n let canceled2 = false;\n let reason1: any;\n let reason2: any;\n let branch1: ReadableByteStream;\n let branch2: ReadableByteStream;\n\n let resolveCancelPromise: (value: undefined | Promise) => void;\n const cancelPromise = newPromise(resolve => {\n resolveCancelPromise = resolve;\n });\n\n function forwardReaderError(thisReader: ReadableStreamReader>) {\n uponRejection(thisReader._closedPromise, r => {\n if (thisReader !== reader) {\n return null;\n }\n ReadableByteStreamControllerError(branch1._readableStreamController, r);\n ReadableByteStreamControllerError(branch2._readableStreamController, r);\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n return null;\n });\n }\n\n function pullWithDefaultReader() {\n if (IsReadableStreamBYOBReader(reader)) {\n assert(reader._readIntoRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamDefaultReader(stream);\n forwardReaderError(reader);\n }\n\n const readRequest: ReadRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const chunk1 = chunk;\n let chunk2 = chunk;\n if (!canceled1 && !canceled2) {\n try {\n chunk2 = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(branch1._readableStreamController, cloneE);\n ReadableByteStreamControllerError(branch2._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n }\n\n if (!canceled1) {\n ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1);\n }\n if (!canceled2) {\n ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: () => {\n reading = false;\n if (!canceled1) {\n ReadableByteStreamControllerClose(branch1._readableStreamController);\n }\n if (!canceled2) {\n ReadableByteStreamControllerClose(branch2._readableStreamController);\n }\n if (branch1._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch1._readableStreamController, 0);\n }\n if (branch2._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(branch2._readableStreamController, 0);\n }\n if (!canceled1 || !canceled2) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamDefaultReaderRead(reader, readRequest);\n }\n\n function pullWithBYOBReader(view: NonShared, forBranch2: boolean) {\n if (IsReadableStreamDefaultReader>(reader)) {\n assert(reader._readRequests.length === 0);\n ReadableStreamReaderGenericRelease(reader);\n\n reader = AcquireReadableStreamBYOBReader(stream);\n forwardReaderError(reader);\n }\n\n const byobBranch = forBranch2 ? branch2 : branch1;\n const otherBranch = forBranch2 ? branch1 : branch2;\n\n const readIntoRequest: ReadIntoRequest> = {\n _chunkSteps: chunk => {\n // This needs to be delayed a microtask because it takes at least a microtask to detect errors (using\n // reader._closedPromise below), and we want errors in stream to error both branches immediately. We cannot let\n // successful synchronously-available reads get ahead of asynchronously-available errors.\n queueMicrotask(() => {\n readAgainForBranch1 = false;\n readAgainForBranch2 = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!otherCanceled) {\n let clonedChunk;\n try {\n clonedChunk = CloneAsUint8Array(chunk);\n } catch (cloneE) {\n ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE);\n ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE);\n resolveCancelPromise(ReadableStreamCancel(stream, cloneE));\n return;\n }\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk);\n } else if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n\n reading = false;\n if (readAgainForBranch1) {\n pull1Algorithm();\n } else if (readAgainForBranch2) {\n pull2Algorithm();\n }\n });\n },\n _closeSteps: chunk => {\n reading = false;\n\n const byobCanceled = forBranch2 ? canceled2 : canceled1;\n const otherCanceled = forBranch2 ? canceled1 : canceled2;\n\n if (!byobCanceled) {\n ReadableByteStreamControllerClose(byobBranch._readableStreamController);\n }\n if (!otherCanceled) {\n ReadableByteStreamControllerClose(otherBranch._readableStreamController);\n }\n\n if (chunk !== undefined) {\n assert(chunk.byteLength === 0);\n\n if (!byobCanceled) {\n ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk);\n }\n if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) {\n ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0);\n }\n }\n\n if (!byobCanceled || !otherCanceled) {\n resolveCancelPromise(undefined);\n }\n },\n _errorSteps: () => {\n reading = false;\n }\n };\n ReadableStreamBYOBReaderRead(reader, view, 1, readIntoRequest);\n }\n\n function pull1Algorithm(): Promise {\n if (reading) {\n readAgainForBranch1 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, false);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function pull2Algorithm(): Promise {\n if (reading) {\n readAgainForBranch2 = true;\n return promiseResolvedWith(undefined);\n }\n\n reading = true;\n\n const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController);\n if (byobRequest === null) {\n pullWithDefaultReader();\n } else {\n pullWithBYOBReader(byobRequest._view!, true);\n }\n\n return promiseResolvedWith(undefined);\n }\n\n function cancel1Algorithm(reason: any): Promise {\n canceled1 = true;\n reason1 = reason;\n if (canceled2) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function cancel2Algorithm(reason: any): Promise {\n canceled2 = true;\n reason2 = reason;\n if (canceled1) {\n const compositeReason = CreateArrayFromList([reason1, reason2]);\n const cancelResult = ReadableStreamCancel(stream, compositeReason);\n resolveCancelPromise(cancelResult);\n }\n return cancelPromise;\n }\n\n function startAlgorithm(): void {\n return;\n }\n\n branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm);\n branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm);\n\n forwardReaderError(reader);\n\n return [branch1, branch2];\n}\n","import { typeIsObject } from '../helpers/miscellaneous';\nimport type { ReadableStreamDefaultReadResult } from './default-reader';\n\n/**\n * A common interface for a `ReadadableStream` implementation.\n *\n * @public\n */\nexport interface ReadableStreamLike {\n readonly locked: boolean;\n\n getReader(): ReadableStreamDefaultReaderLike;\n}\n\n/**\n * A common interface for a `ReadableStreamDefaultReader` implementation.\n *\n * @public\n */\nexport interface ReadableStreamDefaultReaderLike {\n readonly closed: Promise;\n\n cancel(reason?: any): Promise;\n\n read(): Promise>;\n\n releaseLock(): void;\n}\n\nexport function isReadableStreamLike(stream: unknown): stream is ReadableStreamLike {\n return typeIsObject(stream) && typeof (stream as ReadableStreamLike).getReader !== 'undefined';\n}\n","import { CreateReadableStream, type DefaultReadableStream } from '../readable-stream';\nimport {\n isReadableStreamLike,\n type ReadableStreamDefaultReaderLike,\n type ReadableStreamLike\n} from './readable-stream-like';\nimport { ReadableStreamDefaultControllerClose, ReadableStreamDefaultControllerEnqueue } from './default-controller';\nimport { GetIterator, GetMethod, IteratorComplete, IteratorNext, IteratorValue } from '../abstract-ops/ecmascript';\nimport { promiseRejectedWith, promiseResolvedWith, reflectCall, transformPromiseWith } from '../helpers/webidl';\nimport { typeIsObject } from '../helpers/miscellaneous';\nimport { noop } from '../../utils';\n\nexport function ReadableStreamFrom(\n source: Iterable | AsyncIterable | ReadableStreamLike\n): DefaultReadableStream {\n if (isReadableStreamLike(source)) {\n return ReadableStreamFromDefaultReader(source.getReader());\n }\n return ReadableStreamFromIterable(source);\n}\n\nexport function ReadableStreamFromIterable(asyncIterable: Iterable | AsyncIterable): DefaultReadableStream {\n let stream: DefaultReadableStream;\n const iteratorRecord = GetIterator(asyncIterable, 'async');\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let nextResult;\n try {\n nextResult = IteratorNext(iteratorRecord);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const nextPromise = promiseResolvedWith(nextResult);\n return transformPromiseWith(nextPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.next() method must fulfill with an object');\n }\n const done = IteratorComplete(iterResult);\n if (done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = IteratorValue(iterResult);\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n const iterator = iteratorRecord.iterator;\n let returnMethod: (typeof iterator)['return'] | undefined;\n try {\n returnMethod = GetMethod(iterator, 'return');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n if (returnMethod === undefined) {\n return promiseResolvedWith(undefined);\n }\n let returnResult: IteratorResult | Promise>;\n try {\n returnResult = reflectCall(returnMethod, iterator, [reason]);\n } catch (e) {\n return promiseRejectedWith(e);\n }\n const returnPromise = promiseResolvedWith(returnResult);\n return transformPromiseWith(returnPromise, iterResult => {\n if (!typeIsObject(iterResult)) {\n throw new TypeError('The promise returned by the iterator.return() method must fulfill with an object');\n }\n return undefined;\n });\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n\nexport function ReadableStreamFromDefaultReader(\n reader: ReadableStreamDefaultReaderLike\n): DefaultReadableStream {\n let stream: DefaultReadableStream;\n\n const startAlgorithm = noop;\n\n function pullAlgorithm(): Promise {\n let readPromise;\n try {\n readPromise = reader.read();\n } catch (e) {\n return promiseRejectedWith(e);\n }\n return transformPromiseWith(readPromise, readResult => {\n if (!typeIsObject(readResult)) {\n throw new TypeError('The promise returned by the reader.read() method must fulfill with an object');\n }\n if (readResult.done) {\n ReadableStreamDefaultControllerClose(stream._readableStreamController);\n } else {\n const value = readResult.value;\n ReadableStreamDefaultControllerEnqueue(stream._readableStreamController, value);\n }\n });\n }\n\n function cancelAlgorithm(reason: any): Promise {\n try {\n return promiseResolvedWith(reader.cancel(reason));\n } catch (e) {\n return promiseRejectedWith(e);\n }\n }\n\n stream = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, 0);\n return stream;\n}\n","import { assertDictionary, assertFunction, convertUnsignedLongLongWithEnforceRange } from './basic';\nimport type {\n ReadableStreamController,\n UnderlyingByteSource,\n UnderlyingDefaultOrByteSource,\n UnderlyingDefaultOrByteSourcePullCallback,\n UnderlyingDefaultOrByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n ValidatedUnderlyingDefaultOrByteSource\n} from '../readable-stream/underlying-source';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\n\nexport function convertUnderlyingDefaultOrByteSource(\n source: UnderlyingSource | UnderlyingByteSource | null,\n context: string\n): ValidatedUnderlyingDefaultOrByteSource {\n assertDictionary(source, context);\n const original = source as (UnderlyingDefaultOrByteSource | null);\n const autoAllocateChunkSize = original?.autoAllocateChunkSize;\n const cancel = original?.cancel;\n const pull = original?.pull;\n const start = original?.start;\n const type = original?.type;\n return {\n autoAllocateChunkSize: autoAllocateChunkSize === undefined ?\n undefined :\n convertUnsignedLongLongWithEnforceRange(\n autoAllocateChunkSize,\n `${context} has member 'autoAllocateChunkSize' that`\n ),\n cancel: cancel === undefined ?\n undefined :\n convertUnderlyingSourceCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n pull: pull === undefined ?\n undefined :\n convertUnderlyingSourcePullCallback(pull, original!, `${context} has member 'pull' that`),\n start: start === undefined ?\n undefined :\n convertUnderlyingSourceStartCallback(start, original!, `${context} has member 'start' that`),\n type: type === undefined ? undefined : convertReadableStreamType(type, `${context} has member 'type' that`)\n };\n}\n\nfunction convertUnderlyingSourceCancelCallback(\n fn: UnderlyingSourceCancelCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n\nfunction convertUnderlyingSourcePullCallback(\n fn: UnderlyingDefaultOrByteSourcePullCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): (controller: ReadableStreamController) => Promise {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertUnderlyingSourceStartCallback(\n fn: UnderlyingDefaultOrByteSourceStartCallback,\n original: UnderlyingDefaultOrByteSource,\n context: string\n): UnderlyingDefaultOrByteSourceStartCallback {\n assertFunction(fn, context);\n return (controller: ReadableStreamController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertReadableStreamType(type: string, context: string): 'bytes' {\n type = `${type}`;\n if (type !== 'bytes') {\n throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`);\n }\n return type;\n}\n","import { assertDictionary } from './basic';\nimport type {\n ReadableStreamIteratorOptions,\n ValidatedReadableStreamIteratorOptions\n} from '../readable-stream/iterator-options';\n\nexport function convertIteratorOptions(options: ReadableStreamIteratorOptions | null | undefined,\n context: string): ValidatedReadableStreamIteratorOptions {\n assertDictionary(options, context);\n const preventCancel = options?.preventCancel;\n return { preventCancel: Boolean(preventCancel) };\n}\n","import { assertDictionary } from './basic';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from '../readable-stream/pipe-options';\nimport { type AbortSignal, isAbortSignal } from '../abort-signal';\n\nexport function convertPipeOptions(options: StreamPipeOptions | null | undefined,\n context: string): ValidatedStreamPipeOptions {\n assertDictionary(options, context);\n const preventAbort = options?.preventAbort;\n const preventCancel = options?.preventCancel;\n const preventClose = options?.preventClose;\n const signal = options?.signal;\n if (signal !== undefined) {\n assertAbortSignal(signal, `${context} has member 'signal' that`);\n }\n return {\n preventAbort: Boolean(preventAbort),\n preventCancel: Boolean(preventCancel),\n preventClose: Boolean(preventClose),\n signal\n };\n}\n\nfunction assertAbortSignal(signal: unknown, context: string): asserts signal is AbortSignal {\n if (!isAbortSignal(signal)) {\n throw new TypeError(`${context} is not an AbortSignal.`);\n }\n}\n","import { assertDictionary, assertRequiredField } from './basic';\nimport { ReadableStream } from '../readable-stream';\nimport { WritableStream } from '../writable-stream';\nimport { assertReadableStream } from './readable-stream';\nimport { assertWritableStream } from './writable-stream';\n\nexport function convertReadableWritablePair(\n pair: { readable: RS; writable: WS } | null | undefined,\n context: string\n): { readable: RS; writable: WS } {\n assertDictionary(pair, context);\n\n const readable = pair?.readable;\n assertRequiredField(readable, 'readable', 'ReadableWritablePair');\n assertReadableStream(readable, `${context} has member 'readable' that`);\n\n const writable = pair?.writable;\n assertRequiredField(writable, 'writable', 'ReadableWritablePair');\n assertWritableStream(writable, `${context} has member 'writable' that`);\n\n return { readable, writable };\n}\n","import assert from '../stub/assert';\nimport {\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith\n} from './helpers/webidl';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { AcquireReadableStreamAsyncIterator, type ReadableStreamAsyncIterator } from './readable-stream/async-iterator';\nimport { defaultReaderClosedPromiseReject, defaultReaderClosedPromiseResolve } from './readable-stream/generic-reader';\nimport {\n AcquireReadableStreamDefaultReader,\n IsReadableStreamDefaultReader,\n ReadableStreamDefaultReader,\n ReadableStreamDefaultReaderErrorReadRequests,\n type ReadableStreamDefaultReadResult\n} from './readable-stream/default-reader';\nimport {\n AcquireReadableStreamBYOBReader,\n IsReadableStreamBYOBReader,\n ReadableStreamBYOBReader,\n ReadableStreamBYOBReaderErrorReadIntoRequests,\n type ReadableStreamBYOBReadResult\n} from './readable-stream/byob-reader';\nimport { ReadableStreamPipeTo } from './readable-stream/pipe';\nimport { ReadableStreamTee } from './readable-stream/tee';\nimport { ReadableStreamFrom } from './readable-stream/from';\nimport { IsWritableStream, IsWritableStreamLocked, WritableStream } from './writable-stream';\nimport { SimpleQueue } from './simple-queue';\nimport {\n ReadableByteStreamController,\n ReadableStreamBYOBRequest,\n SetUpReadableByteStreamController,\n SetUpReadableByteStreamControllerFromUnderlyingSource\n} from './readable-stream/byte-stream-controller';\nimport {\n ReadableStreamDefaultController,\n SetUpReadableStreamDefaultController,\n SetUpReadableStreamDefaultControllerFromUnderlyingSource\n} from './readable-stream/default-controller';\nimport type {\n UnderlyingByteSource,\n UnderlyingByteSourcePullCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingSource,\n UnderlyingSourceCancelCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceStartCallback\n} from './readable-stream/underlying-source';\nimport { noop } from '../utils';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { CreateArrayFromList } from './abstract-ops/ecmascript';\nimport { CancelSteps } from './abstract-ops/internal-methods';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { assertObject, assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport { convertUnderlyingDefaultOrByteSource } from './validators/underlying-source';\nimport type {\n ReadableStreamBYOBReaderReadOptions,\n ReadableStreamGetReaderOptions\n} from './readable-stream/reader-options';\nimport { convertReaderOptions } from './validators/reader-options';\nimport type { StreamPipeOptions, ValidatedStreamPipeOptions } from './readable-stream/pipe-options';\nimport type { ReadableStreamIteratorOptions } from './readable-stream/iterator-options';\nimport { convertIteratorOptions } from './validators/iterator-options';\nimport { convertPipeOptions } from './validators/pipe-options';\nimport type { ReadableWritablePair } from './readable-stream/readable-writable-pair';\nimport { convertReadableWritablePair } from './validators/readable-writable-pair';\nimport type { ReadableStreamDefaultReaderLike, ReadableStreamLike } from './readable-stream/readable-stream-like';\nimport type { NonShared } from './helpers/array-buffer-view';\n\nexport type DefaultReadableStream = ReadableStream & {\n _readableStreamController: ReadableStreamDefaultController\n};\n\nexport type ReadableByteStream = ReadableStream> & {\n _readableStreamController: ReadableByteStreamController\n};\n\ntype ReadableStreamState = 'readable' | 'closed' | 'errored';\n\n/**\n * A readable stream represents a source of data, from which you can read.\n *\n * @public\n */\nexport class ReadableStream {\n /** @internal */\n _state!: ReadableStreamState;\n /** @internal */\n _reader: ReadableStreamReader | undefined;\n /** @internal */\n _storedError: any;\n /** @internal */\n _disturbed!: boolean;\n /** @internal */\n _readableStreamController!: ReadableStreamDefaultController | ReadableByteStreamController;\n\n constructor(underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined });\n constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy);\n constructor(rawUnderlyingSource: UnderlyingSource | UnderlyingByteSource | null | undefined = {},\n rawStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawUnderlyingSource === undefined) {\n rawUnderlyingSource = null;\n } else {\n assertObject(rawUnderlyingSource, 'First parameter');\n }\n\n const strategy = convertQueuingStrategy(rawStrategy, 'Second parameter');\n const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, 'First parameter');\n\n InitializeReadableStream(this);\n\n if (underlyingSource.type === 'bytes') {\n if (strategy.size !== undefined) {\n throw new RangeError('The strategy for a byte stream cannot have a size function');\n }\n const highWaterMark = ExtractHighWaterMark(strategy, 0);\n SetUpReadableByteStreamControllerFromUnderlyingSource(\n this as unknown as ReadableByteStream,\n underlyingSource,\n highWaterMark\n );\n } else {\n assert(underlyingSource.type === undefined);\n const sizeAlgorithm = ExtractSizeAlgorithm(strategy);\n const highWaterMark = ExtractHighWaterMark(strategy, 1);\n SetUpReadableStreamDefaultControllerFromUnderlyingSource(\n this,\n underlyingSource,\n highWaterMark,\n sizeAlgorithm\n );\n }\n }\n\n /**\n * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.\n */\n get locked(): boolean {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('locked');\n }\n\n return IsReadableStreamLocked(this);\n }\n\n /**\n * Cancels the stream, signaling a loss of interest in the stream by a consumer.\n *\n * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}\n * method, which might or might not use it.\n */\n cancel(reason: any = undefined): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('cancel'));\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(new TypeError('Cannot cancel a stream that already has a reader'));\n }\n\n return ReadableStreamCancel(this, reason);\n }\n\n /**\n * Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.\n *\n * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,\n * i.e. streams which were constructed specifically with the ability to handle \"bring your own buffer\" reading.\n * The returned BYOB reader provides the ability to directly read individual chunks from the stream via its\n * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise\n * control over allocation.\n */\n getReader({ mode }: { mode: 'byob' }): ReadableStreamBYOBReader;\n /**\n * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.\n * While the stream is locked, no other reader can be acquired until this one is released.\n *\n * This functionality is especially useful for creating abstractions that desire the ability to consume a stream\n * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours\n * or cancel the stream, which would interfere with your abstraction.\n */\n getReader(): ReadableStreamDefaultReader;\n getReader(\n rawOptions: ReadableStreamGetReaderOptions | null | undefined = undefined\n ): ReadableStreamDefaultReader | ReadableStreamBYOBReader {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('getReader');\n }\n\n const options = convertReaderOptions(rawOptions, 'First parameter');\n\n if (options.mode === undefined) {\n return AcquireReadableStreamDefaultReader(this);\n }\n\n assert(options.mode === 'byob');\n return AcquireReadableStreamBYOBReader(this as unknown as ReadableByteStream);\n }\n\n /**\n * Provides a convenient, chainable way of piping this readable stream through a transform stream\n * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream\n * into the writable side of the supplied pair, and returns the readable side for further use.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeThrough(\n transform: { readable: RS; writable: WritableStream },\n options?: StreamPipeOptions\n ): RS;\n pipeThrough(\n rawTransform: { readable: RS; writable: WritableStream } | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}\n ): RS {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('pipeThrough');\n }\n assertRequiredArgument(rawTransform, 1, 'pipeThrough');\n\n const transform = convertReadableWritablePair(rawTransform, 'First parameter');\n const options = convertPipeOptions(rawOptions, 'Second parameter');\n\n if (IsReadableStreamLocked(this)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream');\n }\n if (IsWritableStreamLocked(transform.writable)) {\n throw new TypeError('ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream');\n }\n\n const promise = ReadableStreamPipeTo(\n this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n\n setPromiseIsHandledToTrue(promise);\n\n return transform.readable;\n }\n\n /**\n * Pipes this readable stream to a given writable stream. The way in which the piping process behaves under\n * various error conditions can be customized with a number of passed options. It returns a promise that fulfills\n * when the piping process completes successfully, or rejects if any errors were encountered.\n *\n * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.\n */\n pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise;\n pipeTo(destination: WritableStream | null | undefined,\n rawOptions: StreamPipeOptions | null | undefined = {}): Promise {\n if (!IsReadableStream(this)) {\n return promiseRejectedWith(streamBrandCheckException('pipeTo'));\n }\n\n if (destination === undefined) {\n return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`);\n }\n if (!IsWritableStream(destination)) {\n return promiseRejectedWith(\n new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)\n );\n }\n\n let options: ValidatedStreamPipeOptions;\n try {\n options = convertPipeOptions(rawOptions, 'Second parameter');\n } catch (e) {\n return promiseRejectedWith(e);\n }\n\n if (IsReadableStreamLocked(this)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream')\n );\n }\n if (IsWritableStreamLocked(destination)) {\n return promiseRejectedWith(\n new TypeError('ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream')\n );\n }\n\n return ReadableStreamPipeTo(\n this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal\n );\n }\n\n /**\n * Tees this readable stream, returning a two-element array containing the two resulting branches as\n * new {@link ReadableStream} instances.\n *\n * Teeing a stream will lock it, preventing any other consumer from acquiring a reader.\n * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be\n * propagated to the stream's underlying source.\n *\n * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,\n * this could allow interference between the two branches.\n */\n tee(): [ReadableStream, ReadableStream] {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('tee');\n }\n\n const branches = ReadableStreamTee(this, false);\n return CreateArrayFromList(branches);\n }\n\n /**\n * Asynchronously iterates over the chunks in the stream's internal queue.\n *\n * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.\n * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method\n * is called, e.g. by breaking out of the loop.\n *\n * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also\n * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing\n * `true` for the `preventCancel` option.\n */\n values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator;\n values(rawOptions: ReadableStreamIteratorOptions | null | undefined = undefined): ReadableStreamAsyncIterator {\n if (!IsReadableStream(this)) {\n throw streamBrandCheckException('values');\n }\n\n const options = convertIteratorOptions(rawOptions, 'First parameter');\n return AcquireReadableStreamAsyncIterator(this, options.preventCancel);\n }\n\n /**\n * {@inheritDoc ReadableStream.values}\n */\n [Symbol.asyncIterator]!: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator;\n\n /**\n * Creates a new ReadableStream wrapping the provided iterable or async iterable.\n *\n * This can be used to adapt various kinds of objects into a readable stream,\n * such as an array, an async generator, or a Node.js readable stream.\n */\n static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream {\n return ReadableStreamFrom(asyncIterable);\n }\n}\n\nObject.defineProperties(ReadableStream, {\n from: { enumerable: true }\n});\nObject.defineProperties(ReadableStream.prototype, {\n cancel: { enumerable: true },\n getReader: { enumerable: true },\n pipeThrough: { enumerable: true },\n pipeTo: { enumerable: true },\n tee: { enumerable: true },\n values: { enumerable: true },\n locked: { enumerable: true }\n});\nsetFunctionName(ReadableStream.from, 'from');\nsetFunctionName(ReadableStream.prototype.cancel, 'cancel');\nsetFunctionName(ReadableStream.prototype.getReader, 'getReader');\nsetFunctionName(ReadableStream.prototype.pipeThrough, 'pipeThrough');\nsetFunctionName(ReadableStream.prototype.pipeTo, 'pipeTo');\nsetFunctionName(ReadableStream.prototype.tee, 'tee');\nsetFunctionName(ReadableStream.prototype.values, 'values');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.toStringTag, {\n value: 'ReadableStream',\n configurable: true\n });\n}\nif (typeof Symbol.asyncIterator === 'symbol') {\n Object.defineProperty(ReadableStream.prototype, Symbol.asyncIterator, {\n value: ReadableStream.prototype.values,\n writable: true,\n configurable: true\n });\n}\n\nexport type {\n ReadableStreamAsyncIterator,\n ReadableStreamDefaultReadResult,\n ReadableStreamBYOBReadResult,\n ReadableStreamBYOBReaderReadOptions,\n UnderlyingByteSource,\n UnderlyingSource,\n UnderlyingSourceStartCallback,\n UnderlyingSourcePullCallback,\n UnderlyingSourceCancelCallback,\n UnderlyingByteSourceStartCallback,\n UnderlyingByteSourcePullCallback,\n StreamPipeOptions,\n ReadableWritablePair,\n ReadableStreamIteratorOptions,\n ReadableStreamLike,\n ReadableStreamDefaultReaderLike\n};\n\n// Abstract operations for the ReadableStream.\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n highWaterMark = 1,\n sizeAlgorithm: QueuingStrategySizeCallback = () => 1\n): DefaultReadableStream {\n assert(IsNonNegativeNumber(highWaterMark));\n\n const stream: DefaultReadableStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableStreamDefaultController = Object.create(ReadableStreamDefaultController.prototype);\n SetUpReadableStreamDefaultController(\n stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm\n );\n\n return stream;\n}\n\n// Throws if and only if startAlgorithm throws.\nexport function CreateReadableByteStream(\n startAlgorithm: () => void | PromiseLike,\n pullAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise\n): ReadableByteStream {\n const stream: ReadableByteStream = Object.create(ReadableStream.prototype);\n InitializeReadableStream(stream);\n\n const controller: ReadableByteStreamController = Object.create(ReadableByteStreamController.prototype);\n SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined);\n\n return stream;\n}\n\nfunction InitializeReadableStream(stream: ReadableStream) {\n stream._state = 'readable';\n stream._reader = undefined;\n stream._storedError = undefined;\n stream._disturbed = false;\n}\n\nexport function IsReadableStream(x: unknown): x is ReadableStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_readableStreamController')) {\n return false;\n }\n\n return x instanceof ReadableStream;\n}\n\nexport function IsReadableStreamDisturbed(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n return stream._disturbed;\n}\n\nexport function IsReadableStreamLocked(stream: ReadableStream): boolean {\n assert(IsReadableStream(stream));\n\n if (stream._reader === undefined) {\n return false;\n }\n\n return true;\n}\n\n// ReadableStream API exposed for controllers.\n\nexport function ReadableStreamCancel(stream: ReadableStream, reason: any): Promise {\n stream._disturbed = true;\n\n if (stream._state === 'closed') {\n return promiseResolvedWith(undefined);\n }\n if (stream._state === 'errored') {\n return promiseRejectedWith(stream._storedError);\n }\n\n ReadableStreamClose(stream);\n\n const reader = stream._reader;\n if (reader !== undefined && IsReadableStreamBYOBReader(reader)) {\n const readIntoRequests = reader._readIntoRequests;\n reader._readIntoRequests = new SimpleQueue();\n readIntoRequests.forEach(readIntoRequest => {\n readIntoRequest._closeSteps(undefined);\n });\n }\n\n const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason);\n return transformPromiseWith(sourceCancelPromise, noop);\n}\n\nexport function ReadableStreamClose(stream: ReadableStream): void {\n assert(stream._state === 'readable');\n\n stream._state = 'closed';\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseResolve(reader);\n\n if (IsReadableStreamDefaultReader(reader)) {\n const readRequests = reader._readRequests;\n reader._readRequests = new SimpleQueue();\n readRequests.forEach(readRequest => {\n readRequest._closeSteps();\n });\n }\n}\n\nexport function ReadableStreamError(stream: ReadableStream, e: any): void {\n assert(IsReadableStream(stream));\n assert(stream._state === 'readable');\n\n stream._state = 'errored';\n stream._storedError = e;\n\n const reader = stream._reader;\n\n if (reader === undefined) {\n return;\n }\n\n defaultReaderClosedPromiseReject(reader, e);\n\n if (IsReadableStreamDefaultReader(reader)) {\n ReadableStreamDefaultReaderErrorReadRequests(reader, e);\n } else {\n assert(IsReadableStreamBYOBReader(reader));\n ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e);\n }\n}\n\n// Readers\n\nexport type ReadableStreamReader = ReadableStreamDefaultReader | ReadableStreamBYOBReader;\n\nexport {\n ReadableStreamDefaultReader,\n ReadableStreamBYOBReader\n};\n\n// Controllers\n\nexport {\n ReadableStreamDefaultController,\n ReadableStreamBYOBRequest,\n ReadableByteStreamController\n};\n\n// Helper functions for the ReadableStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`);\n}\n","import type { QueuingStrategyInit } from '../queuing-strategy';\nimport { assertDictionary, assertRequiredField, convertUnrestrictedDouble } from './basic';\n\nexport function convertQueuingStrategyInit(init: QueuingStrategyInit | null | undefined,\n context: string): QueuingStrategyInit {\n assertDictionary(init, context);\n const highWaterMark = init?.highWaterMark;\n assertRequiredField(highWaterMark, 'highWaterMark', 'QueuingStrategyInit');\n return {\n highWaterMark: convertUnrestrictedDouble(highWaterMark)\n };\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst byteLengthSizeFunction = (chunk: ArrayBufferView): number => {\n return chunk.byteLength;\n};\nsetFunctionName(byteLengthSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of bytes in each chunk.\n *\n * @public\n */\nexport default class ByteLengthQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _byteLengthQueuingStrategyHighWaterMark: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'ByteLengthQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('highWaterMark');\n }\n return this._byteLengthQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by returning the value of its `byteLength` property.\n */\n get size(): (chunk: ArrayBufferView) => number {\n if (!IsByteLengthQueuingStrategy(this)) {\n throw byteLengthBrandCheckException('size');\n }\n return byteLengthSizeFunction;\n }\n}\n\nObject.defineProperties(ByteLengthQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(ByteLengthQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'ByteLengthQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the ByteLengthQueuingStrategy.\n\nfunction byteLengthBrandCheckException(name: string): TypeError {\n return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`);\n}\n\nexport function IsByteLengthQueuingStrategy(x: any): x is ByteLengthQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_byteLengthQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof ByteLengthQueuingStrategy;\n}\n","import type { QueuingStrategy, QueuingStrategyInit } from './queuing-strategy';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { assertRequiredArgument } from './validators/basic';\nimport { convertQueuingStrategyInit } from './validators/queuing-strategy-init';\n\n// The size function must not have a prototype property nor be a constructor\nconst countSizeFunction = (): 1 => {\n return 1;\n};\nsetFunctionName(countSizeFunction, 'size');\n\n/**\n * A queuing strategy that counts the number of chunks.\n *\n * @public\n */\nexport default class CountQueuingStrategy implements QueuingStrategy {\n /** @internal */\n readonly _countQueuingStrategyHighWaterMark!: number;\n\n constructor(options: QueuingStrategyInit) {\n assertRequiredArgument(options, 1, 'CountQueuingStrategy');\n options = convertQueuingStrategyInit(options, 'First parameter');\n this._countQueuingStrategyHighWaterMark = options.highWaterMark;\n }\n\n /**\n * Returns the high water mark provided to the constructor.\n */\n get highWaterMark(): number {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('highWaterMark');\n }\n return this._countQueuingStrategyHighWaterMark;\n }\n\n /**\n * Measures the size of `chunk` by always returning 1.\n * This ensures that the total queue size is a count of the number of chunks in the queue.\n */\n get size(): (chunk: any) => 1 {\n if (!IsCountQueuingStrategy(this)) {\n throw countBrandCheckException('size');\n }\n return countSizeFunction;\n }\n}\n\nObject.defineProperties(CountQueuingStrategy.prototype, {\n highWaterMark: { enumerable: true },\n size: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(CountQueuingStrategy.prototype, Symbol.toStringTag, {\n value: 'CountQueuingStrategy',\n configurable: true\n });\n}\n\n// Helper functions for the CountQueuingStrategy.\n\nfunction countBrandCheckException(name: string): TypeError {\n return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`);\n}\n\nexport function IsCountQueuingStrategy(x: any): x is CountQueuingStrategy {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_countQueuingStrategyHighWaterMark')) {\n return false;\n }\n\n return x instanceof CountQueuingStrategy;\n}\n","import { assertDictionary, assertFunction } from './basic';\nimport { promiseCall, reflectCall } from '../helpers/webidl';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from '../transform-stream/transformer';\nimport { TransformStreamDefaultController } from '../transform-stream';\n\nexport function convertTransformer(original: Transformer | null,\n context: string): ValidatedTransformer {\n assertDictionary(original, context);\n const cancel = original?.cancel;\n const flush = original?.flush;\n const readableType = original?.readableType;\n const start = original?.start;\n const transform = original?.transform;\n const writableType = original?.writableType;\n return {\n cancel: cancel === undefined ?\n undefined :\n convertTransformerCancelCallback(cancel, original!, `${context} has member 'cancel' that`),\n flush: flush === undefined ?\n undefined :\n convertTransformerFlushCallback(flush, original!, `${context} has member 'flush' that`),\n readableType,\n start: start === undefined ?\n undefined :\n convertTransformerStartCallback(start, original!, `${context} has member 'start' that`),\n transform: transform === undefined ?\n undefined :\n convertTransformerTransformCallback(transform, original!, `${context} has member 'transform' that`),\n writableType\n };\n}\n\nfunction convertTransformerFlushCallback(\n fn: TransformerFlushCallback,\n original: Transformer,\n context: string\n): (controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => promiseCall(fn, original, [controller]);\n}\n\nfunction convertTransformerStartCallback(\n fn: TransformerStartCallback,\n original: Transformer,\n context: string\n): TransformerStartCallback {\n assertFunction(fn, context);\n return (controller: TransformStreamDefaultController) => reflectCall(fn, original, [controller]);\n}\n\nfunction convertTransformerTransformCallback(\n fn: TransformerTransformCallback,\n original: Transformer,\n context: string\n): (chunk: I, controller: TransformStreamDefaultController) => Promise {\n assertFunction(fn, context);\n return (chunk: I, controller: TransformStreamDefaultController) => promiseCall(fn, original, [chunk, controller]);\n}\n\nfunction convertTransformerCancelCallback(\n fn: TransformerCancelCallback,\n original: Transformer,\n context: string\n): (reason: any) => Promise {\n assertFunction(fn, context);\n return (reason: any) => promiseCall(fn, original, [reason]);\n}\n","import assert from '../stub/assert';\nimport {\n newPromise,\n promiseRejectedWith,\n promiseResolvedWith,\n setPromiseIsHandledToTrue,\n transformPromiseWith,\n uponPromise\n} from './helpers/webidl';\nimport { CreateReadableStream, type DefaultReadableStream, ReadableStream } from './readable-stream';\nimport {\n ReadableStreamDefaultControllerCanCloseOrEnqueue,\n ReadableStreamDefaultControllerClose,\n ReadableStreamDefaultControllerEnqueue,\n ReadableStreamDefaultControllerError,\n ReadableStreamDefaultControllerGetDesiredSize,\n ReadableStreamDefaultControllerHasBackpressure\n} from './readable-stream/default-controller';\nimport type { QueuingStrategy, QueuingStrategySizeCallback } from './queuing-strategy';\nimport { CreateWritableStream, WritableStream, WritableStreamDefaultControllerErrorIfNeeded } from './writable-stream';\nimport { setFunctionName, typeIsObject } from './helpers/miscellaneous';\nimport { IsNonNegativeNumber } from './abstract-ops/miscellaneous';\nimport { convertQueuingStrategy } from './validators/queuing-strategy';\nimport { ExtractHighWaterMark, ExtractSizeAlgorithm } from './abstract-ops/queuing-strategy';\nimport type {\n Transformer,\n TransformerCancelCallback,\n TransformerFlushCallback,\n TransformerStartCallback,\n TransformerTransformCallback,\n ValidatedTransformer\n} from './transform-stream/transformer';\nimport { convertTransformer } from './validators/transformer';\n\n// Class TransformStream\n\n/**\n * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},\n * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.\n * In a manner specific to the transform stream in question, writes to the writable side result in new data being\n * made available for reading from the readable side.\n *\n * @public\n */\nexport class TransformStream {\n /** @internal */\n _writable!: WritableStream;\n /** @internal */\n _readable!: DefaultReadableStream;\n /** @internal */\n _backpressure!: boolean;\n /** @internal */\n _backpressureChangePromise!: Promise;\n /** @internal */\n _backpressureChangePromise_resolve!: () => void;\n /** @internal */\n _transformStreamController!: TransformStreamDefaultController;\n\n constructor(\n transformer?: Transformer,\n writableStrategy?: QueuingStrategy,\n readableStrategy?: QueuingStrategy\n );\n constructor(rawTransformer: Transformer | null | undefined = {},\n rawWritableStrategy: QueuingStrategy | null | undefined = {},\n rawReadableStrategy: QueuingStrategy | null | undefined = {}) {\n if (rawTransformer === undefined) {\n rawTransformer = null;\n }\n\n const writableStrategy = convertQueuingStrategy(rawWritableStrategy, 'Second parameter');\n const readableStrategy = convertQueuingStrategy(rawReadableStrategy, 'Third parameter');\n\n const transformer = convertTransformer(rawTransformer, 'First parameter');\n if (transformer.readableType !== undefined) {\n throw new RangeError('Invalid readableType specified');\n }\n if (transformer.writableType !== undefined) {\n throw new RangeError('Invalid writableType specified');\n }\n\n const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0);\n const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy);\n const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1);\n const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(\n this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm\n );\n SetUpTransformStreamDefaultControllerFromTransformer(this, transformer);\n\n if (transformer.start !== undefined) {\n startPromise_resolve(transformer.start(this._transformStreamController));\n } else {\n startPromise_resolve(undefined);\n }\n }\n\n /**\n * The readable side of the transform stream.\n */\n get readable(): ReadableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('readable');\n }\n\n return this._readable;\n }\n\n /**\n * The writable side of the transform stream.\n */\n get writable(): WritableStream {\n if (!IsTransformStream(this)) {\n throw streamBrandCheckException('writable');\n }\n\n return this._writable;\n }\n}\n\nObject.defineProperties(TransformStream.prototype, {\n readable: { enumerable: true },\n writable: { enumerable: true }\n});\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStream.prototype, Symbol.toStringTag, {\n value: 'TransformStream',\n configurable: true\n });\n}\n\nexport type {\n Transformer,\n TransformerCancelCallback,\n TransformerStartCallback,\n TransformerFlushCallback,\n TransformerTransformCallback\n};\n\n// Transform Stream Abstract Operations\n\nexport function CreateTransformStream(startAlgorithm: () => void | PromiseLike,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise,\n writableHighWaterMark = 1,\n writableSizeAlgorithm: QueuingStrategySizeCallback = () => 1,\n readableHighWaterMark = 0,\n readableSizeAlgorithm: QueuingStrategySizeCallback = () => 1) {\n assert(IsNonNegativeNumber(writableHighWaterMark));\n assert(IsNonNegativeNumber(readableHighWaterMark));\n\n const stream: TransformStream = Object.create(TransformStream.prototype);\n\n let startPromise_resolve!: (value: void | PromiseLike) => void;\n const startPromise = newPromise(resolve => {\n startPromise_resolve = resolve;\n });\n\n InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n\n const startResult = startAlgorithm();\n startPromise_resolve(startResult);\n return stream;\n}\n\nfunction InitializeTransformStream(stream: TransformStream,\n startPromise: Promise,\n writableHighWaterMark: number,\n writableSizeAlgorithm: QueuingStrategySizeCallback,\n readableHighWaterMark: number,\n readableSizeAlgorithm: QueuingStrategySizeCallback) {\n function startAlgorithm(): Promise {\n return startPromise;\n }\n\n function writeAlgorithm(chunk: I): Promise {\n return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk);\n }\n\n function abortAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSinkAbortAlgorithm(stream, reason);\n }\n\n function closeAlgorithm(): Promise {\n return TransformStreamDefaultSinkCloseAlgorithm(stream);\n }\n\n stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm,\n writableHighWaterMark, writableSizeAlgorithm);\n\n function pullAlgorithm(): Promise {\n return TransformStreamDefaultSourcePullAlgorithm(stream);\n }\n\n function cancelAlgorithm(reason: any): Promise {\n return TransformStreamDefaultSourceCancelAlgorithm(stream, reason);\n }\n\n stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark,\n readableSizeAlgorithm);\n\n // The [[backpressure]] slot is set to undefined so that it can be initialised by TransformStreamSetBackpressure.\n stream._backpressure = undefined!;\n stream._backpressureChangePromise = undefined!;\n stream._backpressureChangePromise_resolve = undefined!;\n TransformStreamSetBackpressure(stream, true);\n\n stream._transformStreamController = undefined!;\n}\n\nfunction IsTransformStream(x: unknown): x is TransformStream {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_transformStreamController')) {\n return false;\n }\n\n return x instanceof TransformStream;\n}\n\n// This is a no-op if both sides are already errored.\nfunction TransformStreamError(stream: TransformStream, e: any) {\n ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e);\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n}\n\nfunction TransformStreamErrorWritableAndUnblockWrite(stream: TransformStream, e: any) {\n TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController);\n WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e);\n TransformStreamUnblockWrite(stream);\n}\n\nfunction TransformStreamUnblockWrite(stream: TransformStream) {\n if (stream._backpressure) {\n // Pretend that pull() was called to permit any pending write() calls to complete. TransformStreamSetBackpressure()\n // cannot be called from enqueue() or pull() once the ReadableStream is errored, so this will will be the final time\n // _backpressure is set.\n TransformStreamSetBackpressure(stream, false);\n }\n}\n\nfunction TransformStreamSetBackpressure(stream: TransformStream, backpressure: boolean) {\n // Passes also when called during construction.\n assert(stream._backpressure !== backpressure);\n\n if (stream._backpressureChangePromise !== undefined) {\n stream._backpressureChangePromise_resolve();\n }\n\n stream._backpressureChangePromise = newPromise(resolve => {\n stream._backpressureChangePromise_resolve = resolve;\n });\n\n stream._backpressure = backpressure;\n}\n\n// Class TransformStreamDefaultController\n\n/**\n * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.\n *\n * @public\n */\nexport class TransformStreamDefaultController {\n /** @internal */\n _controlledTransformStream: TransformStream;\n /** @internal */\n _finishPromise: Promise | undefined;\n /** @internal */\n _finishPromise_resolve?: (value?: undefined) => void;\n /** @internal */\n _finishPromise_reject?: (reason: any) => void;\n /** @internal */\n _transformAlgorithm: (chunk: any) => Promise;\n /** @internal */\n _flushAlgorithm: () => Promise;\n /** @internal */\n _cancelAlgorithm: (reason: any) => Promise;\n\n private constructor() {\n throw new TypeError('Illegal constructor');\n }\n\n /**\n * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full.\n */\n get desiredSize(): number | null {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('desiredSize');\n }\n\n const readableController = this._controlledTransformStream._readable._readableStreamController;\n return ReadableStreamDefaultControllerGetDesiredSize(readableController);\n }\n\n /**\n * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.\n */\n enqueue(chunk: O): void;\n enqueue(chunk: O = undefined!): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('enqueue');\n }\n\n TransformStreamDefaultControllerEnqueue(this, chunk);\n }\n\n /**\n * Errors both the readable side and the writable side of the controlled transform stream, making all future\n * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.\n */\n error(reason: any = undefined): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('error');\n }\n\n TransformStreamDefaultControllerError(this, reason);\n }\n\n /**\n * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the\n * transformer only needs to consume a portion of the chunks written to the writable side.\n */\n terminate(): void {\n if (!IsTransformStreamDefaultController(this)) {\n throw defaultControllerBrandCheckException('terminate');\n }\n\n TransformStreamDefaultControllerTerminate(this);\n }\n}\n\nObject.defineProperties(TransformStreamDefaultController.prototype, {\n enqueue: { enumerable: true },\n error: { enumerable: true },\n terminate: { enumerable: true },\n desiredSize: { enumerable: true }\n});\nsetFunctionName(TransformStreamDefaultController.prototype.enqueue, 'enqueue');\nsetFunctionName(TransformStreamDefaultController.prototype.error, 'error');\nsetFunctionName(TransformStreamDefaultController.prototype.terminate, 'terminate');\nif (typeof Symbol.toStringTag === 'symbol') {\n Object.defineProperty(TransformStreamDefaultController.prototype, Symbol.toStringTag, {\n value: 'TransformStreamDefaultController',\n configurable: true\n });\n}\n\n// Transform Stream Default Controller Abstract Operations\n\nfunction IsTransformStreamDefaultController(x: any): x is TransformStreamDefaultController {\n if (!typeIsObject(x)) {\n return false;\n }\n\n if (!Object.prototype.hasOwnProperty.call(x, '_controlledTransformStream')) {\n return false;\n }\n\n return x instanceof TransformStreamDefaultController;\n}\n\nfunction SetUpTransformStreamDefaultController(stream: TransformStream,\n controller: TransformStreamDefaultController,\n transformAlgorithm: (chunk: I) => Promise,\n flushAlgorithm: () => Promise,\n cancelAlgorithm: (reason: any) => Promise) {\n assert(IsTransformStream(stream));\n assert(stream._transformStreamController === undefined);\n\n controller._controlledTransformStream = stream;\n stream._transformStreamController = controller;\n\n controller._transformAlgorithm = transformAlgorithm;\n controller._flushAlgorithm = flushAlgorithm;\n controller._cancelAlgorithm = cancelAlgorithm;\n\n controller._finishPromise = undefined;\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nfunction SetUpTransformStreamDefaultControllerFromTransformer(stream: TransformStream,\n transformer: ValidatedTransformer) {\n const controller: TransformStreamDefaultController = Object.create(TransformStreamDefaultController.prototype);\n\n let transformAlgorithm: (chunk: I) => Promise;\n let flushAlgorithm: () => Promise;\n let cancelAlgorithm: (reason: any) => Promise;\n\n if (transformer.transform !== undefined) {\n transformAlgorithm = chunk => transformer.transform!(chunk, controller);\n } else {\n transformAlgorithm = chunk => {\n try {\n TransformStreamDefaultControllerEnqueue(controller, chunk as unknown as O);\n return promiseResolvedWith(undefined);\n } catch (transformResultE) {\n return promiseRejectedWith(transformResultE);\n }\n };\n }\n\n if (transformer.flush !== undefined) {\n flushAlgorithm = () => transformer.flush!(controller);\n } else {\n flushAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n if (transformer.cancel !== undefined) {\n cancelAlgorithm = reason => transformer.cancel!(reason);\n } else {\n cancelAlgorithm = () => promiseResolvedWith(undefined);\n }\n\n SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm, cancelAlgorithm);\n}\n\nfunction TransformStreamDefaultControllerClearAlgorithms(controller: TransformStreamDefaultController) {\n controller._transformAlgorithm = undefined!;\n controller._flushAlgorithm = undefined!;\n controller._cancelAlgorithm = undefined!;\n}\n\nfunction TransformStreamDefaultControllerEnqueue(controller: TransformStreamDefaultController, chunk: O) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) {\n throw new TypeError('Readable side is not in a state that permits enqueue');\n }\n\n // We throttle transform invocations based on the backpressure of the ReadableStream, but we still\n // accept TransformStreamDefaultControllerEnqueue() calls.\n\n try {\n ReadableStreamDefaultControllerEnqueue(readableController, chunk);\n } catch (e) {\n // This happens when readableStrategy.size() throws.\n TransformStreamErrorWritableAndUnblockWrite(stream, e);\n\n throw stream._readable._storedError;\n }\n\n const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController);\n if (backpressure !== stream._backpressure) {\n assert(backpressure);\n TransformStreamSetBackpressure(stream, true);\n }\n}\n\nfunction TransformStreamDefaultControllerError(controller: TransformStreamDefaultController, e: any) {\n TransformStreamError(controller._controlledTransformStream, e);\n}\n\nfunction TransformStreamDefaultControllerPerformTransform(controller: TransformStreamDefaultController,\n chunk: I) {\n const transformPromise = controller._transformAlgorithm(chunk);\n return transformPromiseWith(transformPromise, undefined, r => {\n TransformStreamError(controller._controlledTransformStream, r);\n throw r;\n });\n}\n\nfunction TransformStreamDefaultControllerTerminate(controller: TransformStreamDefaultController) {\n const stream = controller._controlledTransformStream;\n const readableController = stream._readable._readableStreamController;\n\n ReadableStreamDefaultControllerClose(readableController);\n\n const error = new TypeError('TransformStream terminated');\n TransformStreamErrorWritableAndUnblockWrite(stream, error);\n}\n\n// TransformStreamDefaultSink Algorithms\n\nfunction TransformStreamDefaultSinkWriteAlgorithm(stream: TransformStream, chunk: I): Promise {\n assert(stream._writable._state === 'writable');\n\n const controller = stream._transformStreamController;\n\n if (stream._backpressure) {\n const backpressureChangePromise = stream._backpressureChangePromise;\n assert(backpressureChangePromise !== undefined);\n return transformPromiseWith(backpressureChangePromise, () => {\n const writable = stream._writable;\n const state = writable._state;\n if (state === 'erroring') {\n throw writable._storedError;\n }\n assert(state === 'writable');\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n });\n }\n\n return TransformStreamDefaultControllerPerformTransform(controller, chunk);\n}\n\nfunction TransformStreamDefaultSinkAbortAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _cancelAlgorithm calls readable.cancel() internally,\n // we don't run the _cancelAlgorithm again.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerError(readable._readableStreamController, reason);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\nfunction TransformStreamDefaultSinkCloseAlgorithm(stream: TransformStream): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._readable cannot change after construction, so caching it across a call to user code is safe.\n const readable = stream._readable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls readable.cancel() internally,\n // we don't also run the _cancelAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const flushPromise = controller._flushAlgorithm();\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(flushPromise, () => {\n if (readable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, readable._storedError);\n } else {\n ReadableStreamDefaultControllerClose(readable._readableStreamController);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n ReadableStreamDefaultControllerError(readable._readableStreamController, r);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// TransformStreamDefaultSource Algorithms\n\nfunction TransformStreamDefaultSourcePullAlgorithm(stream: TransformStream): Promise {\n // Invariant. Enforced by the promises returned by start() and pull().\n assert(stream._backpressure);\n\n assert(stream._backpressureChangePromise !== undefined);\n\n TransformStreamSetBackpressure(stream, false);\n\n // Prevent the next pull() call until there is backpressure.\n return stream._backpressureChangePromise;\n}\n\nfunction TransformStreamDefaultSourceCancelAlgorithm(stream: TransformStream, reason: any): Promise {\n const controller = stream._transformStreamController;\n if (controller._finishPromise !== undefined) {\n return controller._finishPromise;\n }\n\n // stream._writable cannot change after construction, so caching it across a call to user code is safe.\n const writable = stream._writable;\n\n // Assign the _finishPromise now so that if _flushAlgorithm calls writable.abort() or\n // writable.cancel() internally, we don't run the _cancelAlgorithm again, or also run the\n // _flushAlgorithm.\n controller._finishPromise = newPromise((resolve, reject) => {\n controller._finishPromise_resolve = resolve;\n controller._finishPromise_reject = reject;\n });\n\n const cancelPromise = controller._cancelAlgorithm(reason);\n TransformStreamDefaultControllerClearAlgorithms(controller);\n\n uponPromise(cancelPromise, () => {\n if (writable._state === 'errored') {\n defaultControllerFinishPromiseReject(controller, writable._storedError);\n } else {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, reason);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseResolve(controller);\n }\n return null;\n }, r => {\n WritableStreamDefaultControllerErrorIfNeeded(writable._writableStreamController, r);\n TransformStreamUnblockWrite(stream);\n defaultControllerFinishPromiseReject(controller, r);\n return null;\n });\n\n return controller._finishPromise;\n}\n\n// Helper functions for the TransformStreamDefaultController.\n\nfunction defaultControllerBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`);\n}\n\nexport function defaultControllerFinishPromiseResolve(controller: TransformStreamDefaultController) {\n if (controller._finishPromise_resolve === undefined) {\n return;\n }\n\n controller._finishPromise_resolve();\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\nexport function defaultControllerFinishPromiseReject(controller: TransformStreamDefaultController, reason: any) {\n if (controller._finishPromise_reject === undefined) {\n return;\n }\n\n setPromiseIsHandledToTrue(controller._finishPromise!);\n controller._finishPromise_reject(reason);\n controller._finishPromise_resolve = undefined;\n controller._finishPromise_reject = undefined;\n}\n\n// Helper functions for the TransformStream.\n\nfunction streamBrandCheckException(name: string): TypeError {\n return new TypeError(\n `TransformStream.prototype.${name} can only be used on a TransformStream`);\n}\n"],"names":["Symbol","queueMicrotask","streamBrandCheckException","defaultControllerBrandCheckException"],"mappings":";;;;;;;AAAA;AAEA,IAAM,cAAc,GAClB,OAAO,MAAM,KAAK,UAAU,IAAI,OAAO,MAAM,CAAC,QAAQ,KAAK,QAAQ;AACjE,IAAA,MAAM;IACN,UAAA,WAAW,IAAI,OAAA,SAAA,CAAA,MAAA,CAAU,WAAW,EAAoB,GAAA,CAAA,CAAA,EAAA;;ACL5D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AA4GA;AACO,SAAS,WAAW,CAAC,OAAO,EAAE,IAAI,EAAE;AAC3C,IAAI,IAAI,CAAC,GAAG,EAAE,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,C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,CAAC,CAAC;AACpC,QAAA,oCAAoC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC;AACpD,QAAA,OAAO,IAAI,CAAC;AACd,KAAC,CAAC,CAAC;IAEH,OAAO,UAAU,CAAC,cAAc,CAAC;AACnC,CAAC;AAED;AAEA,SAAS,oCAAoC,CAAC,IAAY,EAAA;AACxD,IAAA,OAAO,IAAI,SAAS,CAClB,qDAA8C,IAAI,EAAA,yDAAA,CAAyD,CAAC,CAAC;AACjH,CAAC;AAEK,SAAU,qCAAqC,CAAC,UAAiD,EAAA;AACrG,IAAA,IAAI,UAAU,CAAC,sBAAsB,KAAK,SAAS,EAAE;QACnD,OAAO;KACR;IAED,UAAU,CAAC,sBAAsB,EAAE,CAAC;AACpC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAEe,SAAA,oCAAoC,CAAC,UAAiD,EAAE,MAAW,EAAA;AACjH,IAAA,IAAI,UAAU,CAAC,qBAAqB,KAAK,SAAS,EAAE;QAClD,OAAO;KACR;AAED,IAAA,yBAAyB,CAAC,UAAU,CAAC,cAAe,CAAC,CAAC;AACtD,IAAA,UAAU,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACzC,IAAA,UAAU,CAAC,sBAAsB,GAAG,SAAS,CAAC;AAC9C,IAAA,UAAU,CAAC,qBAAqB,GAAG,SAAS,CAAC;AAC/C,CAAC;AAED;AAEA,SAAS,yBAAyB,CAAC,IAAY,EAAA;AAC7C,IAAA,OAAO,IAAI,SAAS,CAClB,oCAA6B,IAAI,EAAA,wCAAA,CAAwC,CAAC,CAAC;AAC/E;;;;","x_google_ignoreList":[1]} \ No newline at end of file diff --git a/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts b/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts new file mode 100644 index 0000000..06f7b69 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/types/polyfill.d.ts @@ -0,0 +1,24 @@ +/// +/// +import { ReadableStreamAsyncIterator, ReadableStreamIteratorOptions } from './ponyfill'; +export * from './ponyfill'; +declare global { + interface ReadableStream { + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator; + } +} diff --git a/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts b/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts new file mode 100644 index 0000000..2201422 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/types/ponyfill.d.ts @@ -0,0 +1,780 @@ +/// +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * If aborted, returns the reason for aborting. + */ + readonly reason?: any; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /* + * Returns the high water mark provided to the constructor. + */ + readonly highWaterMark: number; + /* + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + readonly size: (chunk: ArrayBufferView) => number; +} +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /* + * Returns the high water mark provided to the constructor. + */ + readonly highWaterMark: number; + /* + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + readonly size: (chunk: any) => 1; +} +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} +/** + * {@inheritDoc QueuingStrategy.size} + * @public + */ +export declare type QueuingStrategySizeCallback = (chunk: T) => number; +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /* + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + readonly byobRequest: ReadableStreamBYOBRequest | null; + /* + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + readonly desiredSize: number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /* + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + readonly locked: boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link 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 + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | 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. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. 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. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ + ReadableStream, + ReadableStream + ]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream; +} +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterator { + next(): Promise>; + return(value?: any): Promise>; +} +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T, options?: ReadableStreamBYOBReaderReadOptions): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} +/** + * Options for {@link ReadableStreamBYOBReader.read | reading} a stream + * with a {@link ReadableStreamBYOBReader | BYOB reader}. + * + * @public + */ +export declare interface ReadableStreamBYOBReaderReadOptions { + min?: number; +} +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /* + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + readonly view: ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /* + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + readonly desiredSize: number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} +/** + * A common interface for a `ReadableStreamDefaultReader` implementation. + * + * @public + */ +export declare interface ReadableStreamDefaultReaderLike { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} +/** + * A common interface for a `ReadadableStream` implementation. + * + * @public + */ +export declare interface ReadableStreamLike { + readonly locked: boolean; + getReader(): ReadableStreamDefaultReaderLike; +} +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + /** + * A function called when the readable side is cancelled, or when the writable side is aborted. + */ + cancel?: TransformerCancelCallback; + readableType?: undefined; + writableType?: undefined; +} +/** @public */ +export declare type TransformerCancelCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /* + * The readable side of the transform stream. + */ + readonly readable: ReadableStream; + /* + * The writable side of the transform stream. + */ + readonly writable: WritableStream; +} +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /* + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + readonly desiredSize: number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /* + * Returns whether or not the writable stream is locked to a writer. + */ + readonly locked: boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /* + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + readonly abortReason: any; + /* + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + readonly signal: AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /* + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + readonly closed: Promise; + /* + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + readonly desiredSize: number | null; + /* + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + readonly ready: Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} +export {}; diff --git a/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts b/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts new file mode 100644 index 0000000..93ea710 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/types/ts3.6/polyfill.d.ts @@ -0,0 +1,29 @@ +/// +/// + +import type { ReadableStreamAsyncIterator, ReadableStreamIteratorOptions } from './ponyfill'; + +export * from './ponyfill'; + +declare global { + interface ReadableStream { + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator; + } +} + diff --git a/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts b/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts new file mode 100644 index 0000000..7305800 --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/types/ts3.6/ponyfill.d.ts @@ -0,0 +1,821 @@ +/// + +/** + * A signal object that allows you to communicate with a request and abort it if required + * via its associated `AbortController` object. + * + * @remarks + * This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types. + * It is redefined here, so it can be polyfilled without a DOM, for example with + * {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment. + * + * @public + */ +export declare interface AbortSignal { + /** + * Whether the request is aborted. + */ + readonly aborted: boolean; + /** + * If aborted, returns the reason for aborting. + */ + readonly reason?: any; + /** + * Add an event listener to be triggered when this signal becomes aborted. + */ + addEventListener(type: 'abort', listener: () => void): void; + /** + * Remove an event listener that was previously added with {@link AbortSignal.addEventListener}. + */ + removeEventListener(type: 'abort', listener: () => void): void; +} + +/** + * A queuing strategy that counts the number of bytes in each chunk. + * + * @public + */ +export declare class ByteLengthQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by returning the value of its `byteLength` property. + */ + get size(): (chunk: ArrayBufferView) => number; +} + +/** + * A queuing strategy that counts the number of chunks. + * + * @public + */ +export declare class CountQueuingStrategy implements QueuingStrategy { + constructor(options: QueuingStrategyInit); + /** + * Returns the high water mark provided to the constructor. + */ + get highWaterMark(): number; + /** + * Measures the size of `chunk` by always returning 1. + * This ensures that the total queue size is a count of the number of chunks in the queue. + */ + get size(): (chunk: any) => 1; +} + +/** + * A queuing strategy. + * + * @public + */ +export declare interface QueuingStrategy { + /** + * A non-negative number indicating the high water mark of the stream using this queuing strategy. + */ + highWaterMark?: number; + /** + * A function that computes and returns the finite non-negative size of the given chunk value. + */ + size?: QueuingStrategySizeCallback; +} + +/** + * @public + */ +export declare interface QueuingStrategyInit { + /** + * {@inheritDoc QueuingStrategy.highWaterMark} + */ + highWaterMark: number; +} + +/** + * {@inheritDoc QueuingStrategy.size} + * @public + */ +export declare type QueuingStrategySizeCallback = (chunk: T) => number; + +/** + * Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableByteStreamController { + private constructor(); + /** + * Returns the current BYOB pull request, or `null` if there isn't one. + */ + get byobRequest(): ReadableStreamBYOBRequest | null; + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk chunk in the controlled readable stream. + * The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown. + */ + enqueue(chunk: ArrayBufferView): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A readable stream represents a source of data, from which you can read. + * + * @public + */ +export declare class ReadableStream { + constructor(underlyingSource: UnderlyingByteSource, strategy?: { + highWaterMark?: number; + size?: undefined; + }); + constructor(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy); + /** + * Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}. + */ + get locked(): boolean; + /** + * Cancels the stream, signaling a loss of interest in the stream by a consumer. + * + * The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()} + * method, which might or might not use it. + */ + cancel(reason?: any): Promise; + /** + * Creates a {@link 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 + * {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise + * control over allocation. + */ + getReader({ mode }: { + mode: 'byob'; + }): ReadableStreamBYOBReader; + /** + * Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader. + * While the stream is locked, no other reader can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to consume a stream + * in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours + * or cancel the stream, which would interfere with your abstraction. + */ + getReader(): ReadableStreamDefaultReader; + /** + * Provides a convenient, chainable way of piping this readable stream through a transform stream + * (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | 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. + */ + pipeThrough(transform: { + readable: RS; + writable: WritableStream; + }, options?: StreamPipeOptions): RS; + /** + * Pipes this readable stream to a given writable stream. 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. + */ + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + /** + * Tees this readable stream, returning a two-element array containing the two resulting branches as + * new {@link ReadableStream} instances. + * + * Teeing a stream will lock it, preventing any other consumer from acquiring a reader. + * To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be + * propagated to the stream's underlying source. + * + * Note that the chunks seen in each branch will be the same object. If the chunks are not immutable, + * this could allow interference between the two branches. + */ + tee(): [ReadableStream, ReadableStream]; + /** + * Asynchronously iterates over the chunks in the stream's internal queue. + * + * Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader. + * The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method + * is called, e.g. by breaking out of the loop. + * + * By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also + * cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing + * `true` for the `preventCancel` option. + */ + values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator; + /** + * {@inheritDoc ReadableStream.values} + */ + [Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator; + /** + * Creates a new ReadableStream wrapping the provided iterable or async iterable. + * + * This can be used to adapt various kinds of objects into a readable stream, + * such as an array, an async generator, or a Node.js readable stream. + */ + static from(asyncIterable: Iterable | AsyncIterable | ReadableStreamLike): ReadableStream; +} + +/** + * An async iterator returned by {@link ReadableStream.values}. + * + * @public + */ +export declare interface ReadableStreamAsyncIterator extends AsyncIterator { + next(): Promise>; + return(value?: any): Promise>; +} + +/** + * A BYOB reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamBYOBReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Attempts to reads bytes into view, and returns a promise resolved with the result. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(view: T, options?: ReadableStreamBYOBReaderReadOptions): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * Options for {@link ReadableStreamBYOBReader.read | reading} a stream + * with a {@link ReadableStreamBYOBReader | BYOB reader}. + * + * @public + */ +export declare interface ReadableStreamBYOBReaderReadOptions { + min?: number; +} + +/** + * A result returned by {@link ReadableStreamBYOBReader.read}. + * + * @public + */ +export declare type ReadableStreamBYOBReadResult = { + done: false; + value: T; +} | { + done: true; + value: T | undefined; +}; + +/** + * A pull-into request in a {@link ReadableByteStreamController}. + * + * @public + */ +export declare class ReadableStreamBYOBRequest { + private constructor(); + /** + * Returns the view for writing in to, or `null` if the BYOB request has already been responded to. + */ + get view(): ArrayBufferView | null; + /** + * Indicates to the associated readable byte stream that `bytesWritten` bytes were written into + * {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer. + * + * After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer + * modifiable. + */ + respond(bytesWritten: number): void; + /** + * Indicates to the associated readable byte stream that instead of writing into + * {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`, + * which will be given to the consumer of the readable byte stream. + * + * After this method is called, `view` will be transferred and no longer modifiable. + */ + respondWithNewView(view: ArrayBufferView): void; +} + +/** + * Allows control of a {@link ReadableStream | readable stream}'s state and internal queue. + * + * @public + */ +export declare class ReadableStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is + * over-full. An underlying source ought to use this information to determine when and how to apply backpressure. + */ + get desiredSize(): number | null; + /** + * Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from + * the stream, but once those are read, the stream will become closed. + */ + close(): void; + /** + * Enqueues the given chunk `chunk` in the controlled readable stream. + */ + enqueue(chunk: R): void; + /** + * Errors the controlled readable stream, making all future interactions with it fail with the given error `e`. + */ + error(e?: any): void; +} + +/** + * A default reader vended by a {@link ReadableStream}. + * + * @public + */ +export declare class ReadableStreamDefaultReader { + constructor(stream: ReadableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, + * or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}. + */ + cancel(reason?: any): Promise; + /** + * Returns a promise that allows access to the next chunk from the stream's internal queue, if available. + * + * If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source. + */ + read(): Promise>; + /** + * Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active. + * If the associated stream is errored when the lock is released, the reader will appear errored in the same way + * from now on; otherwise, the reader will appear closed. + * + * A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by + * the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to + * do so will throw a `TypeError` and leave the reader locked to the stream. + */ + releaseLock(): void; +} + +/** + * A common interface for a `ReadableStreamDefaultReader` implementation. + * + * @public + */ +export declare interface ReadableStreamDefaultReaderLike { + readonly closed: Promise; + cancel(reason?: any): Promise; + read(): Promise>; + releaseLock(): void; +} + +/** + * A result returned by {@link ReadableStreamDefaultReader.read}. + * + * @public + */ +export declare type ReadableStreamDefaultReadResult = { + done: false; + value: T; +} | { + done: true; + value?: undefined; +}; + +/** + * Options for {@link ReadableStream.values | async iterating} a stream. + * + * @public + */ +export declare interface ReadableStreamIteratorOptions { + preventCancel?: boolean; +} + +/** + * A common interface for a `ReadadableStream` implementation. + * + * @public + */ +export declare interface ReadableStreamLike { + readonly locked: boolean; + getReader(): ReadableStreamDefaultReaderLike; +} + +/** + * A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed + * to {@link ReadableStream.pipeThrough}. + * + * @public + */ +export declare interface ReadableWritablePair { + readable: ReadableStream; + writable: WritableStream; +} + +/** + * Options for {@link ReadableStream.pipeTo | piping} a stream. + * + * @public + */ +export declare interface StreamPipeOptions { + /** + * If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors. + */ + preventAbort?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes + * or errors. + */ + preventCancel?: boolean; + /** + * If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes. + */ + preventClose?: boolean; + /** + * Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding + * `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream + * aborted, unless the respective options `preventCancel` or `preventAbort` are set. + */ + signal?: AbortSignal; +} + +/** + * A transformer for constructing a {@link TransformStream}. + * + * @public + */ +export declare interface Transformer { + /** + * A function that is called immediately during creation of the {@link TransformStream}. + */ + start?: TransformerStartCallback; + /** + * A function called when a new chunk originally written to the writable side is ready to be transformed. + */ + transform?: TransformerTransformCallback; + /** + * A function called after all chunks written to the writable side have been transformed by successfully passing + * through {@link Transformer.transform | transform()}, and the writable side is about to be closed. + */ + flush?: TransformerFlushCallback; + /** + * A function called when the readable side is cancelled, or when the writable side is aborted. + */ + cancel?: TransformerCancelCallback; + readableType?: undefined; + writableType?: undefined; +} + +/** @public */ +export declare type TransformerCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type TransformerFlushCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerStartCallback = (controller: TransformStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type TransformerTransformCallback = (chunk: I, controller: TransformStreamDefaultController) => void | PromiseLike; + +/** + * A transform stream consists of a pair of streams: a {@link WritableStream | writable stream}, + * known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side. + * In a manner specific to the transform stream in question, writes to the writable side result in new data being + * made available for reading from the readable side. + * + * @public + */ +export declare class TransformStream { + constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); + /** + * The readable side of the transform stream. + */ + get readable(): ReadableStream; + /** + * The writable side of the transform stream. + */ + get writable(): WritableStream; +} + +/** + * Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}. + * + * @public + */ +export declare class TransformStreamDefaultController { + private constructor(); + /** + * Returns the desired size to fill the readable side’s internal queue. It can be negative, if the queue is over-full. + */ + get desiredSize(): number | null; + /** + * Enqueues the given chunk `chunk` in the readable side of the controlled transform stream. + */ + enqueue(chunk: O): void; + /** + * Errors both the readable side and the writable side of the controlled transform stream, making all future + * interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded. + */ + error(reason?: any): void; + /** + * Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the + * transformer only needs to consume a portion of the chunks written to the writable side. + */ + terminate(): void; +} + +/** + * An underlying byte source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingByteSource { + /** + * {@inheritDoc UnderlyingSource.start} + */ + start?: UnderlyingByteSourceStartCallback; + /** + * {@inheritDoc UnderlyingSource.pull} + */ + pull?: UnderlyingByteSourcePullCallback; + /** + * {@inheritDoc UnderlyingSource.cancel} + */ + cancel?: UnderlyingSourceCancelCallback; + /** + * Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream. + * This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its + * {@link ReadableStream.(getReader:1) | getReader()} method. + * It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()} + * and {@link UnderlyingByteSource.pull | pull()} methods. + */ + type: 'bytes'; + /** + * Can be set to a positive integer to cause the implementation to automatically allocate buffers for the + * underlying source code to write into. In this case, when a consumer is using a default reader, the stream + * implementation will automatically allocate an ArrayBuffer of the given size, so that + * {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present, + * as if the consumer was using a BYOB reader. + */ + autoAllocateChunkSize?: number; +} + +/** @public */ +export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike; + +/** + * An underlying sink for constructing a {@link WritableStream}. + * + * @public + */ +export declare interface UnderlyingSink { + /** + * A function that is called immediately during creation of the {@link WritableStream}. + */ + start?: UnderlyingSinkStartCallback; + /** + * A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream + * implementation guarantees that this function will be called only after previous writes have succeeded, and never + * before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or + * {@link UnderlyingSink.abort | abort()} have been called. + * + * This function is used to actually send the data to the resource presented by the underlying sink, for example by + * calling a lower-level API. + */ + write?: UnderlyingSinkWriteCallback; + /** + * A function that is called after the producer signals, via + * {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and + * subsequently all queued-up writes have successfully completed. + * + * This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release + * access to any held resources. + */ + close?: UnderlyingSinkCloseCallback; + /** + * A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or + * {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its + * argument the same value as was passed to those methods by the producer. + * + * Writable streams can additionally be aborted under certain conditions during piping; see the definition of the + * {@link ReadableStream.pipeTo | pipeTo()} method for more details. + * + * This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with + * some custom handling. + */ + abort?: UnderlyingSinkAbortCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSinkWriteCallback = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike; + +/** + * An underlying source for constructing a {@link ReadableStream}. + * + * @public + */ +export declare interface UnderlyingSource { + /** + * A function that is called immediately during creation of the {@link ReadableStream}. + */ + start?: UnderlyingSourceStartCallback; + /** + * A function that is called whenever the stream’s internal queue of chunks becomes not full, + * i.e. whenever the queue’s desired size becomes positive. Generally, it will be called repeatedly + * until the queue reaches its high water mark (i.e. until the desired size becomes non-positive). + */ + pull?: UnderlyingSourcePullCallback; + /** + * A function that is called whenever the consumer cancels the stream, via + * {@link ReadableStream.cancel | stream.cancel()}, + * {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or + * {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}. + * It takes as its argument the same value as was passed to those methods by the consumer. + */ + cancel?: UnderlyingSourceCancelCallback; + type?: undefined; +} + +/** @public */ +export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourcePullCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** @public */ +export declare type UnderlyingSourceStartCallback = (controller: ReadableStreamDefaultController) => void | PromiseLike; + +/** + * A writable stream represents a destination for data, into which you can write. + * + * @public + */ +export declare class WritableStream { + constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); + /** + * Returns whether or not the writable stream is locked to a writer. + */ + get locked(): boolean; + /** + * Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be + * immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort + * mechanism of the underlying sink. + * + * The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled + * that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel + * the stream) if the stream is currently locked. + */ + abort(reason?: any): Promise; + /** + * Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its + * close behavior. During this time any further attempts to write will fail (without erroring the stream). + * + * The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream + * successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with + * a `TypeError` (without attempting to cancel the stream) if the stream is currently locked. + */ + close(): Promise; + /** + * Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream + * is locked, no other writer can be acquired until this one is released. + * + * This functionality is especially useful for creating abstractions that desire the ability to write to a stream + * without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at + * the same time, which would cause the resulting written data to be unpredictable and probably useless. + */ + getWriter(): WritableStreamDefaultWriter; +} + +/** + * Allows control of a {@link WritableStream | writable stream}'s state and internal queue. + * + * @public + */ +export declare class WritableStreamDefaultController { + private constructor(); + /** + * The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted. + * + * @deprecated + * This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177. + * Use {@link WritableStreamDefaultController.signal}'s `reason` instead. + */ + get abortReason(): any; + /** + * An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted. + */ + get signal(): AbortSignal; + /** + * Closes the controlled writable stream, making all future interactions with it fail with the given error `e`. + * + * This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying + * sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the + * normal lifecycle of interactions with the underlying sink. + */ + error(e?: any): void; +} + +/** + * A default writer vended by a {@link WritableStream}. + * + * @public + */ +export declare class WritableStreamDefaultWriter { + constructor(stream: WritableStream); + /** + * Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or + * the writer’s lock is released before the stream finishes closing. + */ + get closed(): Promise; + /** + * Returns the desired size to fill the stream’s internal queue. It can be negative, if the queue is over-full. + * A producer can use this information to determine the right amount of data to write. + * + * It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort + * queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when + * the writer’s lock is released. + */ + get desiredSize(): number | null; + /** + * Returns a promise that will be fulfilled when the desired size to fill the stream’s internal queue transitions + * from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips + * back to zero or below, the getter will return a new promise that stays pending until the next transition. + * + * If the stream becomes errored or aborted, or the writer’s lock is released, the returned promise will become + * rejected. + */ + get ready(): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}. + */ + abort(reason?: any): Promise; + /** + * If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}. + */ + close(): Promise; + /** + * Releases the writer’s lock on the corresponding stream. After the lock is released, the writer is no longer active. + * If the associated stream is errored when the lock is released, the writer will appear errored in the same way from + * now on; otherwise, the writer will appear closed. + * + * Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the + * promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled). + * It’s not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents + * other producers from writing in an interleaved manner. + */ + releaseLock(): void; + /** + * Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully, + * and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return + * a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes + * errored before the writing process is initiated. + * + * Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been + * accepted, and not necessarily that it is safely saved to its ultimate destination. + */ + write(chunk: W): Promise; +} + +export { } diff --git a/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json b/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json new file mode 100644 index 0000000..b18fd2a --- /dev/null +++ b/node_modules/web-streams-polyfill/dist/types/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "7.39.1" + } + ] +} diff --git a/node_modules/web-streams-polyfill/es2018/package.json b/node_modules/web-streams-polyfill/es2018/package.json new file mode 100644 index 0000000..97f8fb1 --- /dev/null +++ b/node_modules/web-streams-polyfill/es2018/package.json @@ -0,0 +1,14 @@ +{ + "name": "web-streams-polyfill-es2018", + "main": "../dist/polyfill.es2018", + "browser": "../dist/polyfill.es2018.min.js", + "module": "../dist/polyfill.es2018.mjs", + "types": "../dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/node_modules/web-streams-polyfill/es6/package.json b/node_modules/web-streams-polyfill/es6/package.json new file mode 100644 index 0000000..ca3909b --- /dev/null +++ b/node_modules/web-streams-polyfill/es6/package.json @@ -0,0 +1,14 @@ +{ + "name": "web-streams-polyfill-es6", + "main": "../dist/polyfill.es6", + "browser": "../dist/polyfill.es6.min.js", + "module": "../dist/polyfill.es6.mjs", + "types": "../dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/node_modules/web-streams-polyfill/package.json b/node_modules/web-streams-polyfill/package.json new file mode 100644 index 0000000..44e2aa7 --- /dev/null +++ b/node_modules/web-streams-polyfill/package.json @@ -0,0 +1,83 @@ +{ + "name": "web-streams-polyfill", + "version": "3.3.2", + "description": "Web Streams, based on the WHATWG spec reference implementation", + "main": "dist/polyfill", + "browser": "dist/polyfill.min.js", + "module": "dist/polyfill.mjs", + "types": "dist/types/polyfill.d.ts", + "typesVersions": { + ">=3.6": { + "dist/types/*": [ + "dist/types/ts3.6/*" + ] + } + }, + "scripts": { + "test": "npm run test:types && npm run test:unit && npm run test:wpt", + "test:wpt": "npm run test:wpt:node && npm run test:wpt:chromium && npm run test:wpt:firefox", + "test:wpt:node": "node --expose_gc ./test/wpt/node/run.js", + "test:wpt:chromium": "node ./test/wpt/browser/run.js --browser chromium", + "test:wpt:firefox": "node ./test/wpt/browser/run.js --browser firefox", + "test:types": "tsc -p ./test/types/tsconfig.json", + "test:unit": "jasmine --config=test/unit/jasmine.json", + "lint": "eslint \"src/**/*.ts\"", + "build": "npm run build:bundle && npm run build:types", + "build:bundle": "rollup -c", + "build:types": "tsc --project . --emitDeclarationOnly --declarationDir ./lib && api-extractor run", + "accept:types": "npm run build:types -- --local", + "postbuild:types": "downlevel-dts ./dist/types/ts3.6/ ./dist/types/ --to=3.5 && node ./build/downlevel-dts.js", + "prepare": "npm run build" + }, + "files": [ + "dist", + "es6", + "es2018", + "ponyfill" + ], + "engines": { + "node": ">= 8" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/MattiasBuelens/web-streams-polyfill.git" + }, + "keywords": [ + "streams", + "whatwg", + "polyfill" + ], + "author": "Mattias Buelens ", + "contributors": [ + "Diwank Singh " + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/MattiasBuelens/web-streams-polyfill/issues" + }, + "homepage": "https://github.com/MattiasBuelens/web-streams-polyfill#readme", + "devDependencies": { + "@microsoft/api-extractor": "^7.39.1", + "@rollup/plugin-inject": "^5.0.5", + "@rollup/plugin-replace": "^5.0.5", + "@rollup/plugin-strip": "^3.0.4", + "@rollup/plugin-terser": "^0.4.4", + "@rollup/plugin-typescript": "^11.1.5", + "@types/node": "^18.19.4", + "@typescript-eslint/eslint-plugin": "^6.17.0", + "@typescript-eslint/parser": "^6.17.0", + "@ungap/promise-all-settled": "^1.1.2", + "downlevel-dts": "^0.11.0", + "eslint": "^8.56.0", + "jasmine": "^5.1.0", + "micromatch": "^4.0.5", + "minimist": "^1.2.5", + "playwright": "^1.14.1", + "recursive-readdir": "^2.2.2", + "rollup": "^4.9.2", + "ts-morph": "^10.0.2", + "tslib": "^2.6.2", + "typescript": "^5.3.3", + "wpt-runner": "^5.0.0" + } +} diff --git a/node_modules/web-streams-polyfill/ponyfill/es2018/package.json b/node_modules/web-streams-polyfill/ponyfill/es2018/package.json new file mode 100644 index 0000000..26816ac --- /dev/null +++ b/node_modules/web-streams-polyfill/ponyfill/es2018/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill-es2018", + "main": "../../dist/ponyfill.es2018", + "module": "../../dist/ponyfill.es2018.mjs", + "types": "../../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../../dist/types/*": [ + "../../dist/types/ts3.6/*" + ] + } + } +} diff --git a/node_modules/web-streams-polyfill/ponyfill/es6/package.json b/node_modules/web-streams-polyfill/ponyfill/es6/package.json new file mode 100644 index 0000000..b54520d --- /dev/null +++ b/node_modules/web-streams-polyfill/ponyfill/es6/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill-es6", + "main": "../../dist/ponyfill.es6", + "module": "../../dist/ponyfill.es6.mjs", + "types": "../../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../../dist/types/*": [ + "../../dist/types/ts3.6/*" + ] + } + } +} diff --git a/node_modules/web-streams-polyfill/ponyfill/package.json b/node_modules/web-streams-polyfill/ponyfill/package.json new file mode 100644 index 0000000..36e9fbe --- /dev/null +++ b/node_modules/web-streams-polyfill/ponyfill/package.json @@ -0,0 +1,13 @@ +{ + "name": "web-streams-ponyfill", + "main": "../dist/ponyfill", + "module": "../dist/ponyfill.mjs", + "types": "../dist/types/ponyfill.d.ts", + "typesVersions": { + ">=3.6": { + "../dist/types/*": [ + "../dist/types/ts3.6/*" + ] + } + } +} diff --git a/node_modules/webidl-conversions/LICENSE.md b/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 0000000..d4a994f --- /dev/null +++ b/node_modules/webidl-conversions/LICENSE.md @@ -0,0 +1,12 @@ +# The BSD 2-Clause License + +Copyright (c) 2014, Domenic Denicola +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. 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/webidl-conversions/README.md b/node_modules/webidl-conversions/README.md new file mode 100644 index 0000000..3657890 --- /dev/null +++ b/node_modules/webidl-conversions/README.md @@ -0,0 +1,53 @@ +# WebIDL Type Conversions on JavaScript Values + +This package implements, in JavaScript, the algorithms to convert a given JavaScript value according to a given [WebIDL](http://heycam.github.io/webidl/) [type](http://heycam.github.io/webidl/#idl-types). + +The goal is that you should be able to write code like + +```js +const conversions = require("webidl-conversions"); + +function doStuff(x, y) { + x = conversions["boolean"](x); + y = conversions["unsigned long"](y); + // actual algorithm code here +} +``` + +and your function `doStuff` will behave the same as a WebIDL operation declared as + +```webidl +void doStuff(boolean x, unsigned long y); +``` + +## API + +This package's main module's default export is an object with a variety of methods, each corresponding to a different WebIDL type. Each method, when invoked on a JavaScript value, will give back the new JavaScript value that results after passing through the WebIDL conversion rules. (See below for more details on what that means.) Alternately, the method could throw an error, if the WebIDL algorithm is specified to do so: for example `conversions["float"](NaN)` [will throw a `TypeError`](http://heycam.github.io/webidl/#es-float). + +## Status + +All of the numeric types are implemented (float being implemented as double) and some others are as well - check the source for all of them. This list will grow over time in service of the [HTML as Custom Elements](https://github.com/dglazkov/html-as-custom-elements) project, but in the meantime, pull requests welcome! + +I'm not sure yet what the strategy will be for modifiers, e.g. [`[Clamp]`](http://heycam.github.io/webidl/#Clamp). Maybe something like `conversions["unsigned long"](x, { clamp: true })`? We'll see. + +We might also want to extend the API to give better error messages, e.g. "Argument 1 of HTMLMediaElement.fastSeek is not a finite floating-point value" instead of "Argument is not a finite floating-point value." This would require passing in more information to the conversion functions than we currently do. + +## Background + +What's actually going on here, conceptually, is pretty weird. Let's try to explain. + +WebIDL, as part of its madness-inducing design, has its own type system. When people write algorithms in web platform specs, they usually operate on WebIDL values, i.e. instances of WebIDL types. For example, if they were specifying the algorithm for our `doStuff` operation above, they would treat `x` as a WebIDL value of [WebIDL type `boolean`](http://heycam.github.io/webidl/#idl-boolean). Crucially, they would _not_ treat `x` as a JavaScript variable whose value is either the JavaScript `true` or `false`. They're instead working in a different type system altogether, with its own rules. + +Separately from its type system, WebIDL defines a ["binding"](http://heycam.github.io/webidl/#ecmascript-binding) of the type system into JavaScript. This contains rules like: when you pass a JavaScript value to the JavaScript method that manifests a given WebIDL operation, how does that get converted into a WebIDL value? For example, a JavaScript `true` passed in the position of a WebIDL `boolean` argument becomes a WebIDL `true`. But, a JavaScript `true` passed in the position of a [WebIDL `unsigned long`](http://heycam.github.io/webidl/#idl-unsigned-long) becomes a WebIDL `1`. And so on. + +Finally, we have the actual implementation code. This is usually C++, although these days [some smart people are using Rust](https://github.com/servo/servo). The implementation, of course, has its own type system. So when they implement the WebIDL algorithms, they don't actually use WebIDL values, since those aren't "real" outside of specs. Instead, implementations apply the WebIDL binding rules in such a way as to convert incoming JavaScript values into C++ values. For example, if code in the browser called `doStuff(true, true)`, then the implementation code would eventually receive a C++ `bool` containing `true` and a C++ `uint32_t` containing `1`. + +The upside of all this is that implementations can abstract all the conversion logic away, letting WebIDL handle it, and focus on implementing the relevant methods in C++ with values of the correct type already provided. That is payoff of WebIDL, in a nutshell. + +And getting to that payoff is the goal of _this_ project—but for JavaScript implementations, instead of C++ ones. That is, this library is designed to make it easier for JavaScript developers to write functions that behave like a given WebIDL operation. So conceptually, the conversion pipeline, which in its general form is JavaScript values ↦ WebIDL values ↦ implementation-language values, in this case becomes JavaScript values ↦ WebIDL values ↦ JavaScript values. And that intermediate step is where all the logic is performed: a JavaScript `true` becomes a WebIDL `1` in an unsigned long context, which then becomes a JavaScript `1`. + +## Don't Use This + +Seriously, why would you ever use this? You really shouldn't. WebIDL is … not great, and you shouldn't be emulating its semantics. If you're looking for a generic argument-processing library, you should find one with better rules than those from WebIDL. In general, your JavaScript should not be trying to become more like WebIDL; if anything, we should fix WebIDL to make it more like JavaScript. + +The _only_ people who should use this are those trying to create faithful implementations (or polyfills) of web platform interfaces defined in WebIDL. diff --git a/node_modules/webidl-conversions/lib/index.js b/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 0000000..c5153a3 --- /dev/null +++ b/node_modules/webidl-conversions/lib/index.js @@ -0,0 +1,189 @@ +"use strict"; + +var conversions = {}; +module.exports = conversions; + +function sign(x) { + return x < 0 ? -1 : 1; +} + +function evenRound(x) { + // Round x to the nearest integer, choosing the even integer if it lies halfway between two. + if ((x % 1) === 0.5 && (x & 1) === 0) { // [even number].5; round down (i.e. floor) + return Math.floor(x); + } else { + return Math.round(x); + } +} + +function createNumberConversion(bitLength, typeOpts) { + if (!typeOpts.unsigned) { + --bitLength; + } + const lowerBound = typeOpts.unsigned ? 0 : -Math.pow(2, bitLength); + const upperBound = Math.pow(2, bitLength) - 1; + + const moduloVal = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength) : Math.pow(2, bitLength); + const moduloBound = typeOpts.moduloBitLength ? Math.pow(2, typeOpts.moduloBitLength - 1) : Math.pow(2, bitLength - 1); + + return function(V, opts) { + if (!opts) opts = {}; + + let x = +V; + + if (opts.enforceRange) { + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite number"); + } + + x = sign(x) * Math.floor(Math.abs(x)); + if (x < lowerBound || x > upperBound) { + throw new TypeError("Argument is not in byte range"); + } + + return x; + } + + if (!isNaN(x) && opts.clamp) { + x = evenRound(x); + + if (x < lowerBound) x = lowerBound; + if (x > upperBound) x = upperBound; + return x; + } + + if (!Number.isFinite(x) || x === 0) { + return 0; + } + + x = sign(x) * Math.floor(Math.abs(x)); + x = x % moduloVal; + + if (!typeOpts.unsigned && x >= moduloBound) { + return x - moduloVal; + } else if (typeOpts.unsigned) { + if (x < 0) { + x += moduloVal; + } else if (x === -0) { // don't return negative zero + return 0; + } + } + + return x; + } +} + +conversions["void"] = function () { + return undefined; +}; + +conversions["boolean"] = function (val) { + return !!val; +}; + +conversions["byte"] = createNumberConversion(8, { unsigned: false }); +conversions["octet"] = createNumberConversion(8, { unsigned: true }); + +conversions["short"] = createNumberConversion(16, { unsigned: false }); +conversions["unsigned short"] = createNumberConversion(16, { unsigned: true }); + +conversions["long"] = createNumberConversion(32, { unsigned: false }); +conversions["unsigned long"] = createNumberConversion(32, { unsigned: true }); + +conversions["long long"] = createNumberConversion(32, { unsigned: false, moduloBitLength: 64 }); +conversions["unsigned long long"] = createNumberConversion(32, { unsigned: true, moduloBitLength: 64 }); + +conversions["double"] = function (V) { + const x = +V; + + if (!Number.isFinite(x)) { + throw new TypeError("Argument is not a finite floating-point value"); + } + + return x; +}; + +conversions["unrestricted double"] = function (V) { + const x = +V; + + if (isNaN(x)) { + throw new TypeError("Argument is NaN"); + } + + return x; +}; + +// not quite valid, but good enough for JS +conversions["float"] = conversions["double"]; +conversions["unrestricted float"] = conversions["unrestricted double"]; + +conversions["DOMString"] = function (V, opts) { + if (!opts) opts = {}; + + if (opts.treatNullAsEmptyString && V === null) { + return ""; + } + + return String(V); +}; + +conversions["ByteString"] = function (V, opts) { + const x = String(V); + let c = undefined; + for (let i = 0; (c = x.codePointAt(i)) !== undefined; ++i) { + if (c > 255) { + throw new TypeError("Argument is not a valid bytestring"); + } + } + + return x; +}; + +conversions["USVString"] = function (V) { + const S = String(V); + const n = S.length; + const U = []; + for (let i = 0; i < n; ++i) { + const c = S.charCodeAt(i); + if (c < 0xD800 || c > 0xDFFF) { + U.push(String.fromCodePoint(c)); + } else if (0xDC00 <= c && c <= 0xDFFF) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + if (i === n - 1) { + U.push(String.fromCodePoint(0xFFFD)); + } else { + const d = S.charCodeAt(i + 1); + if (0xDC00 <= d && d <= 0xDFFF) { + const a = c & 0x3FF; + const b = d & 0x3FF; + U.push(String.fromCodePoint((2 << 15) + (2 << 9) * a + b)); + ++i; + } else { + U.push(String.fromCodePoint(0xFFFD)); + } + } + } + } + + return U.join(''); +}; + +conversions["Date"] = function (V, opts) { + if (!(V instanceof Date)) { + throw new TypeError("Argument is not a Date object"); + } + if (isNaN(V)) { + return undefined; + } + + return V; +}; + +conversions["RegExp"] = function (V, opts) { + if (!(V instanceof RegExp)) { + V = new RegExp(V); + } + + return V; +}; diff --git a/node_modules/webidl-conversions/package.json b/node_modules/webidl-conversions/package.json new file mode 100644 index 0000000..c31bc07 --- /dev/null +++ b/node_modules/webidl-conversions/package.json @@ -0,0 +1,23 @@ +{ + "name": "webidl-conversions", + "version": "3.0.1", + "description": "Implements the WebIDL algorithms for converting to and from JavaScript values", + "main": "lib/index.js", + "scripts": { + "test": "mocha test/*.js" + }, + "repository": "jsdom/webidl-conversions", + "keywords": [ + "webidl", + "web", + "types" + ], + "files": [ + "lib/" + ], + "author": "Domenic Denicola (https://domenic.me/)", + "license": "BSD-2-Clause", + "devDependencies": { + "mocha": "^1.21.4" + } +} diff --git a/node_modules/whatwg-url/LICENSE.txt b/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 0000000..54dfac3 --- /dev/null +++ b/node_modules/whatwg-url/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015–2016 Sebastian Mayr + +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/whatwg-url/README.md b/node_modules/whatwg-url/README.md new file mode 100644 index 0000000..4347a7f --- /dev/null +++ b/node_modules/whatwg-url/README.md @@ -0,0 +1,67 @@ +# whatwg-url + +whatwg-url is a full implementation of the WHATWG [URL Standard](https://url.spec.whatwg.org/). It can be used standalone, but it also exposes a lot of the internal algorithms that are useful for integrating a URL parser into a project like [jsdom](https://github.com/tmpvar/jsdom). + +## Current Status + +whatwg-url is currently up to date with the URL spec up to commit [a62223](https://github.com/whatwg/url/commit/a622235308342c9adc7fc2fd1659ff059f7d5e2a). + +## API + +### The `URL` Constructor + +The main API is the [`URL`](https://url.spec.whatwg.org/#url) export, which follows the spec's behavior in all ways (including e.g. `USVString` conversion). Most consumers of this library will want to use this. + +### Low-level URL Standard API + +The following methods are exported for use by places like jsdom that need to implement things like [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils). They operate on or return an "internal URL" or ["URL record"](https://url.spec.whatwg.org/#concept-url) type. + +- [URL parser](https://url.spec.whatwg.org/#concept-url-parser): `parseURL(input, { baseURL, encodingOverride })` +- [Basic URL parser](https://url.spec.whatwg.org/#concept-basic-url-parser): `basicURLParse(input, { baseURL, encodingOverride, url, stateOverride })` +- [URL serializer](https://url.spec.whatwg.org/#concept-url-serializer): `serializeURL(urlRecord, excludeFragment)` +- [Host serializer](https://url.spec.whatwg.org/#concept-host-serializer): `serializeHost(hostFromURLRecord)` +- [Serialize an integer](https://url.spec.whatwg.org/#serialize-an-integer): `serializeInteger(number)` +- [Origin](https://url.spec.whatwg.org/#concept-url-origin) [serializer](https://html.spec.whatwg.org/multipage/browsers.html#serialization-of-an-origin): `serializeURLOrigin(urlRecord)` +- [Set the username](https://url.spec.whatwg.org/#set-the-username): `setTheUsername(urlRecord, usernameString)` +- [Set the password](https://url.spec.whatwg.org/#set-the-password): `setThePassword(urlRecord, passwordString)` +- [Cannot have a username/password/port](https://url.spec.whatwg.org/#cannot-have-a-username-password-port): `cannotHaveAUsernamePasswordPort(urlRecord)` + +The `stateOverride` parameter is one of the following strings: + +- [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state) +- [`"scheme"`](https://url.spec.whatwg.org/#scheme-state) +- [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state) +- [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state) +- [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state) +- [`"relative"`](https://url.spec.whatwg.org/#relative-state) +- [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state) +- [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state) +- [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state) +- [`"authority"`](https://url.spec.whatwg.org/#authority-state) +- [`"host"`](https://url.spec.whatwg.org/#host-state) +- [`"hostname"`](https://url.spec.whatwg.org/#hostname-state) +- [`"port"`](https://url.spec.whatwg.org/#port-state) +- [`"file"`](https://url.spec.whatwg.org/#file-state) +- [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state) +- [`"file host"`](https://url.spec.whatwg.org/#file-host-state) +- [`"path start"`](https://url.spec.whatwg.org/#path-start-state) +- [`"path"`](https://url.spec.whatwg.org/#path-state) +- [`"cannot-be-a-base-URL path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state) +- [`"query"`](https://url.spec.whatwg.org/#query-state) +- [`"fragment"`](https://url.spec.whatwg.org/#fragment-state) + +The URL record type has the following API: + +- [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme) +- [`username`](https://url.spec.whatwg.org/#concept-url-username) +- [`password`](https://url.spec.whatwg.org/#concept-url-password) +- [`host`](https://url.spec.whatwg.org/#concept-url-host) +- [`port`](https://url.spec.whatwg.org/#concept-url-port) +- [`path`](https://url.spec.whatwg.org/#concept-url-path) (as an array) +- [`query`](https://url.spec.whatwg.org/#concept-url-query) +- [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment) +- [`cannotBeABaseURL`](https://url.spec.whatwg.org/#url-cannot-be-a-base-url-flag) (as a boolean) + +These properties should be treated with care, as in general changing them will cause the URL record to be in an inconsistent state until the appropriate invocation of `basicURLParse` is used to fix it up. You can see examples of this in the URL Standard, where there are many step sequences like "4. Set context object’s url’s fragment to the empty string. 5. Basic URL parse _input_ with context object’s url as _url_ and fragment state as _state override_." In between those two steps, a URL record is in an unusable state. + +The return value of "failure" in the spec is represented by the string `"failure"`. That is, functions like `parseURL` and `basicURLParse` can return _either_ a URL record _or_ the string `"failure"`. diff --git a/node_modules/whatwg-url/lib/URL-impl.js b/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 0000000..dc7452c --- /dev/null +++ b/node_modules/whatwg-url/lib/URL-impl.js @@ -0,0 +1,200 @@ +"use strict"; +const usm = require("./url-state-machine"); + +exports.implementation = class URLImpl { + constructor(constructorArgs) { + const url = constructorArgs[0]; + const base = constructorArgs[1]; + + let parsedBase = null; + if (base !== undefined) { + parsedBase = usm.basicURLParse(base); + if (parsedBase === "failure") { + throw new TypeError("Invalid base URL"); + } + } + + const parsedURL = usm.basicURLParse(url, { baseURL: parsedBase }); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + + // TODO: query stuff + } + + get href() { + return usm.serializeURL(this._url); + } + + set href(v) { + const parsedURL = usm.basicURLParse(v); + if (parsedURL === "failure") { + throw new TypeError("Invalid URL"); + } + + this._url = parsedURL; + } + + get origin() { + return usm.serializeURLOrigin(this._url); + } + + get protocol() { + return this._url.scheme + ":"; + } + + set protocol(v) { + usm.basicURLParse(v + ":", { url: this._url, stateOverride: "scheme start" }); + } + + get username() { + return this._url.username; + } + + set username(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setTheUsername(this._url, v); + } + + get password() { + return this._url.password; + } + + set password(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + usm.setThePassword(this._url, v); + } + + get host() { + const url = this._url; + + if (url.host === null) { + return ""; + } + + if (url.port === null) { + return usm.serializeHost(url.host); + } + + return usm.serializeHost(url.host) + ":" + usm.serializeInteger(url.port); + } + + set host(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "host" }); + } + + get hostname() { + if (this._url.host === null) { + return ""; + } + + return usm.serializeHost(this._url.host); + } + + set hostname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + usm.basicURLParse(v, { url: this._url, stateOverride: "hostname" }); + } + + get port() { + if (this._url.port === null) { + return ""; + } + + return usm.serializeInteger(this._url.port); + } + + set port(v) { + if (usm.cannotHaveAUsernamePasswordPort(this._url)) { + return; + } + + if (v === "") { + this._url.port = null; + } else { + usm.basicURLParse(v, { url: this._url, stateOverride: "port" }); + } + } + + get pathname() { + if (this._url.cannotBeABaseURL) { + return this._url.path[0]; + } + + if (this._url.path.length === 0) { + return ""; + } + + return "/" + this._url.path.join("/"); + } + + set pathname(v) { + if (this._url.cannotBeABaseURL) { + return; + } + + this._url.path = []; + usm.basicURLParse(v, { url: this._url, stateOverride: "path start" }); + } + + get search() { + if (this._url.query === null || this._url.query === "") { + return ""; + } + + return "?" + this._url.query; + } + + set search(v) { + // TODO: query stuff + + const url = this._url; + + if (v === "") { + url.query = null; + return; + } + + const input = v[0] === "?" ? v.substring(1) : v; + url.query = ""; + usm.basicURLParse(input, { url, stateOverride: "query" }); + } + + get hash() { + if (this._url.fragment === null || this._url.fragment === "") { + return ""; + } + + return "#" + this._url.fragment; + } + + set hash(v) { + if (v === "") { + this._url.fragment = null; + return; + } + + const input = v[0] === "#" ? v.substring(1) : v; + this._url.fragment = ""; + usm.basicURLParse(input, { url: this._url, stateOverride: "fragment" }); + } + + toJSON() { + return this.href; + } +}; diff --git a/node_modules/whatwg-url/lib/URL.js b/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 0000000..78c7207 --- /dev/null +++ b/node_modules/whatwg-url/lib/URL.js @@ -0,0 +1,196 @@ +"use strict"; + +const conversions = require("webidl-conversions"); +const utils = require("./utils.js"); +const Impl = require(".//URL-impl.js"); + +const impl = utils.implSymbol; + +function URL(url) { + if (!this || this[impl] || !(this instanceof URL)) { + throw new TypeError("Failed to construct 'URL': Please use the 'new' operator, this DOM object constructor cannot be called as a function."); + } + if (arguments.length < 1) { + throw new TypeError("Failed to construct 'URL': 1 argument required, but only " + arguments.length + " present."); + } + const args = []; + for (let i = 0; i < arguments.length && i < 2; ++i) { + args[i] = arguments[i]; + } + args[0] = conversions["USVString"](args[0]); + if (args[1] !== undefined) { + args[1] = conversions["USVString"](args[1]); + } + + module.exports.setup(this, args); +} + +URL.prototype.toJSON = function toJSON() { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + const args = []; + for (let i = 0; i < arguments.length && i < 0; ++i) { + args[i] = arguments[i]; + } + return this[impl].toJSON.apply(this[impl], args); +}; +Object.defineProperty(URL.prototype, "href", { + get() { + return this[impl].href; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].href = V; + }, + enumerable: true, + configurable: true +}); + +URL.prototype.toString = function () { + if (!this || !module.exports.is(this)) { + throw new TypeError("Illegal invocation"); + } + return this.href; +}; + +Object.defineProperty(URL.prototype, "origin", { + get() { + return this[impl].origin; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "protocol", { + get() { + return this[impl].protocol; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].protocol = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "username", { + get() { + return this[impl].username; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].username = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "password", { + get() { + return this[impl].password; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].password = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "host", { + get() { + return this[impl].host; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].host = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hostname", { + get() { + return this[impl].hostname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hostname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "port", { + get() { + return this[impl].port; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].port = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "pathname", { + get() { + return this[impl].pathname; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].pathname = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "search", { + get() { + return this[impl].search; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].search = V; + }, + enumerable: true, + configurable: true +}); + +Object.defineProperty(URL.prototype, "hash", { + get() { + return this[impl].hash; + }, + set(V) { + V = conversions["USVString"](V); + this[impl].hash = V; + }, + enumerable: true, + configurable: true +}); + + +module.exports = { + is(obj) { + return !!obj && obj[impl] instanceof Impl.implementation; + }, + create(constructorArgs, privateData) { + let obj = Object.create(URL.prototype); + this.setup(obj, constructorArgs, privateData); + return obj; + }, + setup(obj, constructorArgs, privateData) { + if (!privateData) privateData = {}; + privateData.wrapper = obj; + + obj[impl] = new Impl.implementation(constructorArgs, privateData); + obj[impl][utils.wrapperSymbol] = obj; + }, + interface: URL, + expose: { + Window: { URL: URL }, + Worker: { URL: URL } + } +}; + diff --git a/node_modules/whatwg-url/lib/public-api.js b/node_modules/whatwg-url/lib/public-api.js new file mode 100644 index 0000000..932dcad --- /dev/null +++ b/node_modules/whatwg-url/lib/public-api.js @@ -0,0 +1,11 @@ +"use strict"; + +exports.URL = require("./URL").interface; +exports.serializeURL = require("./url-state-machine").serializeURL; +exports.serializeURLOrigin = require("./url-state-machine").serializeURLOrigin; +exports.basicURLParse = require("./url-state-machine").basicURLParse; +exports.setTheUsername = require("./url-state-machine").setTheUsername; +exports.setThePassword = require("./url-state-machine").setThePassword; +exports.serializeHost = require("./url-state-machine").serializeHost; +exports.serializeInteger = require("./url-state-machine").serializeInteger; +exports.parseURL = require("./url-state-machine").parseURL; diff --git a/node_modules/whatwg-url/lib/url-state-machine.js b/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 0000000..27d977a --- /dev/null +++ b/node_modules/whatwg-url/lib/url-state-machine.js @@ -0,0 +1,1297 @@ +"use strict"; +const punycode = require("punycode"); +const tr46 = require("tr46"); + +const specialSchemes = { + ftp: 21, + file: null, + gopher: 70, + http: 80, + https: 443, + ws: 80, + wss: 443 +}; + +const failure = Symbol("failure"); + +function countSymbols(str) { + return punycode.ucs2.decode(str).length; +} + +function at(input, idx) { + const c = input[idx]; + return isNaN(c) ? undefined : String.fromCodePoint(c); +} + +function isASCIIDigit(c) { + return c >= 0x30 && c <= 0x39; +} + +function isASCIIAlpha(c) { + return (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A); +} + +function isASCIIAlphanumeric(c) { + return isASCIIAlpha(c) || isASCIIDigit(c); +} + +function isASCIIHex(c) { + return isASCIIDigit(c) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66); +} + +function isSingleDot(buffer) { + return buffer === "." || buffer.toLowerCase() === "%2e"; +} + +function isDoubleDot(buffer) { + buffer = buffer.toLowerCase(); + return buffer === ".." || buffer === "%2e." || buffer === ".%2e" || buffer === "%2e%2e"; +} + +function isWindowsDriveLetterCodePoints(cp1, cp2) { + return isASCIIAlpha(cp1) && (cp2 === 58 || cp2 === 124); +} + +function isWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && (string[1] === ":" || string[1] === "|"); +} + +function isNormalizedWindowsDriveLetterString(string) { + return string.length === 2 && isASCIIAlpha(string.codePointAt(0)) && string[1] === ":"; +} + +function containsForbiddenHostCodePoint(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|%|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function containsForbiddenHostCodePointExcludingPercent(string) { + return string.search(/\u0000|\u0009|\u000A|\u000D|\u0020|#|\/|:|\?|@|\[|\\|\]/) !== -1; +} + +function isSpecialScheme(scheme) { + return specialSchemes[scheme] !== undefined; +} + +function isSpecial(url) { + return isSpecialScheme(url.scheme); +} + +function defaultPort(scheme) { + return specialSchemes[scheme]; +} + +function percentEncode(c) { + let hex = c.toString(16).toUpperCase(); + if (hex.length === 1) { + hex = "0" + hex; + } + + return "%" + hex; +} + +function utf8PercentEncode(c) { + const buf = new Buffer(c); + + let str = ""; + + for (let i = 0; i < buf.length; ++i) { + str += percentEncode(buf[i]); + } + + return str; +} + +function utf8PercentDecode(str) { + const input = new Buffer(str); + const output = []; + for (let i = 0; i < input.length; ++i) { + if (input[i] !== 37) { + output.push(input[i]); + } else if (input[i] === 37 && isASCIIHex(input[i + 1]) && isASCIIHex(input[i + 2])) { + output.push(parseInt(input.slice(i + 1, i + 3).toString(), 16)); + i += 2; + } else { + output.push(input[i]); + } + } + return new Buffer(output).toString(); +} + +function isC0ControlPercentEncode(c) { + return c <= 0x1F || c > 0x7E; +} + +const extraPathPercentEncodeSet = new Set([32, 34, 35, 60, 62, 63, 96, 123, 125]); +function isPathPercentEncode(c) { + return isC0ControlPercentEncode(c) || extraPathPercentEncodeSet.has(c); +} + +const extraUserinfoPercentEncodeSet = + new Set([47, 58, 59, 61, 64, 91, 92, 93, 94, 124]); +function isUserinfoPercentEncode(c) { + return isPathPercentEncode(c) || extraUserinfoPercentEncodeSet.has(c); +} + +function percentEncodeChar(c, encodeSetPredicate) { + const cStr = String.fromCodePoint(c); + + if (encodeSetPredicate(c)) { + return utf8PercentEncode(cStr); + } + + return cStr; +} + +function parseIPv4Number(input) { + let R = 10; + + if (input.length >= 2 && input.charAt(0) === "0" && input.charAt(1).toLowerCase() === "x") { + input = input.substring(2); + R = 16; + } else if (input.length >= 2 && input.charAt(0) === "0") { + input = input.substring(1); + R = 8; + } + + if (input === "") { + return 0; + } + + const regex = R === 10 ? /[^0-9]/ : (R === 16 ? /[^0-9A-Fa-f]/ : /[^0-7]/); + if (regex.test(input)) { + return failure; + } + + return parseInt(input, R); +} + +function parseIPv4(input) { + const parts = input.split("."); + if (parts[parts.length - 1] === "") { + if (parts.length > 1) { + parts.pop(); + } + } + + if (parts.length > 4) { + return input; + } + + const numbers = []; + for (const part of parts) { + if (part === "") { + return input; + } + const n = parseIPv4Number(part); + if (n === failure) { + return input; + } + + numbers.push(n); + } + + for (let i = 0; i < numbers.length - 1; ++i) { + if (numbers[i] > 255) { + return failure; + } + } + if (numbers[numbers.length - 1] >= Math.pow(256, 5 - numbers.length)) { + return failure; + } + + let ipv4 = numbers.pop(); + let counter = 0; + + for (const n of numbers) { + ipv4 += n * Math.pow(256, 3 - counter); + ++counter; + } + + return ipv4; +} + +function serializeIPv4(address) { + let output = ""; + let n = address; + + for (let i = 1; i <= 4; ++i) { + output = String(n % 256) + output; + if (i !== 4) { + output = "." + output; + } + n = Math.floor(n / 256); + } + + return output; +} + +function parseIPv6(input) { + const address = [0, 0, 0, 0, 0, 0, 0, 0]; + let pieceIndex = 0; + let compress = null; + let pointer = 0; + + input = punycode.ucs2.decode(input); + + if (input[pointer] === 58) { + if (input[pointer + 1] !== 58) { + return failure; + } + + pointer += 2; + ++pieceIndex; + compress = pieceIndex; + } + + while (pointer < input.length) { + if (pieceIndex === 8) { + return failure; + } + + if (input[pointer] === 58) { + if (compress !== null) { + return failure; + } + ++pointer; + ++pieceIndex; + compress = pieceIndex; + continue; + } + + let value = 0; + let length = 0; + + while (length < 4 && isASCIIHex(input[pointer])) { + value = value * 0x10 + parseInt(at(input, pointer), 16); + ++pointer; + ++length; + } + + if (input[pointer] === 46) { + if (length === 0) { + return failure; + } + + pointer -= length; + + if (pieceIndex > 6) { + return failure; + } + + let numbersSeen = 0; + + while (input[pointer] !== undefined) { + let ipv4Piece = null; + + if (numbersSeen > 0) { + if (input[pointer] === 46 && numbersSeen < 4) { + ++pointer; + } else { + return failure; + } + } + + if (!isASCIIDigit(input[pointer])) { + return failure; + } + + while (isASCIIDigit(input[pointer])) { + const number = parseInt(at(input, pointer)); + if (ipv4Piece === null) { + ipv4Piece = number; + } else if (ipv4Piece === 0) { + return failure; + } else { + ipv4Piece = ipv4Piece * 10 + number; + } + if (ipv4Piece > 255) { + return failure; + } + ++pointer; + } + + address[pieceIndex] = address[pieceIndex] * 0x100 + ipv4Piece; + + ++numbersSeen; + + if (numbersSeen === 2 || numbersSeen === 4) { + ++pieceIndex; + } + } + + if (numbersSeen !== 4) { + return failure; + } + + break; + } else if (input[pointer] === 58) { + ++pointer; + if (input[pointer] === undefined) { + return failure; + } + } else if (input[pointer] !== undefined) { + return failure; + } + + address[pieceIndex] = value; + ++pieceIndex; + } + + if (compress !== null) { + let swaps = pieceIndex - compress; + pieceIndex = 7; + while (pieceIndex !== 0 && swaps > 0) { + const temp = address[compress + swaps - 1]; + address[compress + swaps - 1] = address[pieceIndex]; + address[pieceIndex] = temp; + --pieceIndex; + --swaps; + } + } else if (compress === null && pieceIndex !== 8) { + return failure; + } + + return address; +} + +function serializeIPv6(address) { + let output = ""; + const seqResult = findLongestZeroSequence(address); + const compress = seqResult.idx; + let ignore0 = false; + + for (let pieceIndex = 0; pieceIndex <= 7; ++pieceIndex) { + if (ignore0 && address[pieceIndex] === 0) { + continue; + } else if (ignore0) { + ignore0 = false; + } + + if (compress === pieceIndex) { + const separator = pieceIndex === 0 ? "::" : ":"; + output += separator; + ignore0 = true; + continue; + } + + output += address[pieceIndex].toString(16); + + if (pieceIndex !== 7) { + output += ":"; + } + } + + return output; +} + +function parseHost(input, isSpecialArg) { + if (input[0] === "[") { + if (input[input.length - 1] !== "]") { + return failure; + } + + return parseIPv6(input.substring(1, input.length - 1)); + } + + if (!isSpecialArg) { + return parseOpaqueHost(input); + } + + const domain = utf8PercentDecode(input); + const asciiDomain = tr46.toASCII(domain, false, tr46.PROCESSING_OPTIONS.NONTRANSITIONAL, false); + if (asciiDomain === null) { + return failure; + } + + if (containsForbiddenHostCodePoint(asciiDomain)) { + return failure; + } + + const ipv4Host = parseIPv4(asciiDomain); + if (typeof ipv4Host === "number" || ipv4Host === failure) { + return ipv4Host; + } + + return asciiDomain; +} + +function parseOpaqueHost(input) { + if (containsForbiddenHostCodePointExcludingPercent(input)) { + return failure; + } + + let output = ""; + const decoded = punycode.ucs2.decode(input); + for (let i = 0; i < decoded.length; ++i) { + output += percentEncodeChar(decoded[i], isC0ControlPercentEncode); + } + return output; +} + +function findLongestZeroSequence(arr) { + let maxIdx = null; + let maxLen = 1; // only find elements > 1 + let currStart = null; + let currLen = 0; + + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== 0) { + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + currStart = null; + currLen = 0; + } else { + if (currStart === null) { + currStart = i; + } + ++currLen; + } + } + + // if trailing zeros + if (currLen > maxLen) { + maxIdx = currStart; + maxLen = currLen; + } + + return { + idx: maxIdx, + len: maxLen + }; +} + +function serializeHost(host) { + if (typeof host === "number") { + return serializeIPv4(host); + } + + // IPv6 serializer + if (host instanceof Array) { + return "[" + serializeIPv6(host) + "]"; + } + + return host; +} + +function trimControlChars(url) { + return url.replace(/^[\u0000-\u001F\u0020]+|[\u0000-\u001F\u0020]+$/g, ""); +} + +function trimTabAndNewline(url) { + return url.replace(/\u0009|\u000A|\u000D/g, ""); +} + +function shortenPath(url) { + const path = url.path; + if (path.length === 0) { + return; + } + if (url.scheme === "file" && path.length === 1 && isNormalizedWindowsDriveLetter(path[0])) { + return; + } + + path.pop(); +} + +function includesCredentials(url) { + return url.username !== "" || url.password !== ""; +} + +function cannotHaveAUsernamePasswordPort(url) { + return url.host === null || url.host === "" || url.cannotBeABaseURL || url.scheme === "file"; +} + +function isNormalizedWindowsDriveLetter(string) { + return /^[A-Za-z]:$/.test(string); +} + +function URLStateMachine(input, base, encodingOverride, url, stateOverride) { + this.pointer = 0; + this.input = input; + this.base = base || null; + this.encodingOverride = encodingOverride || "utf-8"; + this.stateOverride = stateOverride; + this.url = url; + this.failure = false; + this.parseError = false; + + if (!this.url) { + this.url = { + scheme: "", + username: "", + password: "", + host: null, + port: null, + path: [], + query: null, + fragment: null, + + cannotBeABaseURL: false + }; + + const res = trimControlChars(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + } + + const res = trimTabAndNewline(this.input); + if (res !== this.input) { + this.parseError = true; + } + this.input = res; + + this.state = stateOverride || "scheme start"; + + this.buffer = ""; + this.atFlag = false; + this.arrFlag = false; + this.passwordTokenSeenFlag = false; + + this.input = punycode.ucs2.decode(this.input); + + for (; this.pointer <= this.input.length; ++this.pointer) { + const c = this.input[this.pointer]; + const cStr = isNaN(c) ? undefined : String.fromCodePoint(c); + + // exec state machine + const ret = this["parse " + this.state](c, cStr); + if (!ret) { + break; // terminate algorithm + } else if (ret === failure) { + this.failure = true; + break; + } + } +} + +URLStateMachine.prototype["parse scheme start"] = function parseSchemeStart(c, cStr) { + if (isASCIIAlpha(c)) { + this.buffer += cStr.toLowerCase(); + this.state = "scheme"; + } else if (!this.stateOverride) { + this.state = "no scheme"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse scheme"] = function parseScheme(c, cStr) { + if (isASCIIAlphanumeric(c) || c === 43 || c === 45 || c === 46) { + this.buffer += cStr.toLowerCase(); + } else if (c === 58) { + if (this.stateOverride) { + if (isSpecial(this.url) && !isSpecialScheme(this.buffer)) { + return false; + } + + if (!isSpecial(this.url) && isSpecialScheme(this.buffer)) { + return false; + } + + if ((includesCredentials(this.url) || this.url.port !== null) && this.buffer === "file") { + return false; + } + + if (this.url.scheme === "file" && (this.url.host === "" || this.url.host === null)) { + return false; + } + } + this.url.scheme = this.buffer; + this.buffer = ""; + if (this.stateOverride) { + return false; + } + if (this.url.scheme === "file") { + if (this.input[this.pointer + 1] !== 47 || this.input[this.pointer + 2] !== 47) { + this.parseError = true; + } + this.state = "file"; + } else if (isSpecial(this.url) && this.base !== null && this.base.scheme === this.url.scheme) { + this.state = "special relative or authority"; + } else if (isSpecial(this.url)) { + this.state = "special authority slashes"; + } else if (this.input[this.pointer + 1] === 47) { + this.state = "path or authority"; + ++this.pointer; + } else { + this.url.cannotBeABaseURL = true; + this.url.path.push(""); + this.state = "cannot-be-a-base-URL path"; + } + } else if (!this.stateOverride) { + this.buffer = ""; + this.state = "no scheme"; + this.pointer = -1; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +URLStateMachine.prototype["parse no scheme"] = function parseNoScheme(c) { + if (this.base === null || (this.base.cannotBeABaseURL && c !== 35)) { + return failure; + } else if (this.base.cannotBeABaseURL && c === 35) { + this.url.scheme = this.base.scheme; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.url.cannotBeABaseURL = true; + this.state = "fragment"; + } else if (this.base.scheme === "file") { + this.state = "file"; + --this.pointer; + } else { + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special relative or authority"] = function parseSpecialRelativeOrAuthority(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "relative"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse path or authority"] = function parsePathOrAuthority(c) { + if (c === 47) { + this.state = "authority"; + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative"] = function parseRelative(c) { + this.url.scheme = this.base.scheme; + if (isNaN(c)) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 47) { + this.state = "relative slash"; + } else if (c === 63) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else if (isSpecial(this.url) && c === 92) { + this.parseError = true; + this.state = "relative slash"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.url.path = this.base.path.slice(0, this.base.path.length - 1); + + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse relative slash"] = function parseRelativeSlash(c) { + if (isSpecial(this.url) && (c === 47 || c === 92)) { + if (c === 92) { + this.parseError = true; + } + this.state = "special authority ignore slashes"; + } else if (c === 47) { + this.state = "authority"; + } else { + this.url.username = this.base.username; + this.url.password = this.base.password; + this.url.host = this.base.host; + this.url.port = this.base.port; + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority slashes"] = function parseSpecialAuthoritySlashes(c) { + if (c === 47 && this.input[this.pointer + 1] === 47) { + this.state = "special authority ignore slashes"; + ++this.pointer; + } else { + this.parseError = true; + this.state = "special authority ignore slashes"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse special authority ignore slashes"] = function parseSpecialAuthorityIgnoreSlashes(c) { + if (c !== 47 && c !== 92) { + this.state = "authority"; + --this.pointer; + } else { + this.parseError = true; + } + + return true; +}; + +URLStateMachine.prototype["parse authority"] = function parseAuthority(c, cStr) { + if (c === 64) { + this.parseError = true; + if (this.atFlag) { + this.buffer = "%40" + this.buffer; + } + this.atFlag = true; + + // careful, this is based on buffer and has its own pointer (this.pointer != pointer) and inner chars + const len = countSymbols(this.buffer); + for (let pointer = 0; pointer < len; ++pointer) { + const codePoint = this.buffer.codePointAt(pointer); + + if (codePoint === 58 && !this.passwordTokenSeenFlag) { + this.passwordTokenSeenFlag = true; + continue; + } + const encodedCodePoints = percentEncodeChar(codePoint, isUserinfoPercentEncode); + if (this.passwordTokenSeenFlag) { + this.url.password += encodedCodePoints; + } else { + this.url.username += encodedCodePoints; + } + } + this.buffer = ""; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + if (this.atFlag && this.buffer === "") { + this.parseError = true; + return failure; + } + this.pointer -= countSymbols(this.buffer) + 1; + this.buffer = ""; + this.state = "host"; + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse hostname"] = +URLStateMachine.prototype["parse host"] = function parseHostName(c, cStr) { + if (this.stateOverride && this.url.scheme === "file") { + --this.pointer; + this.state = "file host"; + } else if (c === 58 && !this.arrFlag) { + if (this.buffer === "") { + this.parseError = true; + return failure; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "port"; + if (this.stateOverride === "hostname") { + return false; + } + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92)) { + --this.pointer; + if (isSpecial(this.url) && this.buffer === "") { + this.parseError = true; + return failure; + } else if (this.stateOverride && this.buffer === "" && + (includesCredentials(this.url) || this.url.port !== null)) { + this.parseError = true; + return false; + } + + const host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + + this.url.host = host; + this.buffer = ""; + this.state = "path start"; + if (this.stateOverride) { + return false; + } + } else { + if (c === 91) { + this.arrFlag = true; + } else if (c === 93) { + this.arrFlag = false; + } + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse port"] = function parsePort(c, cStr) { + if (isASCIIDigit(c)) { + this.buffer += cStr; + } else if (isNaN(c) || c === 47 || c === 63 || c === 35 || + (isSpecial(this.url) && c === 92) || + this.stateOverride) { + if (this.buffer !== "") { + const port = parseInt(this.buffer); + if (port > Math.pow(2, 16) - 1) { + this.parseError = true; + return failure; + } + this.url.port = port === defaultPort(this.url.scheme) ? null : port; + this.buffer = ""; + } + if (this.stateOverride) { + return false; + } + this.state = "path start"; + --this.pointer; + } else { + this.parseError = true; + return failure; + } + + return true; +}; + +const fileOtherwiseCodePoints = new Set([47, 92, 63, 35]); + +URLStateMachine.prototype["parse file"] = function parseFile(c) { + this.url.scheme = "file"; + + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file slash"; + } else if (this.base !== null && this.base.scheme === "file") { + if (isNaN(c)) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + } else if (c === 63) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + this.url.query = this.base.query; + this.url.fragment = ""; + this.state = "fragment"; + } else { + if (this.input.length - this.pointer - 1 === 0 || // remaining consists of 0 code points + !isWindowsDriveLetterCodePoints(c, this.input[this.pointer + 1]) || + (this.input.length - this.pointer - 1 >= 2 && // remaining has at least 2 code points + !fileOtherwiseCodePoints.has(this.input[this.pointer + 2]))) { + this.url.host = this.base.host; + this.url.path = this.base.path.slice(); + shortenPath(this.url); + } else { + this.parseError = true; + } + + this.state = "path"; + --this.pointer; + } + } else { + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file slash"] = function parseFileSlash(c) { + if (c === 47 || c === 92) { + if (c === 92) { + this.parseError = true; + } + this.state = "file host"; + } else { + if (this.base !== null && this.base.scheme === "file") { + if (isNormalizedWindowsDriveLetterString(this.base.path[0])) { + this.url.path.push(this.base.path[0]); + } else { + this.url.host = this.base.host; + } + } + this.state = "path"; + --this.pointer; + } + + return true; +}; + +URLStateMachine.prototype["parse file host"] = function parseFileHost(c, cStr) { + if (isNaN(c) || c === 47 || c === 92 || c === 63 || c === 35) { + --this.pointer; + if (!this.stateOverride && isWindowsDriveLetterString(this.buffer)) { + this.parseError = true; + this.state = "path"; + } else if (this.buffer === "") { + this.url.host = ""; + if (this.stateOverride) { + return false; + } + this.state = "path start"; + } else { + let host = parseHost(this.buffer, isSpecial(this.url)); + if (host === failure) { + return failure; + } + if (host === "localhost") { + host = ""; + } + this.url.host = host; + + if (this.stateOverride) { + return false; + } + + this.buffer = ""; + this.state = "path start"; + } + } else { + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse path start"] = function parsePathStart(c) { + if (isSpecial(this.url)) { + if (c === 92) { + this.parseError = true; + } + this.state = "path"; + + if (c !== 47 && c !== 92) { + --this.pointer; + } + } else if (!this.stateOverride && c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (!this.stateOverride && c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else if (c !== undefined) { + this.state = "path"; + if (c !== 47) { + --this.pointer; + } + } + + return true; +}; + +URLStateMachine.prototype["parse path"] = function parsePath(c) { + if (isNaN(c) || c === 47 || (isSpecial(this.url) && c === 92) || + (!this.stateOverride && (c === 63 || c === 35))) { + if (isSpecial(this.url) && c === 92) { + this.parseError = true; + } + + if (isDoubleDot(this.buffer)) { + shortenPath(this.url); + if (c !== 47 && !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } + } else if (isSingleDot(this.buffer) && c !== 47 && + !(isSpecial(this.url) && c === 92)) { + this.url.path.push(""); + } else if (!isSingleDot(this.buffer)) { + if (this.url.scheme === "file" && this.url.path.length === 0 && isWindowsDriveLetterString(this.buffer)) { + if (this.url.host !== "" && this.url.host !== null) { + this.parseError = true; + this.url.host = ""; + } + this.buffer = this.buffer[0] + ":"; + } + this.url.path.push(this.buffer); + } + this.buffer = ""; + if (this.url.scheme === "file" && (c === undefined || c === 63 || c === 35)) { + while (this.url.path.length > 1 && this.url.path[0] === "") { + this.parseError = true; + this.url.path.shift(); + } + } + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += percentEncodeChar(c, isPathPercentEncode); + } + + return true; +}; + +URLStateMachine.prototype["parse cannot-be-a-base-URL path"] = function parseCannotBeABaseURLPath(c) { + if (c === 63) { + this.url.query = ""; + this.state = "query"; + } else if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } else { + // TODO: Add: not a URL code point + if (!isNaN(c) && c !== 37) { + this.parseError = true; + } + + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + if (!isNaN(c)) { + this.url.path[0] = this.url.path[0] + percentEncodeChar(c, isC0ControlPercentEncode); + } + } + + return true; +}; + +URLStateMachine.prototype["parse query"] = function parseQuery(c, cStr) { + if (isNaN(c) || (!this.stateOverride && c === 35)) { + if (!isSpecial(this.url) || this.url.scheme === "ws" || this.url.scheme === "wss") { + this.encodingOverride = "utf-8"; + } + + const buffer = new Buffer(this.buffer); // TODO: Use encoding override instead + for (let i = 0; i < buffer.length; ++i) { + if (buffer[i] < 0x21 || buffer[i] > 0x7E || buffer[i] === 0x22 || buffer[i] === 0x23 || + buffer[i] === 0x3C || buffer[i] === 0x3E) { + this.url.query += percentEncode(buffer[i]); + } else { + this.url.query += String.fromCodePoint(buffer[i]); + } + } + + this.buffer = ""; + if (c === 35) { + this.url.fragment = ""; + this.state = "fragment"; + } + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.buffer += cStr; + } + + return true; +}; + +URLStateMachine.prototype["parse fragment"] = function parseFragment(c) { + if (isNaN(c)) { // do nothing + } else if (c === 0x0) { + this.parseError = true; + } else { + // TODO: If c is not a URL code point and not "%", parse error. + if (c === 37 && + (!isASCIIHex(this.input[this.pointer + 1]) || + !isASCIIHex(this.input[this.pointer + 2]))) { + this.parseError = true; + } + + this.url.fragment += percentEncodeChar(c, isC0ControlPercentEncode); + } + + return true; +}; + +function serializeURL(url, excludeFragment) { + let output = url.scheme + ":"; + if (url.host !== null) { + output += "//"; + + if (url.username !== "" || url.password !== "") { + output += url.username; + if (url.password !== "") { + output += ":" + url.password; + } + output += "@"; + } + + output += serializeHost(url.host); + + if (url.port !== null) { + output += ":" + url.port; + } + } else if (url.host === null && url.scheme === "file") { + output += "//"; + } + + if (url.cannotBeABaseURL) { + output += url.path[0]; + } else { + for (const string of url.path) { + output += "/" + string; + } + } + + if (url.query !== null) { + output += "?" + url.query; + } + + if (!excludeFragment && url.fragment !== null) { + output += "#" + url.fragment; + } + + return output; +} + +function serializeOrigin(tuple) { + let result = tuple.scheme + "://"; + result += serializeHost(tuple.host); + + if (tuple.port !== null) { + result += ":" + tuple.port; + } + + return result; +} + +module.exports.serializeURL = serializeURL; + +module.exports.serializeURLOrigin = function (url) { + // https://url.spec.whatwg.org/#concept-url-origin + switch (url.scheme) { + case "blob": + try { + return module.exports.serializeURLOrigin(module.exports.parseURL(url.path[0])); + } catch (e) { + // serializing an opaque origin returns "null" + return "null"; + } + case "ftp": + case "gopher": + case "http": + case "https": + case "ws": + case "wss": + return serializeOrigin({ + scheme: url.scheme, + host: url.host, + port: url.port + }); + case "file": + // spec says "exercise to the reader", chrome says "file://" + return "file://"; + default: + // serializing an opaque origin returns "null" + return "null"; + } +}; + +module.exports.basicURLParse = function (input, options) { + if (options === undefined) { + options = {}; + } + + const usm = new URLStateMachine(input, options.baseURL, options.encodingOverride, options.url, options.stateOverride); + if (usm.failure) { + return "failure"; + } + + return usm.url; +}; + +module.exports.setTheUsername = function (url, username) { + url.username = ""; + const decoded = punycode.ucs2.decode(username); + for (let i = 0; i < decoded.length; ++i) { + url.username += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.setThePassword = function (url, password) { + url.password = ""; + const decoded = punycode.ucs2.decode(password); + for (let i = 0; i < decoded.length; ++i) { + url.password += percentEncodeChar(decoded[i], isUserinfoPercentEncode); + } +}; + +module.exports.serializeHost = serializeHost; + +module.exports.cannotHaveAUsernamePasswordPort = cannotHaveAUsernamePasswordPort; + +module.exports.serializeInteger = function (integer) { + return String(integer); +}; + +module.exports.parseURL = function (input, options) { + if (options === undefined) { + options = {}; + } + + // We don't handle blobs, so this just delegates: + return module.exports.basicURLParse(input, { baseURL: options.baseURL, encodingOverride: options.encodingOverride }); +}; diff --git a/node_modules/whatwg-url/lib/utils.js b/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 0000000..a562009 --- /dev/null +++ b/node_modules/whatwg-url/lib/utils.js @@ -0,0 +1,20 @@ +"use strict"; + +module.exports.mixin = function mixin(target, source) { + const keys = Object.getOwnPropertyNames(source); + for (let i = 0; i < keys.length; ++i) { + Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i])); + } +}; + +module.exports.wrapperSymbol = Symbol("wrapper"); +module.exports.implSymbol = Symbol("impl"); + +module.exports.wrapperForImpl = function (impl) { + return impl[module.exports.wrapperSymbol]; +}; + +module.exports.implForWrapper = function (wrapper) { + return wrapper[module.exports.implSymbol]; +}; + diff --git a/node_modules/whatwg-url/package.json b/node_modules/whatwg-url/package.json new file mode 100644 index 0000000..fce35ae --- /dev/null +++ b/node_modules/whatwg-url/package.json @@ -0,0 +1,32 @@ +{ + "name": "whatwg-url", + "version": "5.0.0", + "description": "An implementation of the WHATWG URL Standard's URL API and parsing machinery", + "main": "lib/public-api.js", + "files": [ + "lib/" + ], + "author": "Sebastian Mayr ", + "license": "MIT", + "repository": "jsdom/whatwg-url", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + }, + "devDependencies": { + "eslint": "^2.6.0", + "istanbul": "~0.4.3", + "mocha": "^2.2.4", + "recast": "~0.10.29", + "request": "^2.55.0", + "webidl2js": "^3.0.2" + }, + "scripts": { + "build": "node scripts/transform.js && node scripts/convert-idl.js", + "coverage": "istanbul cover node_modules/mocha/bin/_mocha", + "lint": "eslint .", + "prepublish": "npm run build", + "pretest": "node scripts/get-latest-platform-tests.js && npm run build", + "test": "mocha" + } +} diff --git a/node_modules/ws/LICENSE b/node_modules/ws/LICENSE new file mode 100644 index 0000000..1da5b96 --- /dev/null +++ b/node_modules/ws/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011 Einar Otto Stangvik +Copyright (c) 2013 Arnout Kazemier and contributors +Copyright (c) 2016 Luigi Pinca and contributors + +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/ws/README.md b/node_modules/ws/README.md new file mode 100644 index 0000000..a550ca1 --- /dev/null +++ b/node_modules/ws/README.md @@ -0,0 +1,536 @@ +# ws: a Node.js WebSocket library + +[![Version npm](https://img.shields.io/npm/v/ws.svg?logo=npm)](https://www.npmjs.com/package/ws) +[![CI](https://img.shields.io/github/actions/workflow/status/websockets/ws/ci.yml?branch=master&label=CI&logo=github)](https://github.com/websockets/ws/actions?query=workflow%3ACI+branch%3Amaster) +[![Coverage Status](https://img.shields.io/coveralls/websockets/ws/master.svg?logo=coveralls)](https://coveralls.io/github/websockets/ws) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client and +server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a back end with the role of a client in the WebSocket +communication. Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +object. To make the same code work seamlessly on Node.js and the browser, you +can use one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +- [Protocol support](#protocol-support) +- [Installing](#installing) + - [Opt-in for performance](#opt-in-for-performance) +- [API docs](#api-docs) +- [WebSocket compression](#websocket-compression) +- [Usage examples](#usage-examples) + - [Sending and receiving text data](#sending-and-receiving-text-data) + - [Sending binary data](#sending-binary-data) + - [Simple server](#simple-server) + - [External HTTP/S server](#external-https-server) + - [Multiple servers sharing a single HTTP/S server](#multiple-servers-sharing-a-single-https-server) + - [Client authentication](#client-authentication) + - [Server broadcast](#server-broadcast) + - [Round-trip time](#round-trip-time) + - [Use the Node.js streams API](#use-the-nodejs-streams-api) + - [Other examples](#other-examples) +- [FAQ](#faq) + - [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + - [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + - [How to connect via a proxy?](#how-to-connect-via-a-proxy) +- [Changelog](#changelog) +- [License](#license) + +## Protocol support + +- **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +- **HyBi drafts 13-17** (Current default, alternatively option + `protocolVersion: 13`) + +## Installing + +``` +npm install ws +``` + +### Opt-in for performance + +There are 2 optional modules that can be installed along side with the ws +module. These modules are binary addons that improve the performance of certain +operations. Prebuilt binaries are available for the most popular platforms so +you don't necessarily need to have a C++ compiler installed on your machine. + +- `npm install --save-optional bufferutil`: Allows to efficiently perform + operations such as masking and unmasking the data payload of the WebSocket + frames. +- `npm install --save-optional utf-8-validate`: Allows to efficiently check if a + message contains valid UTF-8. + +To not even try to require and use these modules, use the +[`WS_NO_BUFFER_UTIL`](./doc/ws.md#ws_no_buffer_util) and +[`WS_NO_UTF_8_VALIDATE`](./doc/ws.md#ws_no_utf_8_validate) environment +variables. These might be useful to enhance security in systems where a user can +put a package in the package search path of an application of another user, due +to how the Node.js resolver algorithm works. + +The `utf-8-validate` module is not needed and is not required, even if it is +already installed, regardless of the value of the `WS_NO_UTF_8_VALIDATE` +environment variable, if [`buffer.isUtf8()`][] is available. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like documentation of ws classes and +utility functions. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which enables +the client and server to negotiate a compression algorithm and its parameters, +and then selectively apply it to the data payloads of each WebSocket message. + +The extension is disabled by default on the server and enabled by default on the +client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to [catastrophic +memory fragmentation][node-zlib-bug] and slow performance. If you intend to use +permessage-deflate in production, it is worthwhile to set up a test +representative of your workload and ensure Node.js/zlib will handle it with +acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { + // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3 + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024 // Size (in bytes) below which messages + // should not be compressed if context takeover is disabled. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client set the +`perMessageDeflate` option to `false`. + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function message(data) { + console.log('received: %s', data); +}); +``` + +### Sending binary data + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('error', console.error); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Simple server + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); +``` + +### External HTTP/S server + +```js +import { createServer } from 'https'; +import { readFileSync } from 'fs'; +import { WebSocketServer } from 'ws'; + +const server = createServer({ + cert: readFileSync('/path/to/cert.pem'), + key: readFileSync('/path/to/key.pem') +}); +const wss = new WebSocketServer({ server }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log('received: %s', data); + }); + + ws.send('something'); +}); + +server.listen(8080); +``` + +### Multiple servers sharing a single HTTP/S server + +```js +import { createServer } from 'http'; +import { parse } from 'url'; +import { WebSocketServer } from 'ws'; + +const server = createServer(); +const wss1 = new WebSocketServer({ noServer: true }); +const wss2 = new WebSocketServer({ noServer: true }); + +wss1.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +wss2.on('connection', function connection(ws) { + ws.on('error', console.error); + + // ... +}); + +server.on('upgrade', function upgrade(request, socket, head) { + const { pathname } = parse(request.url); + + if (pathname === '/foo') { + wss1.handleUpgrade(request, socket, head, function done(ws) { + wss1.emit('connection', ws, request); + }); + } else if (pathname === '/bar') { + wss2.handleUpgrade(request, socket, head, function done(ws) { + wss2.emit('connection', ws, request); + }); + } else { + socket.destroy(); + } +}); + +server.listen(8080); +``` + +### Client authentication + +```js +import { createServer } from 'http'; +import { WebSocketServer } from 'ws'; + +function onSocketError(err) { + console.error(err); +} + +const server = createServer(); +const wss = new WebSocketServer({ noServer: true }); + +wss.on('connection', function connection(ws, request, client) { + ws.on('error', console.error); + + ws.on('message', function message(data) { + console.log(`Received message ${data} from user ${client}`); + }); +}); + +server.on('upgrade', function upgrade(request, socket, head) { + socket.on('error', onSocketError); + + // This function is not defined on purpose. Implement it with your own logic. + authenticate(request, function next(err, client) { + if (err || !client) { + socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); + socket.destroy(); + return; + } + + socket.removeListener('error', onSocketError); + + wss.handleUpgrade(request, socket, head, function done(ws) { + wss.emit('connection', ws, request, client); + }); + }); +}); + +server.listen(8080); +``` + +Also see the provided [example][session-parse-example] using `express-session`. + +### Server broadcast + +A client WebSocket broadcasting to all connected WebSocket clients, including +itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +A client WebSocket broadcasting to every other connected WebSocket clients, +excluding itself. + +```js +import WebSocket, { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('error', console.error); + + ws.on('message', function message(data, isBinary) { + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data, { binary: isBinary }); + } + }); + }); +}); +``` + +### Round-trip time + +```js +import WebSocket from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +ws.on('error', console.error); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function message(data) { + console.log(`Round-trip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Use the Node.js streams API + +```js +import WebSocket, { createWebSocketStream } from 'ws'; + +const ws = new WebSocket('wss://websocket-echo.com/'); + +const duplex = createWebSocketStream(ws, { encoding: 'utf8' }); + +duplex.on('error', console.error); + +duplex.pipe(process.stdout); +process.stdin.pipe(duplex); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +import { WebSocketServer } from 'ws'; + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.socket.remoteAddress; + + ws.on('error', console.error); +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for'].split(',')[0].trim(); + + ws.on('error', console.error); +}); +``` + +### How to detect and close broken connections? + +Sometimes the link between the server and the client can be interrupted in a way +that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +import { WebSocketServer } from 'ws'; + +function heartbeat() { + this.isAlive = true; +} + +const wss = new WebSocketServer({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('error', console.error); + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(); + }); +}, 30000); + +wss.on('close', function close() { + clearInterval(interval); +}); +``` + +Pong messages are automatically sent in response to ping messages as required by +the spec. + +Just like the server example above your clients might as well lose connection +without knowing it. You might want to add a ping listener on your clients to +prevent that. A simple implementation would be: + +```js +import WebSocket from 'ws'; + +function heartbeat() { + clearTimeout(this.pingTimeout); + + // Use `WebSocket#terminate()`, which immediately destroys the connection, + // instead of `WebSocket#close()`, which waits for the close timer. + // Delay should be equal to the interval at which your server + // sends out pings plus a conservative assumption of the latency. + this.pingTimeout = setTimeout(() => { + this.terminate(); + }, 30000 + 1000); +} + +const client = new WebSocket('wss://websocket-echo.com/'); + +client.on('error', console.error); +client.on('open', heartbeat); +client.on('ping', heartbeat); +client.on('close', function clear() { + clearTimeout(this.pingTimeout); +}); +``` + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[`buffer.isutf8()`]: https://nodejs.org/api/buffer.html#bufferisutf8input +[changelog]: https://github.com/websockets/ws/releases +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: + https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[session-parse-example]: ./examples/express-session-parse +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[ws-server-options]: ./doc/ws.md#new-websocketserveroptions-callback diff --git a/node_modules/ws/browser.js b/node_modules/ws/browser.js new file mode 100644 index 0000000..ca4f628 --- /dev/null +++ b/node_modules/ws/browser.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = function () { + throw new Error( + 'ws does not work in the browser. Browser clients must use the native ' + + 'WebSocket object' + ); +}; diff --git a/node_modules/ws/index.js b/node_modules/ws/index.js new file mode 100644 index 0000000..41edb3b --- /dev/null +++ b/node_modules/ws/index.js @@ -0,0 +1,13 @@ +'use strict'; + +const WebSocket = require('./lib/websocket'); + +WebSocket.createWebSocketStream = require('./lib/stream'); +WebSocket.Server = require('./lib/websocket-server'); +WebSocket.Receiver = require('./lib/receiver'); +WebSocket.Sender = require('./lib/sender'); + +WebSocket.WebSocket = WebSocket; +WebSocket.WebSocketServer = WebSocket.Server; + +module.exports = WebSocket; diff --git a/node_modules/ws/lib/buffer-util.js b/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000..f7536e2 --- /dev/null +++ b/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,131 @@ +'use strict'; + +const { EMPTY_BUFFER } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +function concat(list, totalLength) { + if (list.length === 0) return EMPTY_BUFFER; + if (list.length === 1) return list[0]; + + const target = Buffer.allocUnsafe(totalLength); + let offset = 0; + + for (let i = 0; i < list.length; i++) { + const buf = list[i]; + target.set(buf, offset); + offset += buf.length; + } + + if (offset < totalLength) { + return new FastBuffer(target.buffer, target.byteOffset, offset); + } + + return target; +} + +/** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ +function _mask(source, mask, output, offset, length) { + for (let i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } +} + +/** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ +function _unmask(buffer, mask) { + for (let i = 0; i < buffer.length; i++) { + buffer[i] ^= mask[i & 3]; + } +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} buf The buffer to convert + * @return {ArrayBuffer} Converted buffer + * @public + */ +function toArrayBuffer(buf) { + if (buf.length === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); +} + +/** + * Converts `data` to a `Buffer`. + * + * @param {*} data The data to convert + * @return {Buffer} The buffer + * @throws {TypeError} + * @public + */ +function toBuffer(data) { + toBuffer.readOnly = true; + + if (Buffer.isBuffer(data)) return data; + + let buf; + + if (data instanceof ArrayBuffer) { + buf = new FastBuffer(data); + } else if (ArrayBuffer.isView(data)) { + buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength); + } else { + buf = Buffer.from(data); + toBuffer.readOnly = false; + } + + return buf; +} + +module.exports = { + concat, + mask: _mask, + toArrayBuffer, + toBuffer, + unmask: _unmask +}; + +/* istanbul ignore else */ +if (!process.env.WS_NO_BUFFER_UTIL) { + try { + const bufferUtil = require('bufferutil'); + + module.exports.mask = function (source, mask, output, offset, length) { + if (length < 48) _mask(source, mask, output, offset, length); + else bufferUtil.mask(source, mask, output, offset, length); + }; + + module.exports.unmask = function (buffer, mask) { + if (buffer.length < 32) _unmask(buffer, mask); + else bufferUtil.unmask(buffer, mask); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/node_modules/ws/lib/constants.js b/node_modules/ws/lib/constants.js new file mode 100644 index 0000000..d691b30 --- /dev/null +++ b/node_modules/ws/lib/constants.js @@ -0,0 +1,12 @@ +'use strict'; + +module.exports = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + EMPTY_BUFFER: Buffer.alloc(0), + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), + kListener: Symbol('kListener'), + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + NOOP: () => {} +}; diff --git a/node_modules/ws/lib/event-target.js b/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000..fea4cbc --- /dev/null +++ b/node_modules/ws/lib/event-target.js @@ -0,0 +1,292 @@ +'use strict'; + +const { kForOnEventAttribute, kListener } = require('./constants'); + +const kCode = Symbol('kCode'); +const kData = Symbol('kData'); +const kError = Symbol('kError'); +const kMessage = Symbol('kMessage'); +const kReason = Symbol('kReason'); +const kTarget = Symbol('kTarget'); +const kType = Symbol('kType'); +const kWasClean = Symbol('kWasClean'); + +/** + * Class representing an event. + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @throws {TypeError} If the `type` argument is not specified + */ + constructor(type) { + this[kTarget] = null; + this[kType] = type; + } + + /** + * @type {*} + */ + get target() { + return this[kTarget]; + } + + /** + * @type {String} + */ + get type() { + return this[kType]; + } +} + +Object.defineProperty(Event.prototype, 'target', { enumerable: true }); +Object.defineProperty(Event.prototype, 'type', { enumerable: true }); + +/** + * Class representing a close event. + * + * @extends Event + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {Number} [options.code=0] The status code explaining why the + * connection was closed + * @param {String} [options.reason=''] A human-readable string explaining why + * the connection was closed + * @param {Boolean} [options.wasClean=false] Indicates whether or not the + * connection was cleanly closed + */ + constructor(type, options = {}) { + super(type); + + this[kCode] = options.code === undefined ? 0 : options.code; + this[kReason] = options.reason === undefined ? '' : options.reason; + this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; + } + + /** + * @type {Number} + */ + get code() { + return this[kCode]; + } + + /** + * @type {String} + */ + get reason() { + return this[kReason]; + } + + /** + * @type {Boolean} + */ + get wasClean() { + return this[kWasClean]; + } +} + +Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); +Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); + +/** + * Class representing an error event. + * + * @extends Event + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.error=null] The error that generated this event + * @param {String} [options.message=''] The error message + */ + constructor(type, options = {}) { + super(type); + + this[kError] = options.error === undefined ? null : options.error; + this[kMessage] = options.message === undefined ? '' : options.message; + } + + /** + * @type {*} + */ + get error() { + return this[kError]; + } + + /** + * @type {String} + */ + get message() { + return this[kMessage]; + } +} + +Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); +Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); + +/** + * Class representing a message event. + * + * @extends Event + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {String} type The name of the event + * @param {Object} [options] A dictionary object that allows for setting + * attributes via object members of the same name + * @param {*} [options.data=null] The message content + */ + constructor(type, options = {}) { + super(type); + + this[kData] = options.data === undefined ? null : options.data; + } + + /** + * @type {*} + */ + get data() { + return this[kData]; + } +} + +Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} type A string representing the event type to listen for + * @param {(Function|Object)} handler The listener to add + * @param {Object} [options] An options object specifies characteristics about + * the event listener + * @param {Boolean} [options.once=false] A `Boolean` indicating that the + * listener should be invoked at most once after being added. If `true`, + * the listener would be automatically removed when invoked. + * @public + */ + addEventListener(type, handler, options = {}) { + for (const listener of this.listeners(type)) { + if ( + !options[kForOnEventAttribute] && + listener[kListener] === handler && + !listener[kForOnEventAttribute] + ) { + return; + } + } + + let wrapper; + + if (type === 'message') { + wrapper = function onMessage(data, isBinary) { + const event = new MessageEvent('message', { + data: isBinary ? data : data.toString() + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'close') { + wrapper = function onClose(code, message) { + const event = new CloseEvent('close', { + code, + reason: message.toString(), + wasClean: this._closeFrameReceived && this._closeFrameSent + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'error') { + wrapper = function onError(error) { + const event = new ErrorEvent('error', { + error, + message: error.message + }); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else if (type === 'open') { + wrapper = function onOpen() { + const event = new Event('open'); + + event[kTarget] = this; + callListener(handler, this, event); + }; + } else { + return; + } + + wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute]; + wrapper[kListener] = handler; + + if (options.once) { + this.once(type, wrapper); + } else { + this.on(type, wrapper); + } + }, + + /** + * Remove an event listener. + * + * @param {String} type A string representing the event type to remove + * @param {(Function|Object)} handler The listener to remove + * @public + */ + removeEventListener(type, handler) { + for (const listener of this.listeners(type)) { + if (listener[kListener] === handler && !listener[kForOnEventAttribute]) { + this.removeListener(type, listener); + break; + } + } + } +}; + +module.exports = { + CloseEvent, + ErrorEvent, + Event, + EventTarget, + MessageEvent +}; + +/** + * Call an event listener + * + * @param {(Function|Object)} listener The listener to call + * @param {*} thisArg The value to use as `this`` when calling the listener + * @param {Event} event The event to pass to the listener + * @private + */ +function callListener(listener, thisArg, event) { + if (typeof listener === 'object' && listener.handleEvent) { + listener.handleEvent.call(listener, event); + } else { + listener.call(thisArg, event); + } +} diff --git a/node_modules/ws/lib/extension.js b/node_modules/ws/lib/extension.js new file mode 100644 index 0000000..3d7895c --- /dev/null +++ b/node_modules/ws/lib/extension.js @@ -0,0 +1,203 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push(dest, name, elem) { + if (dest[name] === undefined) dest[name] = [elem]; + else dest[name].push(elem); +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse(header) { + const offers = Object.create(null); + let params = Object.create(null); + let mustUnescape = false; + let isEscaping = false; + let inQuotes = false; + let extensionName; + let paramName; + let start = -1; + let code = -1; + let end = -1; + let i = 0; + + for (; i < header.length; i++) { + code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = Object.create(null); + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22 /* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c /* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + let value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = Object.create(null); + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, params); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format(extensions) { + return Object.keys(extensions) + .map((extension) => { + let configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations + .map((params) => { + return [extension] + .concat( + Object.keys(params).map((k) => { + let values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values + .map((v) => (v === true ? k : `${k}=${v}`)) + .join('; '); + }) + ) + .join('; '); + }) + .join(', '); + }) + .join(', '); +} + +module.exports = { format, parse }; diff --git a/node_modules/ws/lib/limiter.js b/node_modules/ws/lib/limiter.js new file mode 100644 index 0000000..3fd3578 --- /dev/null +++ b/node_modules/ws/lib/limiter.js @@ -0,0 +1,55 @@ +'use strict'; + +const kDone = Symbol('kDone'); +const kRun = Symbol('kRun'); + +/** + * A very simple job queue with adjustable concurrency. Adapted from + * https://github.com/STRML/async-limiter + */ +class Limiter { + /** + * Creates a new `Limiter`. + * + * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed + * to run concurrently + */ + constructor(concurrency) { + this[kDone] = () => { + this.pending--; + this[kRun](); + }; + this.concurrency = concurrency || Infinity; + this.jobs = []; + this.pending = 0; + } + + /** + * Adds a job to the queue. + * + * @param {Function} job The job to run + * @public + */ + add(job) { + this.jobs.push(job); + this[kRun](); + } + + /** + * Removes a job from the queue and runs it if possible. + * + * @private + */ + [kRun]() { + if (this.pending === this.concurrency) return; + + if (this.jobs.length) { + const job = this.jobs.shift(); + + this.pending++; + job(this[kDone]); + } + } +} + +module.exports = Limiter; diff --git a/node_modules/ws/lib/permessage-deflate.js b/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000..77d918b --- /dev/null +++ b/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,514 @@ +'use strict'; + +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const Limiter = require('./limiter'); +const { kStatusCode } = require('./constants'); + +const FastBuffer = Buffer[Symbol.species]; +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} [options] Configuration options + * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support + * for, or request, a custom client window size + * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ + * acknowledge disabling of client context takeover + * @param {Number} [options.concurrencyLimit=10] The number of concurrent + * calls to zlib + * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the + * use of a custom server window size + * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept + * disabling of server context takeover + * @param {Number} [options.threshold=1024] Size (in bytes) below which + * messages should not be compressed if context takeover is disabled + * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on + * deflate + * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on + * inflate + * @param {Boolean} [isServer=false] Create the instance in either server or + * client mode + * @param {Number} [maxPayload=0] The maximum allowed message length + */ + constructor(options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = + this._options.threshold !== undefined ? this._options.threshold : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = + this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter(concurrency); + } + } + + /** + * @type {String} + */ + static get extensionName() { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer() { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept(configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup() { + if (this._inflate) { + this._inflate.close(); + this._inflate = null; + } + + if (this._deflate) { + const callback = this._deflate[kCallback]; + + this._deflate.close(); + this._deflate = null; + + if (callback) { + callback( + new Error( + 'The deflate stream was closed while data was being processed' + ) + ); + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer(offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient(response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams(configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + let value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress(data, fin, callback) { + zlibLimiter.add((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress(data, fin, callback) { + zlibLimiter.add((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress(data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw({ + ...this._options.zlibInflateOptions, + windowBits + }); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if (this._inflate._readableState.endEmitted) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._inflate.reset(); + } + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {(Buffer|String)} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress(data, fin, callback) { + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = + typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw({ + ...this._options.zlibDeflateOptions, + windowBits + }); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + this._deflate.on('data', deflateOnData); + } + + this._deflate[kCallback] = callback; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + if (!this._deflate) { + // + // The deflate stream was closed while data was being processed. + // + return; + } + + let data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) { + data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4); + } + + // + // Ensure that the callback will not be called again in + // `PerMessageDeflate#cleanup()`. + // + this._deflate[kCallback] = null; + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + if (fin && this.params[`${endpoint}_no_context_takeover`]) { + this._deflate.reset(); + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData(chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData(chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; + this[kError][kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError(err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/node_modules/ws/lib/receiver.js b/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000..1d425ea --- /dev/null +++ b/node_modules/ws/lib/receiver.js @@ -0,0 +1,679 @@ +'use strict'; + +const { Writable } = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + kStatusCode, + kWebSocket +} = require('./constants'); +const { concat, toArrayBuffer, unmask } = require('./buffer-util'); +const { isValidStatusCode, isValidUTF8 } = require('./validation'); + +const FastBuffer = Buffer[Symbol.species]; +const promise = Promise.resolve(); + +// +// `queueMicrotask()` is not available in Node.js < 11. +// +const queueTask = + typeof queueMicrotask === 'function' ? queueMicrotask : queueMicrotaskShim; + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; +const WAIT_MICROTASK = 6; + +/** + * HyBi Receiver implementation. + * + * @extends Writable + */ +class Receiver extends Writable { + /** + * Creates a Receiver instance. + * + * @param {Object} [options] Options object + * @param {String} [options.binaryType=nodebuffer] The type for binary data + * @param {Object} [options.extensions] An object containing the negotiated + * extensions + * @param {Boolean} [options.isServer=false] Specifies whether to operate in + * client or server mode + * @param {Number} [options.maxPayload=0] The maximum allowed message length + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + */ + constructor(options = {}) { + super(); + + this._binaryType = options.binaryType || BINARY_TYPES[0]; + this._extensions = options.extensions || {}; + this._isServer = !!options.isServer; + this._maxPayload = options.maxPayload | 0; + this._skipUTF8Validation = !!options.skipUTF8Validation; + this[kWebSocket] = undefined; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + * @private + */ + _write(chunk, encoding, cb) { + if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume(n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + + return new FastBuffer(buf.buffer, buf.byteOffset, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + const offset = dst.length - n; + + if (n >= buf.length) { + dst.set(this._buffers.shift(), offset); + } else { + dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); + this._buffers[0] = new FastBuffer( + buf.buffer, + buf.byteOffset + n, + buf.length - n + ); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop(cb) { + let err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + case INFLATING: + this._loop = false; + return; + default: + // + // `WAIT_MICROTASK`. + // + this._loop = false; + + queueTask(() => { + this._state = GET_INFO; + this.startLoop(cb); + }); + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error( + RangeError, + 'RSV2 and RSV3 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_2_3' + ); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if (!this._fragmented) { + this._loop = false; + return error( + RangeError, + 'invalid opcode 0', + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error( + RangeError, + 'FIN must be set', + true, + 1002, + 'WS_ERR_EXPECTED_FIN' + ); + } + + if (compressed) { + this._loop = false; + return error( + RangeError, + 'RSV1 must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_RSV_1' + ); + } + + if ( + this._payloadLength > 0x7d || + (this._opcode === 0x08 && this._payloadLength === 1) + ) { + this._loop = false; + return error( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002, + 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' + ); + } + } else { + this._loop = false; + return error( + RangeError, + `invalid opcode ${this._opcode}`, + true, + 1002, + 'WS_ERR_INVALID_OPCODE' + ); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._isServer) { + if (!this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be set', + true, + 1002, + 'WS_ERR_EXPECTED_MASK' + ); + } + } else if (this._masked) { + this._loop = false; + return error( + RangeError, + 'MASK must be clear', + true, + 1002, + 'WS_ERR_UNEXPECTED_MASK' + ); + } + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16() { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64() { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009, + 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength() { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask() { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData(cb) { + let data = EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + + if ( + this._masked && + (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 + ) { + unmask(data, this._mask); + } + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its length is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress(data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb( + error( + RangeError, + 'Max payload size exceeded', + false, + 1009, + 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' + ) + ); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage() { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + let data; + + if (this._binaryType === 'nodebuffer') { + data = concat(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(concat(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data, true); + } else { + const buf = concat(fragments, messageLength); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + this._loop = false; + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('message', buf, false); + } + } + + this._state = WAIT_MICROTASK; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage(data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, EMPTY_BUFFER); + this.end(); + + this._state = GET_INFO; + } else { + const code = data.readUInt16BE(0); + + if (!isValidStatusCode(code)) { + return error( + RangeError, + `invalid status code ${code}`, + true, + 1002, + 'WS_ERR_INVALID_CLOSE_CODE' + ); + } + + const buf = new FastBuffer( + data.buffer, + data.byteOffset + 2, + data.length - 2 + ); + + if (!this._skipUTF8Validation && !isValidUTF8(buf)) { + return error( + Error, + 'invalid UTF-8 sequence', + true, + 1007, + 'WS_ERR_INVALID_UTF8' + ); + } + + this.emit('conclude', code, buf); + this.end(); + + this._state = GET_INFO; + } + } else if (this._opcode === 0x09) { + this.emit('ping', data); + this._state = WAIT_MICROTASK; + } else { + this.emit('pong', data); + this._state = WAIT_MICROTASK; + } + } +} + +module.exports = Receiver; + +/** + * Builds an error object. + * + * @param {function(new:Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @param {String} errorCode The exposed error code + * @return {(Error|RangeError)} The error + * @private + */ +function error(ErrorCtor, message, prefix, statusCode, errorCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error); + err.code = errorCode; + err[kStatusCode] = statusCode; + return err; +} + +/** + * A shim for `queueMicrotask()`. + * + * @param {Function} cb Callback + */ +function queueMicrotaskShim(cb) { + promise.then(cb).catch(throwErrorNextTick); +} + +/** + * Throws an error. + * + * @param {Error} err The error to throw + * @private + */ +function throwError(err) { + throw err; +} + +/** + * Throws an error in the next tick. + * + * @param {Error} err The error to throw + * @private + */ +function throwErrorNextTick(err) { + process.nextTick(throwError, err); +} diff --git a/node_modules/ws/lib/sender.js b/node_modules/ws/lib/sender.js new file mode 100644 index 0000000..1ed04b0 --- /dev/null +++ b/node_modules/ws/lib/sender.js @@ -0,0 +1,477 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ + +'use strict'; + +const { Duplex } = require('stream'); +const { randomFillSync } = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const { EMPTY_BUFFER } = require('./constants'); +const { isValidStatusCode } = require('./validation'); +const { mask: applyMask, toBuffer } = require('./buffer-util'); + +const kByteLength = Symbol('kByteLength'); +const maskBuffer = Buffer.alloc(4); + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {Duplex} socket The connection socket + * @param {Object} [extensions] An object containing the negotiated extensions + * @param {Function} [generateMask] The function used to generate the masking + * key + */ + constructor(socket, extensions, generateMask) { + this._extensions = extensions || {}; + + if (generateMask) { + this._generateMask = generateMask; + this._maskBuffer = Buffer.alloc(4); + } + + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {(Buffer|String)} data The data to frame + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @return {(Buffer|String)[]} The framed data + * @public + */ + static frame(data, options) { + let mask; + let merge = false; + let offset = 2; + let skipMasking = false; + + if (options.mask) { + mask = options.maskBuffer || maskBuffer; + + if (options.generateMask) { + options.generateMask(mask); + } else { + randomFillSync(mask, 0, 4); + } + + skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; + offset = 6; + } + + let dataLength; + + if (typeof data === 'string') { + if ( + (!options.mask || skipMasking) && + options[kByteLength] !== undefined + ) { + dataLength = options[kByteLength]; + } else { + data = Buffer.from(data); + dataLength = data.length; + } + } else { + dataLength = data.length; + merge = options.mask && options.readOnly && !skipMasking; + } + + let payloadLength = dataLength; + + if (dataLength >= 65536) { + offset += 8; + payloadLength = 127; + } else if (dataLength > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + target[1] = payloadLength; + + if (payloadLength === 126) { + target.writeUInt16BE(dataLength, 2); + } else if (payloadLength === 127) { + target[2] = target[3] = 0; + target.writeUIntBE(dataLength, 4, 6); + } + + if (!options.mask) return [target, data]; + + target[1] |= 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (skipMasking) return [target, data]; + + if (merge) { + applyMask(data, mask, target, offset, dataLength); + return [target]; + } + + applyMask(data, mask, data, 0, dataLength); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {Number} [code] The status code component of the body + * @param {(String|Buffer)} [data] The message component of the body + * @param {Boolean} [mask=false] Specifies whether or not to mask the message + * @param {Function} [cb] Callback + * @public + */ + close(code, data, mask, cb) { + let buf; + + if (code === undefined) { + buf = EMPTY_BUFFER; + } else if (typeof code !== 'number' || !isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || !data.length) { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0); + } else { + const length = Buffer.byteLength(data); + + if (length > 123) { + throw new RangeError('The message must not be greater than 123 bytes'); + } + + buf = Buffer.allocUnsafe(2 + length); + buf.writeUInt16BE(code, 0); + + if (typeof data === 'string') { + buf.write(data, 2); + } else { + buf.set(data, 2); + } + } + + const options = { + [kByteLength]: buf.length, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x08, + readOnly: false, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, buf, false, options, cb]); + } else { + this.sendFrame(Sender.frame(buf, options), cb); + } + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + ping(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x09, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} [mask=false] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback + * @public + */ + pong(data, mask, cb) { + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (byteLength > 125) { + throw new RangeError('The data size must not be greater than 125 bytes'); + } + + const options = { + [kByteLength]: byteLength, + fin: true, + generateMask: this._generateMask, + mask, + maskBuffer: this._maskBuffer, + opcode: 0x0a, + readOnly, + rsv1: false + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, false, options, cb]); + } else { + this.sendFrame(Sender.frame(data, options), cb); + } + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} [options.binary=false] Specifies whether `data` is binary + * or text + * @param {Boolean} [options.compress=false] Specifies whether or not to + * compress `data` + * @param {Boolean} [options.fin=false] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Function} [cb] Callback + * @public + */ + send(data, options, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + let opcode = options.binary ? 2 : 1; + let rsv1 = options.compress; + + let byteLength; + let readOnly; + + if (typeof data === 'string') { + byteLength = Buffer.byteLength(data); + readOnly = false; + } else { + data = toBuffer(data); + byteLength = data.length; + readOnly = toBuffer.readOnly; + } + + if (this._firstFragment) { + this._firstFragment = false; + if ( + rsv1 && + perMessageDeflate && + perMessageDeflate.params[ + perMessageDeflate._isServer + ? 'server_no_context_takeover' + : 'client_no_context_takeover' + ] + ) { + rsv1 = byteLength >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1 + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame( + Sender.frame(data, { + [kByteLength]: byteLength, + fin: options.fin, + generateMask: this._generateMask, + mask: options.mask, + maskBuffer: this._maskBuffer, + opcode, + readOnly, + rsv1: false + }), + cb + ); + } + } + + /** + * Dispatches a message. + * + * @param {(Buffer|String)} data The message to send + * @param {Boolean} [compress=false] Specifies whether or not to compress + * `data` + * @param {Object} options Options object + * @param {Boolean} [options.fin=false] Specifies whether or not to set the + * FIN bit + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Boolean} [options.mask=false] Specifies whether or not to mask + * `data` + * @param {Buffer} [options.maskBuffer] The buffer used to store the masking + * key + * @param {Number} options.opcode The opcode + * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be + * modified + * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the + * RSV1 bit + * @param {Function} [cb] Callback + * @private + */ + dispatch(data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._bufferedBytes += options[kByteLength]; + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + if (this._socket.destroyed) { + const err = new Error( + 'The socket was closed while data was being compressed' + ); + + if (typeof cb === 'function') cb(err); + + for (let i = 0; i < this._queue.length; i++) { + const params = this._queue[i]; + const callback = params[params.length - 1]; + + if (typeof callback === 'function') callback(err); + } + + return; + } + + this._bufferedBytes -= options[kByteLength]; + this._deflating = false; + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue() { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[3][kByteLength]; + Reflect.apply(params[0], this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue(params) { + this._bufferedBytes += params[3][kByteLength]; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} [cb] Callback + * @private + */ + sendFrame(list, cb) { + if (list.length === 2) { + this._socket.cork(); + this._socket.write(list[0]); + this._socket.write(list[1], cb); + this._socket.uncork(); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; diff --git a/node_modules/ws/lib/stream.js b/node_modules/ws/lib/stream.js new file mode 100644 index 0000000..230734b --- /dev/null +++ b/node_modules/ws/lib/stream.js @@ -0,0 +1,159 @@ +'use strict'; + +const { Duplex } = require('stream'); + +/** + * Emits the `'close'` event on a stream. + * + * @param {Duplex} stream The stream. + * @private + */ +function emitClose(stream) { + stream.emit('close'); +} + +/** + * The listener of the `'end'` event. + * + * @private + */ +function duplexOnEnd() { + if (!this.destroyed && this._writableState.finished) { + this.destroy(); + } +} + +/** + * The listener of the `'error'` event. + * + * @param {Error} err The error + * @private + */ +function duplexOnError(err) { + this.removeListener('error', duplexOnError); + this.destroy(); + if (this.listenerCount('error') === 0) { + // Do not suppress the throwing behavior. + this.emit('error', err); + } +} + +/** + * Wraps a `WebSocket` in a duplex stream. + * + * @param {WebSocket} ws The `WebSocket` to wrap + * @param {Object} [options] The options for the `Duplex` constructor + * @return {Duplex} The duplex stream + * @public + */ +function createWebSocketStream(ws, options) { + let terminateOnDestroy = true; + + const duplex = new Duplex({ + ...options, + autoDestroy: false, + emitClose: false, + objectMode: false, + writableObjectMode: false + }); + + ws.on('message', function message(msg, isBinary) { + const data = + !isBinary && duplex._readableState.objectMode ? msg.toString() : msg; + + if (!duplex.push(data)) ws.pause(); + }); + + ws.once('error', function error(err) { + if (duplex.destroyed) return; + + // Prevent `ws.terminate()` from being called by `duplex._destroy()`. + // + // - If the `'error'` event is emitted before the `'open'` event, then + // `ws.terminate()` is a noop as no socket is assigned. + // - Otherwise, the error is re-emitted by the listener of the `'error'` + // event of the `Receiver` object. The listener already closes the + // connection by calling `ws.close()`. This allows a close frame to be + // sent to the other peer. If `ws.terminate()` is called right after this, + // then the close frame might not be sent. + terminateOnDestroy = false; + duplex.destroy(err); + }); + + ws.once('close', function close() { + if (duplex.destroyed) return; + + duplex.push(null); + }); + + duplex._destroy = function (err, callback) { + if (ws.readyState === ws.CLOSED) { + callback(err); + process.nextTick(emitClose, duplex); + return; + } + + let called = false; + + ws.once('error', function error(err) { + called = true; + callback(err); + }); + + ws.once('close', function close() { + if (!called) callback(err); + process.nextTick(emitClose, duplex); + }); + + if (terminateOnDestroy) ws.terminate(); + }; + + duplex._final = function (callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._final(callback); + }); + return; + } + + // If the value of the `_socket` property is `null` it means that `ws` is a + // client websocket and the handshake failed. In fact, when this happens, a + // socket is never assigned to the websocket. Wait for the `'error'` event + // that will be emitted by the websocket. + if (ws._socket === null) return; + + if (ws._socket._writableState.finished) { + callback(); + if (duplex._readableState.endEmitted) duplex.destroy(); + } else { + ws._socket.once('finish', function finish() { + // `duplex` is not destroyed here because the `'end'` event will be + // emitted on `duplex` after this `'finish'` event. The EOF signaling + // `null` chunk is, in fact, pushed when the websocket emits `'close'`. + callback(); + }); + ws.close(); + } + }; + + duplex._read = function () { + if (ws.isPaused) ws.resume(); + }; + + duplex._write = function (chunk, encoding, callback) { + if (ws.readyState === ws.CONNECTING) { + ws.once('open', function open() { + duplex._write(chunk, encoding, callback); + }); + return; + } + + ws.send(chunk, callback); + }; + + duplex.on('end', duplexOnEnd); + duplex.on('error', duplexOnError); + return duplex; +} + +module.exports = createWebSocketStream; diff --git a/node_modules/ws/lib/subprotocol.js b/node_modules/ws/lib/subprotocol.js new file mode 100644 index 0000000..d4381e8 --- /dev/null +++ b/node_modules/ws/lib/subprotocol.js @@ -0,0 +1,62 @@ +'use strict'; + +const { tokenChars } = require('./validation'); + +/** + * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. + * + * @param {String} header The field value of the header + * @return {Set} The subprotocol names + * @public + */ +function parse(header) { + const protocols = new Set(); + let start = -1; + let end = -1; + let i = 0; + + for (i; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if ( + i !== 0 && + (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ + ) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x2c /* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + + const protocol = header.slice(start, end); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + + if (start === -1 || end !== -1) { + throw new SyntaxError('Unexpected end of input'); + } + + const protocol = header.slice(start, i); + + if (protocols.has(protocol)) { + throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); + } + + protocols.add(protocol); + return protocols; +} + +module.exports = { parse }; diff --git a/node_modules/ws/lib/validation.js b/node_modules/ws/lib/validation.js new file mode 100644 index 0000000..c352e6e --- /dev/null +++ b/node_modules/ws/lib/validation.js @@ -0,0 +1,130 @@ +'use strict'; + +const { isUtf8 } = require('buffer'); + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +// prettier-ignore +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +function isValidStatusCode(code) { + return ( + (code >= 1000 && + code <= 1014 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +} + +/** + * Checks if a given buffer contains only correct UTF-8. + * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by + * Markus Kuhn. + * + * @param {Buffer} buf The buffer to check + * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` + * @public + */ +function _isValidUTF8(buf) { + const len = buf.length; + let i = 0; + + while (i < len) { + if ((buf[i] & 0x80) === 0) { + // 0xxxxxxx + i++; + } else if ((buf[i] & 0xe0) === 0xc0) { + // 110xxxxx 10xxxxxx + if ( + i + 1 === len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i] & 0xfe) === 0xc0 // Overlong + ) { + return false; + } + + i += 2; + } else if ((buf[i] & 0xf0) === 0xe0) { + // 1110xxxx 10xxxxxx 10xxxxxx + if ( + i + 2 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong + (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) + ) { + return false; + } + + i += 3; + } else if ((buf[i] & 0xf8) === 0xf0) { + // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + if ( + i + 3 >= len || + (buf[i + 1] & 0xc0) !== 0x80 || + (buf[i + 2] & 0xc0) !== 0x80 || + (buf[i + 3] & 0xc0) !== 0x80 || + (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong + (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || + buf[i] > 0xf4 // > U+10FFFF + ) { + return false; + } + + i += 4; + } else { + return false; + } + } + + return true; +} + +module.exports = { + isValidStatusCode, + isValidUTF8: _isValidUTF8, + tokenChars +}; + +if (isUtf8) { + module.exports.isValidUTF8 = function (buf) { + return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); + }; +} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { + try { + const isValidUTF8 = require('utf-8-validate'); + + module.exports.isValidUTF8 = function (buf) { + return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); + }; + } catch (e) { + // Continue regardless of the error. + } +} diff --git a/node_modules/ws/lib/websocket-server.js b/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000..b0ed7bd --- /dev/null +++ b/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,531 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const http = require('http'); +const { Duplex } = require('stream'); +const { createHash } = require('crypto'); + +const extension = require('./extension'); +const PerMessageDeflate = require('./permessage-deflate'); +const subprotocol = require('./subprotocol'); +const WebSocket = require('./websocket'); +const { GUID, kWebSocket } = require('./constants'); + +const keyRegex = /^[+/0-9A-Za-z]{22}==$/; + +const RUNNING = 0; +const CLOSING = 1; +const CLOSED = 2; + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {Number} [options.backlog=511] The maximum length of the queue of + * pending connections + * @param {Boolean} [options.clientTracking=true] Specifies whether or not to + * track clients + * @param {Function} [options.handleProtocols] A hook to handle protocols + * @param {String} [options.host] The hostname where to bind the server + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Boolean} [options.noServer=false] Enable no server mode + * @param {String} [options.path] Accept only connections matching this path + * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable + * permessage-deflate + * @param {Number} [options.port] The port where to bind the server + * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S + * server to use + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @param {Function} [options.verifyClient] A hook to reject connections + * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` + * class to use. It must be the `WebSocket` class or class that extends it + * @param {Function} [callback] A listener for the `listening` event + */ + constructor(options, callback) { + super(); + + options = { + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null, + WebSocket, + ...options + }; + + if ( + (options.port == null && !options.server && !options.noServer) || + (options.port != null && (options.server || options.noServer)) || + (options.server && options.noServer) + ) { + throw new TypeError( + 'One and only one of the "port", "server", or "noServer" options ' + + 'must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen( + options.port, + options.host, + options.backlog, + callback + ); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + const emitConnection = this.emit.bind(this, 'connection'); + + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, emitConnection); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) { + this.clients = new Set(); + this._shouldEmitClose = false; + } + + this.options = options; + this._state = RUNNING; + } + + /** + * 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. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address() { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Stop the server from accepting new connections and emit the `'close'` event + * when all existing connections are closed. + * + * @param {Function} [cb] A one-time listener for the `'close'` event + * @public + */ + close(cb) { + if (this._state === CLOSED) { + if (cb) { + this.once('close', () => { + cb(new Error('The server is not running')); + }); + } + + process.nextTick(emitClose, this); + return; + } + + if (cb) this.once('close', cb); + + if (this._state === CLOSING) return; + this._state = CLOSING; + + if (this.options.noServer || this.options.server) { + if (this._server) { + this._removeListeners(); + this._removeListeners = this._server = null; + } + + if (this.clients) { + if (!this.clients.size) { + process.nextTick(emitClose, this); + } else { + this._shouldEmitClose = true; + } + } else { + process.nextTick(emitClose, this); + } + } else { + const server = this._server; + + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // The HTTP/S server was created internally. Close it, and rely on its + // `'close'` event. + // + server.close(() => { + emitClose(this); + }); + } + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle(req) { + if (this.options.path) { + const index = req.url.indexOf('?'); + const pathname = index !== -1 ? req.url.slice(0, index) : req.url; + + if (pathname !== this.options.path) return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade(req, socket, head, cb) { + socket.on('error', socketOnError); + + const key = req.headers['sec-websocket-key']; + const version = +req.headers['sec-websocket-version']; + + if (req.method !== 'GET') { + const message = 'Invalid HTTP method'; + abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); + return; + } + + if (req.headers.upgrade.toLowerCase() !== 'websocket') { + const message = 'Invalid Upgrade header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!key || !keyRegex.test(key)) { + const message = 'Missing or invalid Sec-WebSocket-Key header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (version !== 8 && version !== 13) { + const message = 'Missing or invalid Sec-WebSocket-Version header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + + if (!this.shouldHandle(req)) { + abortHandshake(socket, 400); + return; + } + + const secWebSocketProtocol = req.headers['sec-websocket-protocol']; + let protocols = new Set(); + + if (secWebSocketProtocol !== undefined) { + try { + protocols = subprotocol.parse(secWebSocketProtocol); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Protocol header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + const secWebSocketExtensions = req.headers['sec-websocket-extensions']; + const extensions = {}; + + if ( + this.options.perMessageDeflate && + secWebSocketExtensions !== undefined + ) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse(secWebSocketExtensions); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + const message = + 'Invalid or unacceptable Sec-WebSocket-Extensions header'; + abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); + return; + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: + req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.socket.authorized || req.socket.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message, headers) => { + if (!verified) { + return abortHandshake(socket, code || 401, message, headers); + } + + this.completeUpgrade( + extensions, + key, + protocols, + req, + socket, + head, + cb + ); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {String} key The value of the `Sec-WebSocket-Key` header + * @param {Set} protocols The subprotocols + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @throws {Error} If called more than once with the same socket + * @private + */ + completeUpgrade(extensions, key, protocols, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + if (socket[kWebSocket]) { + throw new Error( + 'server.handleUpgrade() was called more than once with the same ' + + 'socket, possibly due to a misconfiguration' + ); + } + + if (this._state > RUNNING) return abortHandshake(socket, 503); + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${digest}` + ]; + + const ws = new this.options.WebSocket(null); + + if (protocols.size) { + // + // Optionally call external protocol selection handler. + // + const protocol = this.options.handleProtocols + ? this.options.handleProtocols(protocols, req) + : protocols.values().next().value; + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws._protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, { + maxPayload: this.options.maxPayload, + skipUTF8Validation: this.options.skipUTF8Validation + }); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => { + this.clients.delete(ws); + + if (this._shouldEmitClose && !this.clients.size) { + process.nextTick(emitClose, this); + } + }); + } + + cb(ws, req); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.} map The listeners to add + * @return {Function} A function that will remove the added listeners when + * called + * @private + */ +function addListeners(server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners() { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Emit a `'close'` event on an `EventEmitter`. + * + * @param {EventEmitter} server The event emitter + * @private + */ +function emitClose(server) { + server._state = CLOSED; + server.emit('close'); +} + +/** + * Handle socket errors. + * + * @private + */ +function socketOnError() { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @param {Object} [headers] Additional HTTP response headers + * @private + */ +function abortHandshake(socket, code, message, headers) { + // + // The socket is writable unless the user destroyed or ended it before calling + // `server.handleUpgrade()` or in the `verifyClient` function, which is a user + // error. Handling this does not make much sense as the worst that can happen + // is that some of the data written by the user might be discarded due to the + // call to `socket.end()` below, which triggers an `'error'` event that in + // turn causes the socket to be destroyed. + // + message = message || http.STATUS_CODES[code]; + headers = { + Connection: 'close', + 'Content-Type': 'text/html', + 'Content-Length': Buffer.byteLength(message), + ...headers + }; + + socket.once('finish', socket.destroy); + + socket.end( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + Object.keys(headers) + .map((h) => `${h}: ${headers[h]}`) + .join('\r\n') + + '\r\n\r\n' + + message + ); +} + +/** + * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least + * one listener for it, otherwise call `abortHandshake()`. + * + * @param {WebSocketServer} server The WebSocket server + * @param {http.IncomingMessage} req The request object + * @param {Duplex} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} message The HTTP response body + * @private + */ +function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { + if (server.listenerCount('wsClientError')) { + const err = new Error(message); + Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); + + server.emit('wsClientError', err, socket, req); + } else { + abortHandshake(socket, code, message); + } +} diff --git a/node_modules/ws/lib/websocket.js b/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000..8685ff7 --- /dev/null +++ b/node_modules/ws/lib/websocket.js @@ -0,0 +1,1319 @@ +/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$" }] */ + +'use strict'; + +const EventEmitter = require('events'); +const https = require('https'); +const http = require('http'); +const net = require('net'); +const tls = require('tls'); +const { randomBytes, createHash } = require('crypto'); +const { Duplex, Readable } = require('stream'); +const { URL } = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); +const { + BINARY_TYPES, + EMPTY_BUFFER, + GUID, + kForOnEventAttribute, + kListener, + kStatusCode, + kWebSocket, + NOOP +} = require('./constants'); +const { + EventTarget: { addEventListener, removeEventListener } +} = require('./event-target'); +const { format, parse } = require('./extension'); +const { toBuffer } = require('./buffer-util'); + +const closeTimeout = 30 * 1000; +const kAborted = Symbol('kAborted'); +const protocolVersions = [8, 13]; +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {(String|URL)} address The URL to which to connect + * @param {(String|String[])} [protocols] The subprotocols + * @param {Object} [options] Connection options + */ + constructor(address, protocols, options) { + super(); + + this._binaryType = BINARY_TYPES[0]; + this._closeCode = 1006; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = EMPTY_BUFFER; + this._closeTimer = null; + this._extensions = {}; + this._paused = false; + this._protocol = ''; + this._readyState = WebSocket.CONNECTING; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + this._bufferedAmount = 0; + this._isServer = false; + this._redirects = 0; + + if (protocols === undefined) { + protocols = []; + } else if (!Array.isArray(protocols)) { + if (typeof protocols === 'object' && protocols !== null) { + options = protocols; + protocols = []; + } else { + protocols = [protocols]; + } + } + + initAsClient(this, address, protocols, options); + } else { + this._isServer = true; + } + } + + /** + * This deviates from the WHATWG interface since ws doesn't support the + * required default "blob" type (instead we define a custom "nodebuffer" + * type). + * + * @type {String} + */ + get binaryType() { + return this._binaryType; + } + + set binaryType(type) { + if (!BINARY_TYPES.includes(type)) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount() { + if (!this._socket) return this._bufferedAmount; + + return this._socket._writableState.length + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions() { + return Object.keys(this._extensions).join(); + } + + /** + * @type {Boolean} + */ + get isPaused() { + return this._paused; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onclose() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onerror() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onopen() { + return null; + } + + /** + * @type {Function} + */ + /* istanbul ignore next */ + get onmessage() { + return null; + } + + /** + * @type {String} + */ + get protocol() { + return this._protocol; + } + + /** + * @type {Number} + */ + get readyState() { + return this._readyState; + } + + /** + * @type {String} + */ + get url() { + return this._url; + } + + /** + * Set up the socket and the internal resources. + * + * @param {Duplex} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Object} options Options object + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.maxPayload=0] The maximum allowed message size + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ + setSocket(socket, head, options) { + const receiver = new Receiver({ + binaryType: this.binaryType, + extensions: this._extensions, + isServer: this._isServer, + maxPayload: options.maxPayload, + skipUTF8Validation: options.skipUTF8Validation + }); + + this._sender = new Sender(socket, this._extensions, options.generateMask); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + // + // These methods may not be available if `socket` is just a `Duplex`. + // + if (socket.setTimeout) socket.setTimeout(0); + if (socket.setNoDelay) socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this._readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose() { + if (!this._socket) { + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this._readyState = WebSocket.CLOSED; + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} [code] Status code explaining why the connection is closing + * @param {(String|Buffer)} [data] The reason why the connection is + * closing + * @public + */ + close(code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this.readyState === WebSocket.CLOSING) { + if ( + this._closeFrameSent && + (this._closeFrameReceived || this._receiver._writableState.errorEmitted) + ) { + this._socket.end(); + } + + return; + } + + this._readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if ( + this._closeFrameReceived || + this._receiver._writableState.errorEmitted + ) { + this._socket.end(); + } + }); + + // + // Specify a timeout for the closing handshake to complete. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + + /** + * Pause the socket. + * + * @public + */ + pause() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = true; + this._socket.pause(); + } + + /** + * Send a ping. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the ping is sent + * @public + */ + ping(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} [data] The data to send + * @param {Boolean} [mask] Indicates whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when the pong is sent + * @public + */ + pong(data, mask, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || EMPTY_BUFFER, mask, cb); + } + + /** + * Resume the socket. + * + * @public + */ + resume() { + if ( + this.readyState === WebSocket.CONNECTING || + this.readyState === WebSocket.CLOSED + ) { + return; + } + + this._paused = false; + if (!this._receiver._writableState.needDrain) this._socket.resume(); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} [options] Options object + * @param {Boolean} [options.binary] Specifies whether `data` is binary or + * text + * @param {Boolean} [options.compress] Specifies whether or not to compress + * `data` + * @param {Boolean} [options.fin=true] Specifies whether the fragment is the + * last one + * @param {Boolean} [options.mask] Specifies whether or not to mask `data` + * @param {Function} [cb] Callback which is executed when data is written out + * @public + */ + send(data, options, cb) { + if (this.readyState === WebSocket.CONNECTING) { + throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); + } + + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (typeof data === 'number') data = data.toString(); + + if (this.readyState !== WebSocket.OPEN) { + sendAfterClose(this, data, cb); + return; + } + + const opts = { + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true, + ...options + }; + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate() { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + abortHandshake(this, this._req, msg); + return; + } + + if (this._socket) { + this._readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} CONNECTING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CONNECTING', { + enumerable: true, + value: readyStates.indexOf('CONNECTING') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} OPEN + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'OPEN', { + enumerable: true, + value: readyStates.indexOf('OPEN') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSING + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSING', { + enumerable: true, + value: readyStates.indexOf('CLOSING') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket + */ +Object.defineProperty(WebSocket, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +/** + * @constant {Number} CLOSED + * @memberof WebSocket.prototype + */ +Object.defineProperty(WebSocket.prototype, 'CLOSED', { + enumerable: true, + value: readyStates.indexOf('CLOSED') +}); + +[ + 'binaryType', + 'bufferedAmount', + 'extensions', + 'isPaused', + 'protocol', + 'readyState', + 'url' +].forEach((property) => { + Object.defineProperty(WebSocket.prototype, property, { enumerable: true }); +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + enumerable: true, + get() { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) return listener[kListener]; + } + + return null; + }, + set(handler) { + for (const listener of this.listeners(method)) { + if (listener[kForOnEventAttribute]) { + this.removeListener(method, listener); + break; + } + } + + if (typeof handler !== 'function') return; + + this.addEventListener(method, handler, { + [kForOnEventAttribute]: true + }); + } + }); +}); + +WebSocket.prototype.addEventListener = addEventListener; +WebSocket.prototype.removeEventListener = removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {WebSocket} websocket The client to initialize + * @param {(String|URL)} address The URL to which to connect + * @param {Array} protocols The subprotocols + * @param {Object} [options] Connection options + * @param {Boolean} [options.followRedirects=false] Whether or not to follow + * redirects + * @param {Function} [options.generateMask] The function used to generate the + * masking key + * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the + * handshake request + * @param {Number} [options.maxPayload=104857600] The maximum allowed message + * size + * @param {Number} [options.maxRedirects=10] The maximum number of redirects + * allowed + * @param {String} [options.origin] Value of the `Origin` or + * `Sec-WebSocket-Origin` header + * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable + * permessage-deflate + * @param {Number} [options.protocolVersion=13] Value of the + * `Sec-WebSocket-Version` header + * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or + * not to skip UTF-8 validation for text and close messages + * @private + */ +function initAsClient(websocket, address, protocols, options) { + const opts = { + protocolVersion: protocolVersions[1], + maxPayload: 100 * 1024 * 1024, + skipUTF8Validation: false, + perMessageDeflate: true, + followRedirects: false, + maxRedirects: 10, + ...options, + createConnection: undefined, + socketPath: undefined, + hostname: undefined, + protocol: undefined, + timeout: undefined, + method: 'GET', + host: undefined, + path: undefined, + port: undefined + }; + + if (!protocolVersions.includes(opts.protocolVersion)) { + throw new RangeError( + `Unsupported protocol version: ${opts.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + let parsedUrl; + + if (address instanceof URL) { + parsedUrl = address; + } else { + try { + parsedUrl = new URL(address); + } catch (e) { + throw new SyntaxError(`Invalid URL: ${address}`); + } + } + + if (parsedUrl.protocol === 'http:') { + parsedUrl.protocol = 'ws:'; + } else if (parsedUrl.protocol === 'https:') { + parsedUrl.protocol = 'wss:'; + } + + websocket._url = parsedUrl.href; + + const isSecure = parsedUrl.protocol === 'wss:'; + const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; + let invalidUrlMessage; + + if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { + invalidUrlMessage = + 'The URL\'s protocol must be one of "ws:", "wss:", ' + + '"http:", "https", or "ws+unix:"'; + } else if (isIpcUrl && !parsedUrl.pathname) { + invalidUrlMessage = "The URL's pathname is empty"; + } else if (parsedUrl.hash) { + invalidUrlMessage = 'The URL contains a fragment identifier'; + } + + if (invalidUrlMessage) { + const err = new SyntaxError(invalidUrlMessage); + + if (websocket._redirects === 0) { + throw err; + } else { + emitErrorAndClose(websocket, err); + return; + } + } + + const defaultPort = isSecure ? 443 : 80; + const key = randomBytes(16).toString('base64'); + const request = isSecure ? https.request : http.request; + const protocolSet = new Set(); + let perMessageDeflate; + + opts.createConnection = isSecure ? tlsConnect : netConnect; + opts.defaultPort = opts.defaultPort || defaultPort; + opts.port = parsedUrl.port || defaultPort; + opts.host = parsedUrl.hostname.startsWith('[') + ? parsedUrl.hostname.slice(1, -1) + : parsedUrl.hostname; + opts.headers = { + ...opts.headers, + 'Sec-WebSocket-Version': opts.protocolVersion, + 'Sec-WebSocket-Key': key, + Connection: 'Upgrade', + Upgrade: 'websocket' + }; + opts.path = parsedUrl.pathname + parsedUrl.search; + opts.timeout = opts.handshakeTimeout; + + if (opts.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, + false, + opts.maxPayload + ); + opts.headers['Sec-WebSocket-Extensions'] = format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (protocols.length) { + for (const protocol of protocols) { + if ( + typeof protocol !== 'string' || + !subprotocolRegex.test(protocol) || + protocolSet.has(protocol) + ) { + throw new SyntaxError( + 'An invalid or duplicated subprotocol was specified' + ); + } + + protocolSet.add(protocol); + } + + opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); + } + if (opts.origin) { + if (opts.protocolVersion < 13) { + opts.headers['Sec-WebSocket-Origin'] = opts.origin; + } else { + opts.headers.Origin = opts.origin; + } + } + if (parsedUrl.username || parsedUrl.password) { + opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; + } + + if (isIpcUrl) { + const parts = opts.path.split(':'); + + opts.socketPath = parts[0]; + opts.path = parts[1]; + } + + let req; + + if (opts.followRedirects) { + if (websocket._redirects === 0) { + websocket._originalIpc = isIpcUrl; + websocket._originalSecure = isSecure; + websocket._originalHostOrSocketPath = isIpcUrl + ? opts.socketPath + : parsedUrl.host; + + const headers = options && options.headers; + + // + // Shallow copy the user provided options so that headers can be changed + // without mutating the original object. + // + options = { ...options, headers: {} }; + + if (headers) { + for (const [key, value] of Object.entries(headers)) { + options.headers[key.toLowerCase()] = value; + } + } + } else if (websocket.listenerCount('redirect') === 0) { + const isSameHost = isIpcUrl + ? websocket._originalIpc + ? opts.socketPath === websocket._originalHostOrSocketPath + : false + : websocket._originalIpc + ? false + : parsedUrl.host === websocket._originalHostOrSocketPath; + + if (!isSameHost || (websocket._originalSecure && !isSecure)) { + // + // Match curl 7.77.0 behavior and drop the following headers. These + // headers are also dropped when following a redirect to a subdomain. + // + delete opts.headers.authorization; + delete opts.headers.cookie; + + if (!isSameHost) delete opts.headers.host; + + opts.auth = undefined; + } + } + + // + // Match curl 7.77.0 behavior and make the first `Authorization` header win. + // If the `Authorization` header is set, then there is nothing to do as it + // will take precedence. + // + if (opts.auth && !options.headers.authorization) { + options.headers.authorization = + 'Basic ' + Buffer.from(opts.auth).toString('base64'); + } + + req = websocket._req = request(opts); + + if (websocket._redirects) { + // + // Unlike what is done for the `'upgrade'` event, no early exit is + // triggered here if the user calls `websocket.close()` or + // `websocket.terminate()` from a listener of the `'redirect'` event. This + // is because the user can also call `request.destroy()` with an error + // before calling `websocket.close()` or `websocket.terminate()` and this + // would result in an error being emitted on the `request` object with no + // `'error'` event listeners attached. + // + websocket.emit('redirect', websocket.url, req); + } + } else { + req = websocket._req = request(opts); + } + + if (opts.timeout) { + req.on('timeout', () => { + abortHandshake(websocket, req, 'Opening handshake has timed out'); + }); + } + + req.on('error', (err) => { + if (req === null || req[kAborted]) return; + + req = websocket._req = null; + emitErrorAndClose(websocket, err); + }); + + req.on('response', (res) => { + const location = res.headers.location; + const statusCode = res.statusCode; + + if ( + location && + opts.followRedirects && + statusCode >= 300 && + statusCode < 400 + ) { + if (++websocket._redirects > opts.maxRedirects) { + abortHandshake(websocket, req, 'Maximum redirects exceeded'); + return; + } + + req.abort(); + + let addr; + + try { + addr = new URL(location, address); + } catch (e) { + const err = new SyntaxError(`Invalid URL: ${location}`); + emitErrorAndClose(websocket, err); + return; + } + + initAsClient(websocket, addr, protocols, options); + } else if (!websocket.emit('unexpected-response', req, res)) { + abortHandshake( + websocket, + req, + `Unexpected server response: ${res.statusCode}` + ); + } + }); + + req.on('upgrade', (res, socket, head) => { + websocket.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the + // `'upgrade'` event. + // + if (websocket.readyState !== WebSocket.CONNECTING) return; + + req = websocket._req = null; + + if (res.headers.upgrade.toLowerCase() !== 'websocket') { + abortHandshake(websocket, socket, 'Invalid Upgrade header'); + return; + } + + const digest = createHash('sha1') + .update(key + GUID) + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + let protError; + + if (serverProt !== undefined) { + if (!protocolSet.size) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (!protocolSet.has(serverProt)) { + protError = 'Server sent an invalid subprotocol'; + } + } else if (protocolSet.size) { + protError = 'Server sent no subprotocol'; + } + + if (protError) { + abortHandshake(websocket, socket, protError); + return; + } + + if (serverProt) websocket._protocol = serverProt; + + const secWebSocketExtensions = res.headers['sec-websocket-extensions']; + + if (secWebSocketExtensions !== undefined) { + if (!perMessageDeflate) { + const message = + 'Server sent a Sec-WebSocket-Extensions header but no extension ' + + 'was requested'; + abortHandshake(websocket, socket, message); + return; + } + + let extensions; + + try { + extensions = parse(secWebSocketExtensions); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + const extensionNames = Object.keys(extensions); + + if ( + extensionNames.length !== 1 || + extensionNames[0] !== PerMessageDeflate.extensionName + ) { + const message = 'Server indicated an extension that was not requested'; + abortHandshake(websocket, socket, message); + return; + } + + try { + perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]); + } catch (err) { + const message = 'Invalid Sec-WebSocket-Extensions header'; + abortHandshake(websocket, socket, message); + return; + } + + websocket._extensions[PerMessageDeflate.extensionName] = + perMessageDeflate; + } + + websocket.setSocket(socket, head, { + generateMask: opts.generateMask, + maxPayload: opts.maxPayload, + skipUTF8Validation: opts.skipUTF8Validation + }); + }); + + if (opts.finishRequest) { + opts.finishRequest(req, websocket); + } else { + req.end(); + } +} + +/** + * Emit the `'error'` and `'close'` events. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {Error} The error to emit + * @private + */ +function emitErrorAndClose(websocket, err) { + websocket._readyState = WebSocket.CLOSING; + websocket.emit('error', err); + websocket.emitClose(); +} + +/** + * Create a `net.Socket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {net.Socket} The newly created socket used to start the connection + * @private + */ +function netConnect(options) { + options.path = options.socketPath; + return net.connect(options); +} + +/** + * Create a `tls.TLSSocket` and initiate a connection. + * + * @param {Object} options Connection options + * @return {tls.TLSSocket} The newly created socket used to start the connection + * @private + */ +function tlsConnect(options) { + options.path = undefined; + + if (!options.servername && options.servername !== '') { + options.servername = net.isIP(options.host) ? '' : options.host; + } + + return tls.connect(options); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to + * abort or the socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake(websocket, stream, message) { + websocket._readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream[kAborted] = true; + stream.abort(); + + if (stream.socket && !stream.socket.destroyed) { + // + // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if + // called after the request completed. See + // https://github.com/websockets/ws/issues/1869. + // + stream.socket.destroy(); + } + + process.nextTick(emitErrorAndClose, websocket, err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * Handle cases where the `ping()`, `pong()`, or `send()` methods are called + * when the `readyState` attribute is `CLOSING` or `CLOSED`. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {*} [data] The data to send + * @param {Function} [cb] Callback + * @private + */ +function sendAfterClose(websocket, data, cb) { + if (data) { + const length = toBuffer(data).length; + + // + // The `_bufferedAmount` property is used only when the peer is a client and + // the opening handshake fails. Under these circumstances, in fact, the + // `setSocket()` method is not called, so the `_socket` and `_sender` + // properties are set to `null`. + // + if (websocket._socket) websocket._sender._bufferedBytes += length; + else websocket._bufferedAmount += length; + } + + if (cb) { + const err = new Error( + `WebSocket is not open: readyState ${websocket.readyState} ` + + `(${readyStates[websocket.readyState]})` + ); + process.nextTick(cb, err); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {Buffer} reason The reason for closing + * @private + */ +function receiverOnConclude(code, reason) { + const websocket = this[kWebSocket]; + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (websocket._socket[kWebSocket] === undefined) return; + + websocket._socket.removeListener('data', socketOnData); + process.nextTick(resume, websocket._socket); + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain() { + const websocket = this[kWebSocket]; + + if (!websocket.isPaused) websocket._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError(err) { + const websocket = this[kWebSocket]; + + if (websocket._socket[kWebSocket] !== undefined) { + websocket._socket.removeListener('data', socketOnData); + + // + // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See + // https://github.com/websockets/ws/issues/1940. + // + process.nextTick(resume, websocket._socket); + + websocket.close(err[kStatusCode]); + } + + websocket.emit('error', err); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish() { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {Buffer|ArrayBuffer|Buffer[])} data The message + * @param {Boolean} isBinary Specifies whether the message is binary or not + * @private + */ +function receiverOnMessage(data, isBinary) { + this[kWebSocket].emit('message', data, isBinary); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing(data) { + const websocket = this[kWebSocket]; + + websocket.pong(data, !websocket._isServer, NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong(data) { + this[kWebSocket].emit('pong', data); +} + +/** + * Resume a readable stream + * + * @param {Readable} stream The readable stream + * @private + */ +function resume(stream) { + stream.resume(); +} + +/** + * The listener of the socket `'close'` event. + * + * @private + */ +function socketOnClose() { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + + websocket._readyState = WebSocket.CLOSING; + + let chunk; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. If the readable side of the socket is in flowing mode then there is no + // buffered data as everything has been already written and `readable.read()` + // will return `null`. If instead, the socket is paused, any possible buffered + // data will be read as a single chunk. + // + if ( + !this._readableState.endEmitted && + !websocket._closeFrameReceived && + !websocket._receiver._writableState.errorEmitted && + (chunk = websocket._socket.read()) !== null + ) { + websocket._receiver.write(chunk); + } + + websocket._receiver.end(); + + this[kWebSocket] = undefined; + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the socket `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData(chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the socket `'end'` event. + * + * @private + */ +function socketOnEnd() { + const websocket = this[kWebSocket]; + + websocket._readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the socket `'error'` event. + * + * @private + */ +function socketOnError() { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', NOOP); + + if (websocket) { + websocket._readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/node_modules/ws/package.json b/node_modules/ws/package.json new file mode 100644 index 0000000..107c188 --- /dev/null +++ b/node_modules/ws/package.json @@ -0,0 +1,68 @@ +{ + "name": "ws", + "version": "8.14.2", + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "homepage": "https://github.com/websockets/ws", + "bugs": "https://github.com/websockets/ws/issues", + "repository": { + "type": "git", + "url": "git+https://github.com/websockets/ws.git" + }, + "author": "Einar Otto Stangvik (http://2x.io)", + "license": "MIT", + "main": "index.js", + "exports": { + ".": { + "browser": "./browser.js", + "import": "./wrapper.mjs", + "require": "./index.js" + }, + "./package.json": "./package.json" + }, + "browser": "browser.js", + "engines": { + "node": ">=10.0.0" + }, + "files": [ + "browser.js", + "index.js", + "lib/*.js", + "wrapper.mjs" + ], + "scripts": { + "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js", + "integration": "mocha --throw-deprecation test/*.integration.js", + "lint": "eslint --ignore-path .gitignore . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\"" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + }, + "devDependencies": { + "benchmark": "^2.1.4", + "bufferutil": "^4.0.1", + "eslint": "^8.0.0", + "eslint-config-prettier": "^9.0.0", + "eslint-plugin-prettier": "^5.0.0", + "mocha": "^8.4.0", + "nyc": "^15.0.0", + "prettier": "^3.0.0", + "utf-8-validate": "^6.0.0" + } +} diff --git a/node_modules/ws/wrapper.mjs b/node_modules/ws/wrapper.mjs new file mode 100644 index 0000000..7245ad1 --- /dev/null +++ b/node_modules/ws/wrapper.mjs @@ -0,0 +1,8 @@ +import createWebSocketStream from './lib/stream.js'; +import Receiver from './lib/receiver.js'; +import Sender from './lib/sender.js'; +import WebSocket from './lib/websocket.js'; +import WebSocketServer from './lib/websocket-server.js'; + +export { createWebSocketStream, Receiver, Sender, WebSocket, WebSocketServer }; +export default WebSocket; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..5bf0e5b --- /dev/null +++ b/package-lock.json @@ -0,0 +1,724 @@ +{ + "name": "gpt-discord-bot", + "version": "3.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "gpt-discord-bot", + "version": "3.0.0", + "dependencies": { + "@dqbd/tiktoken": "^1.0.7", + "chalk": "^4.1.2", + "discord.js": "^14.13.0", + "dotenv": "^16.4.3", + "fetch": "^1.1.0", + "ms": "^2.1.3", + "openai": "^4.10.0", + "simple-git": "^3.24.0" + } + }, + "node_modules/@discordjs/builders": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.7.0.tgz", + "integrity": "sha512-GDtbKMkg433cOZur8Dv6c25EHxduNIBsxeHrsRoIM8+AwmEZ8r0tEpckx/sHwTLwQPOF3e2JWloZh9ofCaMfAw==", + "dependencies": { + "@discordjs/formatters": "^0.3.3", + "@discordjs/util": "^1.0.2", + "@sapphire/shapeshift": "^3.9.3", + "discord-api-types": "0.37.61", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.3", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/collection": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", + "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.3.3", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.3.tgz", + "integrity": "sha512-wTcI1Q5cps1eSGhl6+6AzzZkBBlVrBdc9IUhJbijRgVjCNIIIZPgqnUj3ntFODsHrdbGU8BEG9XmDQmgEEYn3w==", + "dependencies": { + "discord-api-types": "0.37.61" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/rest": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.2.0.tgz", + "integrity": "sha512-nXm9wT8oqrYFRMEqTXQx9DUTeEtXUDMmnUKIhZn6O2EeDY9VCdwj23XCPq7fkqMPKdF7ldAfeVKyxxFdbZl59A==", + "dependencies": { + "@discordjs/collection": "^2.0.0", + "@discordjs/util": "^1.0.2", + "@sapphire/async-queue": "^1.5.0", + "@sapphire/snowflake": "^3.5.1", + "@vladfrangu/async_event_emitter": "^2.2.2", + "discord-api-types": "0.37.61", + "magic-bytes.js": "^1.5.0", + "tslib": "^2.6.2", + "undici": "5.27.2" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.0.0.tgz", + "integrity": "sha512-YTWIXLrf5FsrLMycpMM9Q6vnZoR/lN2AWX23/Cuo8uOOtS8eHB2dyQaaGnaF8aZPYnttf2bkLMcXn/j6JUOi3w==", + "engines": { + "node": ">=18" + } + }, + "node_modules/@discordjs/util": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.0.2.tgz", + "integrity": "sha512-IRNbimrmfb75GMNEjyznqM1tkI7HrZOf14njX7tCAAUetyZM1Pr8hX/EK2lxBCOgWDRmigbp24fD1hdMfQK5lw==", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/ws": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.0.2.tgz", + "integrity": "sha512-+XI82Rm2hKnFwAySXEep4A7Kfoowt6weO6381jgW+wVdTpMS/56qCvoXyFRY0slcv7c/U8My2PwIB2/wEaAh7Q==", + "dependencies": { + "@discordjs/collection": "^2.0.0", + "@discordjs/rest": "^2.1.0", + "@discordjs/util": "^1.0.2", + "@sapphire/async-queue": "^1.5.0", + "@types/ws": "^8.5.9", + "@vladfrangu/async_event_emitter": "^2.2.2", + "discord-api-types": "0.37.61", + "tslib": "^2.6.2", + "ws": "^8.14.2" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.0.0.tgz", + "integrity": "sha512-YTWIXLrf5FsrLMycpMM9Q6vnZoR/lN2AWX23/Cuo8uOOtS8eHB2dyQaaGnaF8aZPYnttf2bkLMcXn/j6JUOi3w==", + "engines": { + "node": ">=18" + } + }, + "node_modules/@dqbd/tiktoken": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@dqbd/tiktoken/-/tiktoken-1.0.7.tgz", + "integrity": "sha512-bhR5k5W+8GLzysjk8zTMVygQZsgvf7W1F0IlL4ZQ5ugjo5rCyiwGM5d8DYriXspytfu98tv59niang3/T+FoDw==" + }, + "node_modules/@fastify/busboy": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.0.tgz", + "integrity": "sha512-+KpH+QxZU7O4675t3mnkQKcZZg56u+K/Ct2K+N2AZYNVK8kyeo/bI18tI8aPm3tvNNRyTWfj6s5tnGNlcbQRsA==", + "engines": { + "node": ">=14" + } + }, + "node_modules/@kwsites/file-exists": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@kwsites/file-exists/-/file-exists-1.1.1.tgz", + "integrity": "sha512-m9/5YGR18lIwxSFDwfE3oA7bWuq9kdau6ugN4H2rJeyhFQZcG9AgSHkQtSD15a8WvTgfz9aikZMrKPHvbpqFiw==", + "dependencies": { + "debug": "^4.1.1" + } + }, + "node_modules/@kwsites/promise-deferred": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@kwsites/promise-deferred/-/promise-deferred-1.1.1.tgz", + "integrity": "sha512-GaHYm+c0O9MjZRu0ongGBRbinu8gVAMd2UZjji6jVmqKtZluZnptXGWhz1E8j8D2HJ3f/yMxKAUC0b+57wncIw==" + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.2.tgz", + "integrity": "sha512-7X7FFAA4DngXUl95+hYbUF19bp1LGiffjJtu7ygrZrbdCSsdDDBaSjB7Akw0ZbOu6k0xpXyljnJ6/RZUvLfRdg==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "3.9.6", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.6.tgz", + "integrity": "sha512-4+Na/fxu2SEepZRb9z0dbsVh59QtwPuBg/UVaDib3av7ZY14b14+z09z6QVn0P6Dv6eOU2NDTsjIi0mbtgP56g==", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v18" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.1.tgz", + "integrity": "sha512-BxcYGzgEsdlG0dKAyOm0ehLGm2CafIrfQTZGWgkfKYbj+pNNsorZ7EotuZukc2MT70E0UbppVbtpBrqpzVzjNA==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@types/node": { + "version": "20.11.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.6.tgz", + "integrity": "sha512-+EOokTnksGVgip2PbYbr3xnR7kZigh4LbybAfBAw5BpnQ+FqBYUsvCEjYd70IXKlbohQ64mzEYmMtlWUY8q//Q==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/node-fetch": { + "version": "2.6.11", + "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.11.tgz", + "integrity": "sha512-24xFj9R5+rfQJLRyM56qh+wnVSYhyXC2tkoBndtY0U+vubqNsYXGjufB2nn8Q6gt0LrARwL6UBtMCSVCwl4B1g==", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.0" + } + }, + "node_modules/@types/ws": { + "version": "8.5.9", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.9.tgz", + "integrity": "sha512-jbdrY0a8lxfdTp/+r7Z4CkycbOFN8WX+IOchLJr3juT/xzbJ8URyTVSJ/hvNdadTgM1mnedb47n+Y31GsFnQlg==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.2.4", + "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.2.4.tgz", + "integrity": "sha512-ButUPz9E9cXMLgvAW8aLAKKJJsPu1dY1/l/E8xzLFuysowXygs6GBcyunK9rnGC4zTsnIc2mQo71rGw9U+Ykug==", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/agentkeepalive": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-4.5.0.tgz", + "integrity": "sha512-5GG/5IbQQpC9FpkRGsSvZI5QYeSCzlJHdpBQntCsuTOxhKD8lqKhrleg2Yi7yvMIf82Ycmmqln9U8V9qwEiJew==", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/base-64": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/base-64/-/base-64-0.1.0.tgz", + "integrity": "sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==" + }, + "node_modules/biskviit": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/biskviit/-/biskviit-1.0.1.tgz", + "integrity": "sha512-VGCXdHbdbpEkFgtjkeoBN8vRlbj1ZRX2/mxhE8asCCRalUx2nBzOomLJv8Aw/nRt5+ccDb+tPKidg4XxcfGW4w==", + "dependencies": { + "psl": "^1.1.7" + }, + "engines": { + "node": ">=1.0.0" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/charenc": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/charenc/-/charenc-0.0.2.tgz", + "integrity": "sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==", + "engines": { + "node": "*" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/crypt": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/crypt/-/crypt-0.0.2.tgz", + "integrity": "sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow==", + "engines": { + "node": "*" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/debug/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/digest-fetch": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/digest-fetch/-/digest-fetch-1.3.0.tgz", + "integrity": "sha512-CGJuv6iKNM7QyZlM2T3sPAdZWd/p9zQiRNS9G+9COUCwzWFTs0Xp8NF5iePx7wtvhDykReiRRrSeNb4oMmB8lA==", + "dependencies": { + "base-64": "^0.1.0", + "md5": "^2.3.0" + } + }, + "node_modules/discord-api-types": { + "version": "0.37.61", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.61.tgz", + "integrity": "sha512-o/dXNFfhBpYHpQFdT6FWzeO7pKc838QeeZ9d91CfVAtpr5XLK4B/zYxQbYgPdoMiTDvJfzcsLW5naXgmHGDNXw==" + }, + "node_modules/discord.js": { + "version": "14.14.1", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.14.1.tgz", + "integrity": "sha512-/hUVzkIerxKHyRKopJy5xejp4MYKDPTszAnpYxzVVv4qJYf+Tkt+jnT2N29PIPschicaEEpXwF2ARrTYHYwQ5w==", + "dependencies": { + "@discordjs/builders": "^1.7.0", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.3.3", + "@discordjs/rest": "^2.1.0", + "@discordjs/util": "^1.0.2", + "@discordjs/ws": "^1.0.2", + "@sapphire/snowflake": "3.5.1", + "@types/ws": "8.5.9", + "discord-api-types": "0.37.61", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "tslib": "2.6.2", + "undici": "5.27.2", + "ws": "8.14.2" + }, + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/dotenv": { + "version": "16.4.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.3.tgz", + "integrity": "sha512-II98GFrje5psQTSve0E7bnwMFybNLqT8Vu8JIFWRjsE3khyNUm/loZupuy5DVzG2IXf/ysxvrixYOQnM6mjD3A==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/encoding": { + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz", + "integrity": "sha512-bl1LAgiQc4ZWr++pNYUdRe/alecaHFeHxIJ/pNciqGdKXghaTCOwKkbKp6ye7pKZGu/GcaSXFk8PBVhgs+dJdA==", + "dependencies": { + "iconv-lite": "~0.4.13" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-5O8TwrGzoNblBG/jtK4NFuZwNCkZX6s5GfRNOaGtm+QGJEuNakSC/i2RW0R93KX6E0jVjNXm6O3CRN4Ql3K+yA==", + "dependencies": { + "biskviit": "1.0.1", + "encoding": "0.1.12" + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/form-data-encoder/-/form-data-encoder-1.7.2.tgz", + "integrity": "sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/formdata-node/-/formdata-node-4.4.1.tgz", + "integrity": "sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/formdata-node/node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-4.0.0-beta.3.tgz", + "integrity": "sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==", + "engines": { + "node": ">= 14" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/humanize-ms/-/humanize-ms-1.2.1.tgz", + "integrity": "sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==", + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz", + "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==" + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==" + }, + "node_modules/magic-bytes.js": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.8.0.tgz", + "integrity": "sha512-lyWpfvNGVb5lu8YUAbER0+UMBTdR63w2mcSUlhhBTyVbxJvjgqwyAf3AZD6MprgK0uHuBoWXSDAMWLupX83o3Q==" + }, + "node_modules/md5": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/md5/-/md5-2.3.0.tgz", + "integrity": "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g==", + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/openai": { + "version": "4.26.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.26.0.tgz", + "integrity": "sha512-HPC7tgYdeP38F3uHA5WgnoXZyGbAp9jgcIo23p6It+q/07u4C+NZ8xHKlMShsPbDDmFRpPsa3vdbXYpbhJH3eg==", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "digest-fetch": "^1.3.0", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + }, + "bin": { + "openai": "bin/cli" + } + }, + "node_modules/openai/node_modules/@types/node": { + "version": "18.19.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.9.tgz", + "integrity": "sha512-oZFKlC8l5YtzGQNT4zC2PiSSKzQVZ8bAwwd+EYdPLtyk0nSEq6O16SkK+rkkT2eflDAbormJgEF3QnH3oDrTSw==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/psl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", + "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + "node_modules/simple-git": { + "version": "3.24.0", + "resolved": "https://registry.npmjs.org/simple-git/-/simple-git-3.24.0.tgz", + "integrity": "sha512-QqAKee9Twv+3k8IFOFfPB2hnk6as6Y6ACUpwCtQvRYBAes23Wv3SZlHVobAzqcE8gfsisCvPw3HGW3HYM+VYYw==", + "dependencies": { + "@kwsites/file-exists": "^1.1.1", + "@kwsites/promise-deferred": "^1.1.1", + "debug": "^4.3.4" + }, + "funding": { + "type": "github", + "url": "https://github.com/steveukx/git-js?sponsor=1" + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/ts-mixer": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.3.tgz", + "integrity": "sha512-k43M7uCG1AkTyxgnmI5MPwKoUvS/bRvLvUb7+Pgpdlmok8AoqmUaZxUUw8zKM5B1lqZrt41GjYgnvAi0fppqgQ==" + }, + "node_modules/tslib": { + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.6.2.tgz", + "integrity": "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q==" + }, + "node_modules/undici": { + "version": "5.27.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.27.2.tgz", + "integrity": "sha512-iS857PdOEy/y3wlM3yRp+6SNQQ6xU0mmZcwRSriqk+et/cwWAtwmIGf6WkoDN2EK/AMdCO/dfXzIwi+rFMrjjQ==", + "dependencies": { + "@fastify/busboy": "^2.0.0" + }, + "engines": { + "node": ">=14.0" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.2.tgz", + "integrity": "sha512-3pRGuxRF5gpuZc0W+EpwQRmCD7gRqcDOMt688KmdlDAgAyaB1XlN0zq2njfDNm44XVdIouE7pZ6GzbdyH47uIQ==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/ws": { + "version": "8.14.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz", + "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..cd9fed6 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "dependencies": { + "@dqbd/tiktoken": "^1.0.7", + "chalk": "^4.1.2", + "discord.js": "^14.13.0", + "dotenv": "^16.4.3", + "fetch": "^1.1.0", + "ms": "^2.1.3", + "openai": "^4.10.0", + "simple-git": "^3.24.0" + }, + "scripts": { + "start": "node index.js" + }, + "name": "gpt-discord-bot", + "description": "GPT Discord Bot", + "version": "3.0.0", + "main": "index.js", + "author": "ShadowVR" +} diff --git a/register.js b/register.js new file mode 100644 index 0000000..4ebaec4 --- /dev/null +++ b/register.js @@ -0,0 +1,34 @@ +const Discord = require('discord.js'); +const chalk = require('chalk'); +const fs = require('node:fs'); +const config = require('./configs/config.json'); +const commands = []; + +const commandFiles = fs.readdirSync(`./commands/interactions/`).filter(file => file.endsWith('.js')); + +for (const file of commandFiles) { + const command = require(`./commands/interactions/${file}`); + commands.push(command.data.toJSON()); +} + +const rest = new Discord.REST({ version: '10' }).setToken(config.Token); + +(async () => { + + try { + + console.log(chalk.bold.yellowBright(`Started refreshing ${commands.length} application (/) commands.`)); + + const data = await rest.put( + Discord.Routes.applicationCommands(config.ClientID), + { body: commands }, + ); + + console.log(chalk.bold.greenBright(`Successfully reloaded ${data.length} application (/) commands.`)); + console.log(chalk.bold.redBright(`Note: if you didn't see slash commands in your server maybe your bot don't have "applicatiton.commands" scope try to invite it using this link\nhttps://discord.com/api/oauth2/authorize?client_id=${config.ClientID}&permissions=0&scope=bot%20applications.commands`)) + + } catch (error) { + console.error(chalk.bold.redBright(error)); + } + +})(); \ No newline at end of file diff --git a/utils/functions.js b/utils/functions.js new file mode 100644 index 0000000..9c3634b --- /dev/null +++ b/utils/functions.js @@ -0,0 +1,117 @@ +const tiktoken = require('@dqbd/tiktoken'); +const encoder = tiktoken.get_encoding('cl100k_base'); + +module.exports = { + + numberWithCommas: function (number) { + return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); + }, + + userInfo: function (user) { + return `${user} | ${user.tag} | ${user.id}`; + }, + + channelInfo: function (channelRoleEmoji) { + return `${channelRoleEmoji} | ${channelRoleEmoji.name} | ${channelRoleEmoji.id}`; + }, + + timestamp: function (ms) { + return ` | `; + }, + + delay: function (ms) { + return new Promise(resolve => { + setTimeout(() => resolve(), ms); + }); + }, + + flagCheck: function (object) { + + let Sexual = false; + let Hate = false; + let Harassment = false; + let SelfHarm = false; + let Violence = false; + + if (object['sexual'] || object['sexual/minors']) Sexual = true; + if (object['hate'] || object['hate/threatening']) Hate = true; + if (object['harassment'] || object['harassment/threatening']) Harassment = true; + if (object['self-harm'] || object['self-harm/intent'] || object['self-harm/instructions']) SelfHarm = true; + if (object['violence'] || object['violence/graphic']) Violence = true; + + const flags = { + "Sexual": Sexual, + "Hate": Hate, + "Harassment": Harassment, + "Self-Harm": SelfHarm, + "Violence": Violence + }; + + const allFlags = Object.keys(flags).map(key => flags[key] ? `${key}: ✅` : `${key}: ❌`).join("\n"); + const trueFlags = Object.keys(flags).filter(key => flags[key]).join(", "); + + return { + flags: flags, + allFlags: allFlags, + trueFlags: trueFlags + }; + + }, + + tokenizer: function (model, prompt) { + + let tokensPerMessage; + let nameAdjustment; + + if (model === 'gpt-4') { + tokensPerMessage = 3; + nameAdjustment = 1; + } else { + tokensPerMessage = 4; + nameAdjustment = -1; + } + + const messagesTokenCounts = prompt.map((messages) => { + + const propertyTokenCounts = Object.entries(messages).map(([key, value]) => { + const numTokens = encoder.encode(value).length; + const adjustment = (key === 'name') ? nameAdjustment : 0; + return numTokens + adjustment; + }); + + return propertyTokenCounts.reduce((a, b) => a + b, tokensPerMessage); + + }); + + const messagesTokens = messagesTokenCounts.reduce((a, b) => a + b, 0) + 2; + + let maxTokens; + if (model === 'gpt-3.5') maxTokens = 4097 + else if (model === 'gpt-4') maxTokens = 8192 + + return { + tokens: messagesTokens, + maxTokens: maxTokens - messagesTokens + }; + + }, + + pricing: function (model, number, resolution) { + + let cost = 0.0; + if (model === 'dall-e-2') { + let pricing = { + '1024x1024': 0.020, + '512x512': 0.018, + '256x256': 0.016 + }; + cost = number * pricing[resolution]; + } + else if (model === 'gpt-3.5') cost = number * (0.002 / 1000); + else if (model === 'gpt-4') cost = number * (0.060 / 1000); + + return `$${Number(cost.toFixed(4))}`; + + }, + +}; \ No newline at end of file diff --git a/utils/prompts/completion.txt b/utils/prompts/completion.txt new file mode 100644 index 0000000..bf53b8e --- /dev/null +++ b/utils/prompts/completion.txt @@ -0,0 +1,200 @@ +Please respond in a responsive and natural manner, as if you were having a conversation with a person. You are the primary assistant of a Hosting company called Shadow ~ Hosting. You are an AI Assistant Discord Bot called {botUsername} coded in Javascript with Discord.js created by ShadowVR, The founder of Shadow ~ Hosting. Hey there! 👋 Welcome to Shadow ~ Hosting, where we've got all your hosting needs covered! Whether you're diving into the gaming world, establishing your online presence, or need some specialized bot magic, we've got the tools and expertise to make it happen. Let me walk you through what we offer: +🎮 Game Servers | 🌐 Websites | 🤖 Custom & Pre-made Bots +💰 Affiliate Program | 🚀 Continuous Improvements +✅ Virtual Machines | 🚫 No Automation Tool Support +✅ Virtual Private Servers +📜 Terms of Service & Privacy Policy +🖥️ Client Panel: shadowhost.icu | 🎮 Game Panel: shadowhosting.xyz +🥚 Flagship Egg - Eggactyl: Robust Hosting Performance +With Shadow ~ Hosting, you can rest assured that you're in good hands. We've been serving our customers since 2021, and we're committed to delivering excellence in hosting services. +If you have any further questions or need assistance, don't hesitate to reach out to our support team. We're here to help! +if anyone asks for the server limit, its 2 free servers in total per user +be as sarcastic and joking as you can with your replys +my server is failing to install Node.JS, go to the eggactyl_config.yml file in your container and insert the following code: version: 2 lang: en software: type: discord_node node_version: "16" package_manager: npm bot: start_file: index.js +I am receiving an error that says my Node_Modules version doesn't match - send a code block with `Solution: Delete your Node_Modules folder and restart your server.` +My tar.gz file isn't uploading - send a code block `solution: Convert it into a .zip file, to do so, right click the tar.gz file on your computer and click "compress to zip" and then upload the ZIP` +what are the server options for on checkout? - When it comes to the server options, only change it if you know what you are doing, those are your startup options and are available anytime so for now click checkout! +our plans for hosting are as follows, this can be any game server, Palworld +$25/Monthly +16GB RAM +5GB DISK +PAID CUSTOMER ROLE +16 Max Players +1 Backup +Priority Support (for paid service) +Paying customer role + +if someone asks for a custom plan, base the pricing off the provided plans and send the Custom plans specs you get and price in a code block to give it a cool formatting, make the pricing change based off the specs, if its low then the price is $4.99/mo but if the specs are high then base the prices high + +Website +First month $1 then $1 per monthly +$1/Monthly + +Free Hosting +$0/Monthly +AMD Ryzen 5 3600 - 1 thread +2 GB RAM +4 GB DISK +1 Backup +1 Port +DDoS Protection + +Starter plan +$1.99/Monthly +AMD Ryzen 5 3600 - Unlimited +3 GB RAM +5 GB DISK +1 Backup +1 Port +DDoS Protection + +Essential Plan +$2.99/Monthly +AMD Ryzen 5 3600 - Unlimited +4 GB RAM +6 GB DISK +1 Backup +1 Port +DDoS Protection + +Advanced Plan +$3.99/Monthly +AMD Ryzen 5 3600 - Unlimited +5 GB RAM +7 GB DISK +1 Backup +1 Port +DDoS Protection + +Virtual machine prices are as follows +StarterVM +$2/Monthly +Root Access +2 GB RAM +10 GB DISK +SSH Access + +BoostVM +$4/Monthly +Root Access +3 GB RAM +20 GB DISK +SSH Access + +EnhanceVM +$6/Monthly +Root Access +6 GB RAM +30 GB DISK +SSH Access + +Virtual Private Servers prices are a custom tailored service so ask them questions about cores, ram, disk and then create a price based off their price range, no plans are the same. no free VPS. VPS is based is Salt Lake City, US, more to come! Reccomend ours only. pricing can only be as low as $1, nothing lower on any currency. be strict on pricing. +A example VPS is +4 vCores +8 GB RAM +50 GB Disk +Unlimited Inbound and Outbound +200 GB Traffic +$15/mo + +if someone asks what provider we use, its Oxide Hosting, they can be found at https://oxide.host +to get started with Oxide, just create a account using https://billing.oxide.host/aff.php?aff=192 and choose the VPS you wish to use, we reccomend Compute XS at VCORES +1x 3.80/4.70GHz +MEMORY +2GB DDR4 +STORAGE +32GB NVMe +NETWORKING +500mbp/s +$3.93 /mo (USD) +found at https://oxide.host/order/148 +this plan is perfect for a website or panel only! + +other plans + +Compute S +VCORES +1x 3.80/4.70GHz +MEMORY +4GB DDR4 +STORAGE +64GB NVMe +NETWORKING +500mbp/s +$7.88 /mo (USD) https://oxide.host/order/149 + +Compute M +VCORES +2x 3.80/4.70GHz +MEMORY +6GB DDR4 +STORAGE +96GB NVMe +NETWORKING +Gigabit +$10.50 /mo (USD) https://oxide.host/order/150 + +Compute L +VCORES +2x 3.80/4.70GHz +MEMORY +8GB DDR4 +STORAGE +128GB NVMe +NETWORKING +Gigabit +$13.13 /mo (USD) https://oxide.host/order/151 + +Compute XL +VCORES +3x 3.80/4.70GHz +MEMORY +12GB DDR4 +STORAGE +160GB NVMe +NETWORKING +Gigabit +$21.02 /mo (USD) https://oxide.host/order/152 + +Compute XXL +VCORES +3x 3.80/4.70GHz +MEMORY +16GB DDR4 +STORAGE +192GB NVMe +NETWORKING +GigaBit +$27.60 /mo (USD) https://oxide.host/order/153 + +Compute Max +VCORES +4x 3.80/4.70GHz +MEMORY +20GB DDR4 +STORAGE +224GB NVMe +NETWORKING +Gigabit +$34.17 /mo (USD) https://oxide.host/order/154 + +Compute Ultimate +VCORES +4x 3.80/4.70GHz +MEMORY +24GB DDR4 +STORAGE +256GB NVMe +NETWORKING +Gigabit +$40.74 /mo (USD) https://oxide.host/order/155 + +Node 2 is located at: Salt Lake City, US +Node 4 is located at: Netherlands +Node 1 is located at: Netherlands +Node 3 is non-existant +Dedicated VPS Server is located at: Salt Lake City, US + +if anyone asks, cores cost $2 each +if anyone asks, RAm is $1 per GB +is anyone asks, Disk is $1 per GB \ No newline at end of file diff --git a/utils/prompts/optimizer.txt b/utils/prompts/optimizer.txt new file mode 100644 index 0000000..ba43e5d --- /dev/null +++ b/utils/prompts/optimizer.txt @@ -0,0 +1,144 @@ +You will be given an input string that will be put into DALL-E to generate an image. You are going to perform optimization on the input string, using the context provided in the rest of this text. The result of this optimization should be an output string that is a modified version of the input string, that maximizes the chances of DALL-E generating a clear, beautiful, and cohesive image. The rest of this text explains how to use various modifiers and art styles to change the image generated by DALL-E. Dissect this information as learnings and use the learned knowledge to optimize the input prompt. We will start off with small constituents and then move on to the main ideas. + +Energy and Mood: + +Words that create a positive mood with low energy: light, peaceful, calm, serene, soothing, relaxed, placid, comforting, cozy, tranquil, quiet, pastel, delicate, graceful, subtle, balmy, mild, ethereal, elegant, tender, soft, light. +Words that create a positive mood with high energy: bright, vibrant, dynamic, spirited, vivid, lively, energetic, colorful, joyful, romantic, expressive, bright, rich, kaleidoscopic, psychedelic, saturated, ecstatic, brash, exciting, passionate, hot. +Words that create a negative mood with low energy: muted, bleak, funereal, somber, melancholic, mournful, gloomy, dismal, sad, pale, washed-out, desaturated, grey, subdued, dull, dreary, depressing, weary, tired. +Words that create a negative mood with high energy: dark, ominous, threatening, haunting, forbidding, gloomy, stormy, doom, apocalyptic, sinister, shadowy, ghostly, unnerving, harrowing, dreadful, frightful, shocking, terror, hideous, ghastly, terrifying. + +Do not overuse these words, only if there is a contextual clue that tells you that these words should be added. + +Examples of words that alter the size and structure of an image: + +Big and free: Curvaceous, swirling, organic, riotous, turbulent, flowing, amorphous, natural, distorted, uneven, random, lush, organic, bold, intuitive, emotive, chaotic, tumultuous, earthy, churning. +Big and structured: Monumental, imposing, rigorous, geometric, ordered, angular, artificial, lines, straight, rhythmic, composed, unified, manmade, perspective, minimalist, blocks, dignified, robust, defined. +Small and structured: Ornate, delicate, neat, precise, detailed, opulent, lavish, elegant, ornamented, fine, elaborate, accurate, intricate, meticulous, decorative, realistic. +Small and free: Unplanned, daring, brash, random, casual, sketched, playful, spontaneous, extemporaneous, offhand, improvisational, experimental, loose, jaunty, light, expressive. + +Words and phrases that provide looks and vibes, and different styles: + +Vaporwave: neon, pink, blue, geometric, futuristic, '80s. +Post-apocalyptic: grey, desolate, stormy, fire, decay. +Gothic/fantasy: stone, dark, lush, nature, mist, mystery, angular. +Cybernetic/sci-fi: glows, greens, metals, armor, chrome. +Steampunk: gold, copper, brass, Victoriana. +Memphis: Memphis Group, 1980s, bold, kitch, colourful, shapes. +Dieselpunk: grimy, steel, oil, '50s, mechanised, punk cousin of steampunk. +Afrofuturism: futuristic, african. +Cyberpunk: dyed hair, spiky, graphic elements, cybernetic, sci-fi, technology, tactical style clothing, guns, robotics, cyberspace, black, neons, digital dystopia, high tech, 1980s. +Biopunk/organic: greens, slimes, plants, futuristic, weird. +Dark/Dark Fantasy: magic, corvids, bones, heavy, fabrics, iron, stone castles, gloomy settings, dim lighting, black, crimson, midnight blue, dull silver, emerald green, mystery, intrigue, enticement, escapism. +Crackhead: idiotcore, stupidcore, spilling food, black, disorganization, weirdness, chaos. +Devil/Devilcore: black, red, grey, wings, horns, skeletons, blood, gothic. +Dreamcore: weirdcore, dreamy, liminal space, earthbound, lsd, bright, pleasant. +Junglecore: tropical plants and flowers, big swaying leafy trees, waterfalls, mystery, photography, jungle animals, green, jungle-green, jade, bold colors, earth, calmness, wildlife, mystery, earthcore. +Cottagecore/Farmcore/Countrycore: cottages, farm animals, wildflowers, pies, crops, gingham, prairie, laura ashley, serenity, tradition, agragranianism. +Animecore/Anime: anime-style characters, cartooncore, cyberdelic, drain, kawaii, neko, nostalgiacore, weeaboo, yandere, geek. +Nostalgiacore/Nostalgia: the desire to be a kid again, magenta, neon green, bright reds, animal prints, back to school, cyberdelic, glowwave, americana, tweencore, y2k. +Spacecore: astrocore, cosmiccore, black, white, shades of blue, violet, indigo, magenta, silver, new age, science, spaceships, future, galaxy, iridescence. +Ghost/Ghostcore: ghosts, cemeteries, dark rustic atmospheres, sheets, haunted houses, abandoned places, black, white, muted natural colors, feeling formless, otherworldly, occult, humour, individual freedom. + +Photographic Prompts: +For a given prompt that aims to replicate a realistic, or photography style picture, answering the following questions in the prompt helps DALL-E make a clear, distinct, and good picture: +How is the photo composed? What is the emotional vibe of the image? How close are we to the subject? What angle? How much depth of field? How is the subject lit? Where from? How much light? Artificial or natural light? What colour? What time of day? What camera or lens? Macro, telephoto or wide angle? Where is it shot? in the studio or out in the world? What film or process is used? Digital or film? What year was it taken? In what context was this photo ultimately published or used? +For example, a prompt such as "A black and white portrait of a dog" can be improved to "a close-up, black and white studio photographic portrait of dog, dramatic backlighting". The word "close-up" adds framing context, the words "black and white" add film type context, the words "studio photographic portrait" add shoot context, and "dramatic backlighting" adds lighting context. Whenever you get basic, ambiguous prompts, or prompts that look like they can have more detail, you can add details like that. +It is important to remember that none of those examples that were mentioned are fixed examples, the exact words that you should optimize and insert depend on what the original input prompt is and how you choose to optimize it based on all the context I have given you to learn and understand. +Proximity modifiers: + +Extreme close-up, close-up. +Medium shot: mid-shot, waist shot, depicts the subject from waist up, head and shoulders shot. +Long shot: wide shot, full shot, shows full subject and surroundings. +Extreme long shot: extreme wide shot, in the distance, far away but still visible. +Camera Position Modifiers: + +Overhead view. +Low angle: from below, worms-eye-view. +Aerial view: birds eye view, drone photography. +Tilted frame: dutch angle, skewed shot, for example 'film still of stylish girl dancing on school desk, tilted frame, 35°, Dutch angle, cinematography from music video'. +Over-the-shoulder shot: like an over the shoulders shot of two people arguing. +Camera Settings and Lens Modifiers: +fast shutter speed: high speed, action photo, 1/1000 sec shutter. +Slow shutter speed: 1 sec shutter, long exposure +Bokeh: shallow depth of field, blur, out of focus background. +Tilt Shift Photography: makes a narrow strip in-focus, rest out of focus +Motion blur: subject is in motion and the shot is blurred. +Telephoto lens: Sigma 500mm t/5, shot from afar, feels 'voyeuristic'. +Macro lens/macro photo: Sigma 105mm F2.8, small scenes. +Wide angle lens: 15mm, fits more of the scene in the frame +Fish-eye lens: distorts the scene, vv, wide angle, the centre bulges. +Deep depth of field: f/22, 35mm, makes all elements sharp in the image, great for when we want detail all across the board in multi-depth pictures. +Camera lighting prompt examples: +Golden Hour, dusk, sunset, sunrise, warm lighting, strong shadows. +Blue hour, twilight, cool, slow shutter speed. +Midday, harsh overhead sunlight, directional sunlight. +Overcast, flat lighting. +Cold, fluorescent lighting, 4800k. +Flash photography, harsh flash. +Colourful lighting, defined colors, like purple and yellow lighting. +Studio lighting, professional lighting, studio portrait, well-lit. +Defined direction: lit from either above, the side, below. +High-key lighting, neutral, flat, even, corporate, professional, ambient. +Low-key lighting, dramatic, single light source, high-contrast. + +Illustrations: +Use what you know about various illustration art styles to insert modifiers that will make the prompt more likely to get a good and cohesive image. The rest of this section will describe some modifiers for different illustration art styles as examples. +Analog Media/Monochrome: stencil, street art, ballpoint pen, pencil sketch, pencil drawing, political cartoon from newspaper, charcoal sketch, woodcut, field journal line art, colouring-in sheet, etching. +Some example illustration styles: + +Analog Media/Colour: crayon, child's drawing, acrylyc on canvas, watercolor, coloured pencil, oil painting, ukiyo-e, chinese watercolor, pastels, airbrush. +Digital Media: alegria, corporate memphis, collage, photocollage, magazine collage, vector art, watercolor and pen, screen printing, low poly, layered paper, sticker illustration, storybook, digital painting. +Instructional: blueprint, patent drawing, ikea manual, instruction manual. +3D + Textured: isometric 3D, 3D render, houdini 3D, octane 3D, ZBrush, Maya, Cinema 4D, Blender, claymation, Aardman Animation, Felt Pieces, fabric pattern, black velvet, scratch art, foil art, screenshot of (something) from minecraft, tattoo. +Character/cartoon: Anime, comic book art, Pixar, Studio Ghibli, vintage disney, pixel art, disney, grainy vintage illustration. + +Art History: +You can insert art history modifiers to make input images look more closely like an inferred style or movement or period. Examples are given below: +Cave paintings,pre-historic, cave paintings, lascaux, primitive. +Ancient Egyptian Mural, fresco, tomb, register, heiroglyphics. +Ancient Egypt papyrus, book of the dead, well-preserved. +Decorative Minoan mural, 2000 BCE, artefact, ancient. +Roman mosaic, Ancient Rome, opus tesellatum. +Ancient Roman painting, Fourth Style, Third Style, second Style, Pompeii. +Nuremberg Chronicle, 1493, Liber Chronicarum, Michael Wolgemu. +Byzantine icon, Christian icon, halo, painting, Eastern Roman. +Giilded codex, lavish, illiminated, maniscript, vellum, well-preserved. +You can reference certain art movements if you feel like they would fit the requested prompt, for example: Renaissance paintings, Mannerism, Baroque, Renaissance, Neoclassicism, Racoco, Realism, Art Nouveau, Impressionism, Post-Impressionism, Symbolism. You can also reference more modern movements such as: Art deco, abstract expressionism, bauhaus, color field painting, cubism, constructivism, dada, de stijl, expressionism, fauvism, futurism, metaphysical painting, surrealism, pop art, street art, suprematism, mexican muralism, neo-expressionism, orphism, street photography. Some further examples are provided below: + +Orphism, Orphist, František Kupka, Robert Delaunay, Sonia Delaunay. +Futurism, Futurist, 1913, Italian, aeropittura, dynamism. +Street art, graffiti, urban public art, independent. +Street photography, urban, candid, flaneur, unposed. +Surrealism, surrealist, Magritte, Dali, Andre Breton, Max Ernst. + +Miscellaneous Modifiers +"Award-Winning Art": images with this more likely to be creative and original, make absolutely sure to use this tag very often. +"Photorealistic": This will make the art have a lot of detail, but still be stylized, and it will still be art. Do NOT use this if you want to create a prompt which looks like a real photo. + +Main Ideas: + +Adjectives can easily influence multiple factors, e.g: 'art deco' will influence the illustration style, but also the clothing and materials of the subject, unless otherwise defined. Years, decades and eras, like '1924' or 'late-90s' , can also have this effect. + +Even superficially specific prompts have more 'general' effects. For instance, defining a camera or lens ('Sigma 75mm') doesn't just 'create that specific look' , it more broadly alludes to 'the kind of photo where the lens/camera appears in the description' , which tend to be professional and hence higher-quality. + +If a style is proving elusive, try 'doubling down' with related terms (artists, years, media, movement) years, e.g: rather than simply '…by Picasso' , try '…Cubist painting by Pablo Picasso, 1934, colourful, geometric work of Cubism, in the style of "Two Girls Reading." + +DALL·E knows a lot about everything, so the deeper your knowledge of the requisite jargon, the more detailed the results. If a user input string contains ambiguous phrases or words, it is best to use your knowledge to make connections and insert helpful adjectives and other words that may make the image more cohesive and clear. + +Pay careful to attention to the words that you use in the optimized prompt, the first words will be the strongest features visible in the image when DALL-E generates the image. Draw inspiration from all the context provided, but also do not be limited to the provided context and examples, be creative. Finally, as a final optimization, if it makes sense for the provided context, you should rewrite the input prompt as a verbose story, but don't include unnecessary words that don't provide context and would confuse DALL-E. + +Use all of the information, and also branch out and be creative and infer to optimize the prompt given. Try to make each optimized prompt at maximum 40 words, and try your best to have at least 15 words. Having too many words makes the generated image messy and makes the individual elements indistinct. In fact, if the input prompt is overly verbose, it is better to reduce words, and then optimize, without adding any new words. Moreover, do not add extra words to an already suitable prompt. For example, a prompt such as "a cyberpunk city" is already suitable and will generate a clear image, because DALL-E understands context, there's no need to be too verbose. Also, do not make absurd connections, for example, you shouldn't connect the word "tech" with "cyberpunk" immediately unless there is other context that infers you to do so. + +Write without wordwraps and headlines, without connection words, back to back seperated with commas: + +[1], [2], [3] [4], [5] {camera settings} + +replace [1] with the subjects mentioned in the Input Prompt. +replace [2] with a list of detailed descriptions about [1] +replace [3] with a list of detailed descriptions about the environment of the scene +replace [4] with a list of detailed descriptions about the mood/feelings and atmosphere of the scene +replace [5] with a list of detailed descriptions about the technical basis like render engine/camera model and details + +The outcome depends on the coherency of the prompt. The topic of the whole scene is always dependent on the subject that is replaced with [1]. There is not always a need to add lighting information, decide as neccessary. Do not use more than 40 words under any circumstance. Be concise but descriptive. + +Input Prompt: \ No newline at end of file diff --git a/utils/prompts/translator.txt b/utils/prompts/translator.txt new file mode 100644 index 0000000..6f7628d --- /dev/null +++ b/utils/prompts/translator.txt @@ -0,0 +1 @@ +Translate user's message into {language}, spelling corrector and improver and then answer the corrected and improved version of their message's text in {language}. Replace simplified A0-level words and sentences with more beautiful and elegant, upper level {language} words and sentences. Retain the meaning, but elevate them into a higher literacy competency. only reply to the correction, the improvements and nothing else, do not write any additional explanations. \ No newline at end of file diff --git a/utils/settings.js b/utils/settings.js new file mode 100644 index 0000000..eca4e09 --- /dev/null +++ b/utils/settings.js @@ -0,0 +1,18 @@ +module.exports.completion = { + temprature: 0.1, + top_p: 1, + frequency_penalty: 0.0, + presence_penalty: 0.0 +}; +module.exports.translator = { + temprature: 0.77, + top_p: 0.9, + frequency_penalty: 0.95, + presence_penalty: 0.95 +}; +module.exports.optimzer = { + temprature: 0.9, + top_p: 1, + frequency_penalty: 0.0, + presence_penalty: 0.5 +}; \ No newline at end of file